diff --git a/AGENTS.md b/AGENTS.md
index dbc9c85..3ff269a 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -16,6 +16,9 @@ If you are an AI coding agent or an autonomous tool reading this for orientation
| --- | --- |
| DApp integration in the browser (TIP-6963 / `eth_requestAccounts` / `tronWeb`) | [docs/dapp/getting-started.en.md](docs/dapp/getting-started.en.md) + [docs/plugin-wallet/*](docs/plugin-wallet/) |
| Mobile DeepLink (`tronlinkoutside://`) | [docs/mobile/deeplink.en.md](docs/mobile/deeplink.en.md) |
+| Android wallet core | [docs/mobile/android-core.en.md](docs/mobile/android-core.en.md) |
+| iOS wallet core | [docs/mobile/ios-core.en.md](docs/mobile/ios-core.en.md) |
+| Browser extension wallet core | [docs/plugin-wallet/extension-core.en.md](docs/plugin-wallet/extension-core.en.md) |
| AI-agent tooling overview | [docs/ai-support/ai-llms.en.md](docs/ai-support/ai-llms.en.md) |
| MCP server (production) | [docs/ai-support/mcp-server-tronlink.en.md](docs/ai-support/mcp-server-tronlink.en.md) |
| MCP framework / SSOT error codes | [docs/ai-support/tronlink-mcp-core.en.md](docs/ai-support/tronlink-mcp-core.en.md) |
diff --git a/docs/AGENTS.txt b/docs/AGENTS.txt
index bb7c1b7..4c47263 100644
--- a/docs/AGENTS.txt
+++ b/docs/AGENTS.txt
@@ -16,6 +16,9 @@ If you are an AI coding agent or an autonomous tool reading this for orientation
| --- | --- |
| DApp integration in the browser (TIP-6963 / `eth_requestAccounts` / `tronWeb`) | [docs.tronlink.org/dapp/getting-started/](https://docs.tronlink.org/dapp/getting-started/) + [docs.tronlink.org/plugin-wallet/*](https://docs.tronlink.org/plugin-wallet/active-requests/) |
| Mobile DeepLink (`tronlinkoutside://`) | [docs.tronlink.org/mobile/deeplink/](https://docs.tronlink.org/mobile/deeplink/) |
+| Android wallet core | [docs.tronlink.org/mobile/android-core/](https://docs.tronlink.org/mobile/android-core/) |
+| iOS wallet core | [docs.tronlink.org/mobile/ios-core/](https://docs.tronlink.org/mobile/ios-core/) |
+| Browser extension wallet core | [docs.tronlink.org/plugin-wallet/extension-core/](https://docs.tronlink.org/plugin-wallet/extension-core/) |
| AI-agent tooling overview | [docs.tronlink.org/ai-support/ai-llms/](https://docs.tronlink.org/ai-support/ai-llms/) |
| MCP server (production) | [docs.tronlink.org/ai-support/mcp-server-tronlink/](https://docs.tronlink.org/ai-support/mcp-server-tronlink/) |
| MCP framework / SSOT error codes | [docs.tronlink.org/ai-support/tronlink-mcp-core/](https://docs.tronlink.org/ai-support/tronlink-mcp-core/) |
diff --git a/docs/ai-support/mcp-server-tronlink.en.md b/docs/ai-support/mcp-server-tronlink.en.md
index 81eaab4..5bf2046 100644
--- a/docs/ai-support/mcp-server-tronlink.en.md
+++ b/docs/ai-support/mcp-server-tronlink.en.md
@@ -8,7 +8,7 @@
**Key Highlights:**
- Dual-mode architecture: **Playwright** (browser automation) + **Direct API** (on-chain operations)
-- 32 built-in Flow Recipes with pre-checks and dependency resolution
+- 24 built-in Flow Recipes with pre-checks and dependency resolution
- Non-custodial local transaction signing via encrypted `agent-wallet`
- Multi-signature management with real-time WebSocket monitoring
- Gas-free TRC20 transfers via GasFree service integration
@@ -27,7 +27,7 @@ flowchart TD
Multi["TronLinkMultiSigCapability (5 tools)"]
GasFree["TronLinkGasFreeCapability (3 tools)"]
Util["Utility Capabilities
Build · StateSnapshot · TRON Crypto"]
- Flow["Flow Recipes
(32 built-in, pre-checked)"]
+ Flow["Flow Recipes
(24 built-in, pre-checked)"]
Ext["TronGrid API / Multi-Sig Service / GasFree Service"]
Chain["TRON Blockchain"]
Agent -- "MCP Protocol — stdio / JSON-RPC 2.0" --> Server
@@ -174,11 +174,13 @@ Uses `@noble/curves` (secp256k1 ECDSA) and `@noble/hashes` (Keccak-256, SHA256).
---
-## Flow Recipes (32 Built-In)
+## Flow Recipes (24 Built-In) {#flow-recipes}
Pre-configured multi-step workflows with dependency checks and parameter templates.
-### Playwright Flows
+Call `tl_list_flows` for the registry in the running server.
+
+### Playwright Flows (4) {#playwright-flows}
| Flow | Description |
|------|-------------|
| `switchNetworkFlow` | Switch to Mainnet/Nile/Shasta |
@@ -248,7 +250,7 @@ Pre-configured multi-step workflows with dependency checks and parameter templat
| Variable | Description |
|----------|-------------|
-| `AGENT_WALLET_PASSWORD` | Encryption password (optional if using `tl_wallet_create`; required for manual or existing wallets) |
+| `AGENT_WALLET_PASSWORD` | Encryption password (supply for manually provisioned wallets; local auto-created wallets reuse their saved password) |
| `AGENT_WALLET_DIR` | Custom wallet storage directory |
| `TL_OWNER_WALLET_ID` | Owner wallet ID for multisig signing |
| `TL_COSIGNER_WALLET_ID` | Co-signer wallet ID for multisig |
@@ -290,12 +292,13 @@ Auto-detected by Claude Code:
}
```
-If no wallet exists yet, startup shows two paths:
+**Manual creation (recommended for production).** For a new wallet, run `agent-wallet start local_secure --generate --wallet-id main`. For this or an existing wallet, load its password into the launch environment of Claude Code (tested with 2.1.141) as `AGENT_WALLET_PASSWORD` using your secret manager. Add the following entry to the server’s `env` object. Claude Code expands the reference when starting the server. [Claude Code MCP](https://code.claude.com/docs/en/mcp#environment-variable-expansion-in-mcp-json)
-- Auto-create in the running MCP session: call `tl_wallet_create`
-- Manual setup: create the wallet locally with `agent-wallet start local_secure --generate --wallet-id main`, then set `AGENT_WALLET_PASSWORD` and restart
+```json
+{ "AGENT_WALLET_PASSWORD": "${AGENT_WALLET_PASSWORD}" }
+```
-If you choose auto-create, the server generates a random password, saves it to `~/.agent-wallet/runtime_secrets.json`, creates an encrypted `main` wallet, and continues with the current session.
+**Automatic creation (local development).** Leave the password entry out. With no wallet present, call `tl_wallet_create`. The server generates a random password and stores it in plaintext in `~/.agent-wallet/runtime_secrets.json` for reuse after restart. Restrict the file to its owner (`chmod 600`) and protect backups.
The following is a fuller Nile configuration. The router addresses are SunSwap's official Nile Routers ([V2](https://docs.sun.io/protocols/sunswap-v2/reference/contract/), [V3](https://docs.sun.io/protocols/sunswap-v3/reference/contract/)); do not copy Mainnet router addresses into a Nile configuration. `tl_chain_swap` (V2) executes the token path of the quote API's best route through the V2 router, so it fails when the route includes non-V2 pools (for example TRX→USDT on Nile). A Shasta URL selects the Mainnet defaults, so swaps do not work on Shasta:
@@ -311,7 +314,6 @@ The following is a fuller Nile configuration. The router addresses are SunSwap's
"TL_MODE": "prod",
"TL_HEADLESS": "false",
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -338,7 +340,6 @@ If you only need direct API tools and do not need browser automation, you can ke
"cwd": ".",
"env": {
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -396,7 +397,7 @@ mcp-server-tronlink/
│ │ ├── state-snapshot.ts # UI state extraction
│ │ └── tron-crypto.ts # Address derivation, signing, Base58
│ └── flows/
-│ ├── index.ts # Flow registry (32 recipes)
+│ ├── index.ts # Flow registry (24 recipes)
│ ├── switch-network.ts # Network switching flows
│ ├── transfer-trx.ts # Transfer flows
│ ├── multisig.ts # 6 multi-sig flows
@@ -414,7 +415,7 @@ mcp-server-tronlink/
## Dependencies
-Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
+Ranges from the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
| Package | Version | Purpose |
|---------|---------|---------|
@@ -422,14 +423,14 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
| `@noble/hashes` | ^2.0.1 | Keccak-256, SHA256 |
| `@tronlink/tronlink-mcp-core` | ^0.1.0 | Core MCP server framework |
| `playwright` | ^1.49.0 | Browser automation |
-| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`) — pinned, not `latest`, to keep wallet behavior reproducible |
+| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`). The range allows versions from 2.3.0 up to, excluding, 3.0.0. Check the installed version with `npm ls @bankofai/agent-wallet`. |
| `ws` | ^8.18.0 | WebSocket (multi-sig monitoring) |
---
## Tool Contract & Side Effects
-**Input/output schemas and error contract.** Each tool's input/output schema and the structured error envelope are defined by the underlying framework — see [TronLink MCP Core](tronlink-mcp-core.md#error-codes) for the SSOT error code table (`code` / `retryable` / `hint` / triggered_by). Every response carries `meta.schemaVersion`; field meanings are stable within a major version. Agents should branch on `error.code` and `error.retryable`, never on the human-readable `message`.
+**Tool results and errors.** When the server uses Core 0.1.0, inspect `ok` in the Core response. On failure, use `error.code` to look up retry guidance in the [Core error-code table](tronlink-mcp-core.en.md#error-codes). The response includes `error.message` and may include `error.details`. For writes with an unknown outcome, check the transaction status before retrying.
**Per-tool input schemas are discoverable at runtime.** Every tool's parameters are Zod-validated in core and exposed as a JSON `inputSchema` via the MCP `list_tools` method, so a client can enumerate names, types, and required fields without reading this page. The tables below summarize tools by capability; `list_tools` is the authoritative, machine-readable source.
@@ -446,7 +447,7 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
### Selected tool schemas (inline mirror)
-These are **docs-side mirrors** of the most critical tool inputs — useful when an agent is writing a tool-call call site without an MCP session open. Runtime `list_tools` remains the authoritative source: the schemas there carry full Zod metadata (descriptions, `default`, etc.) plus `meta.schemaVersion`. Fields below are derived from `@tronlink/tronlink-mcp-core` `src/mcp-server/schemas.ts` and follow JSON Schema Draft 7. The full set of 52 tool schemas is **not** reproduced here — see core for the SSOT.
+The following tables summarize selected tool inputs. Call `tools/list` on the installed server to read each tool’s `inputSchema`, including its parameter descriptions and defaults. The examples below use JSON Schema Draft 7.
> Docs CI checks the field names and required flags of every block below against upstream `schemas.ts`; if they ever disagree, `list_tools` wins.
@@ -573,7 +574,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
| Boundary | Guarantee | Agent / operator obligation |
|---|---|---|
-| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `code`, `retryable`) for branching. |
+| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `error.code`) for branching. |
| **Outbound host allowlist (SSRF)** | The server only originates HTTPS to the three configured endpoints — `TL_TRONGRID_URL` (TronGrid; SunSwap router contracts are also called through its `triggersmartcontract` endpoint), `TL_MULTISIG_BASE_URL`, `TL_GASFREE_BASE_URL` — plus the built-in SunSwap quote API (`rot.endjgfsv.link` on Mainnet, `tnrouter.endjgfsv.link` on Nile; not configurable). Tools never accept user-supplied URLs that get fetched verbatim. | Pin these env vars to known hosts in production, and include the quote API host in any egress allowlist; do not let LLM input populate any `*_BASE_URL`. |
| **API key handling (token passthrough)** | `TL_TRONGRID_API_KEY`, `TL_MULTISIG_SECRET_KEY`, `TL_GASFREE_API_SECRET` are read from env at startup and used only on the outbound leg. They are **not** returned in any tool response, error `details`, or Knowledge Store record. The server does not accept Authorization headers from MCP clients and forward them upstream. | Audit env capture in your MCP host config (some hosts log env); store secrets in the host's secret manager, not in `.mcp.json` committed to git. |
| **Browser JS execution** | `tl_evaluate` runs arbitrary JavaScript in the controlled Playwright browser context. This is a **High-risk / Destructive** primitive — it can read DOM, click invisible elements, exfiltrate state, and bypass UI HITL. | Disable `tl_evaluate` from the MCP host's tool allowlist for any agent that does not strictly require it. Never expose it to a remote/multi-user MCP deployment. |
@@ -585,7 +586,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
Swaps are **Remote Write** and execute against a public DEX router, so they are exposed to **price slippage** and **front-running / MEV** (e.g. sandwich attacks): the realized output can be worse than quoted if the pool moves between quote and execution.
-- **Always bound the trade with a minimum-output / slippage limit.** Inspect the `tl_chain_swap_v3` input schema via `list_tools` (the `SwapV3Params` shape) for the exact slippage / minimum-output field names — do **not** rely on an unstated default, and treat a missing or zero minimum-output as unsafe.
+- **Always set `slippage` explicitly.** `tl_chain_swap_v3` has no minimum-output input; the server derives the minimum output from `slippage` (a percentage, default 0.5). Do **not** rely on the default; confirm the tolerance with the user and check the field in the `list_tools` schema.
- **Quote immediately before executing.** Get a fresh quote/route (e.g. Skills `tron-swap` `swap-quote` / `swap-route`), pick a tolerance you accept, and pass it explicitly.
- **Check the router.** Set `TL_SUNSWAP_ROUTER` / `TL_SUNSWAP_V3_ROUTER` to the Routers listed for your network in SunSwap's official contract addresses (see Environment Variables); a stale or wrong router can route funds unexpectedly.
- **No auto-retry.** A failed/uncertain swap is a Remote Write — confirm on-chain before re-issuing (`TL_CHAIN_SWAP_FAILED` is not retryable).
@@ -638,9 +639,9 @@ Verify after restart with `list_tools` — `tl_evaluate` should not appear. The
The Direct-API path signs with a local encrypted wallet managed by `@bankofai/agent-wallet`. Two paths exist for unlocking it; pick deliberately.
-**Path A — Manual (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. The password lives only in process memory; nothing is written by this server.
+**Manual creation (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. This path reads the supplied password from the environment.
-**Path B — Auto-create (convenience for local dev).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
+**Automatic creation (local development).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
1. Generates a random password.
2. Writes it in plaintext to `~/.agent-wallet/runtime_secrets.json` so a restart can reuse the wallet.
@@ -649,7 +650,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
| Aspect | Behavior |
|---|---|
| **File** | `~/.agent-wallet/runtime_secrets.json` (plaintext JSON containing the password) |
-| **Recommended permissions** | `chmod 600` — the file is created under the user's `$HOME`, but no umask hardening is enforced. Verify after first run. |
+| **Recommended permissions** | Version 0.1.1 requests mode `0600` when creating the file. Verify the permissions after startup. |
| **Git safety** | `~/.agent-wallet/` is outside any repo by default. If you point `AGENT_WALLET_DIR` inside a repo, add it to `.gitignore` explicitly. |
| **Knowledge Store redaction** | The Knowledge Store auto-redacts `password`, `mnemonic`, `private_key`, `seed` fields in tool inputs / outputs. It does **not** read or sanitize `runtime_secrets.json`. The file is independent of the Knowledge Store. |
| **Logs / stderr** | The auto-generated password is not logged. The file path may appear in startup output. |
@@ -657,11 +658,11 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
**Production guidance.**
-- Prefer Path A. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (Claude Desktop env, vault, etc.).
-- If you must use Path B (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
+- Prefer manual creation. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (for example, a vault).
+- If you must use automatic creation (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
- For any tool that moves real funds, prefer `mcp-tronlink-signer` (browser approval, no on-disk password) over Direct-API.
-**How to enforce Path A (doc-side, today).**
+**How to enforce manual creation (doc-side, today).**
1. Provision the wallet **before** the server boots. From a separate shell:
@@ -670,7 +671,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
# take note of the password you supply here — it is the only copy
```
-2. Inject the password via the MCP host's secret manager so it lands in the server's `env` at launch:
+2. For Claude Code, export the password from your secret manager into the client’s environment and reference it in the server configuration:
```jsonc
// .mcp.json — secret comes from host env, not from this file
@@ -687,7 +688,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
3. **Do not let the agent call `tl_wallet_create`.** Disable it the same way as `tl_evaluate` above (Claude Code `permissions.deny`, Claude Desktop `disabledTools`, or client-side `list_tools` filtering on the name `tl_wallet_create`).
-4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms Path B did not run.
+4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms automatic creation did not run.
**Tracking issue (code-side).** A `--no-auto-create` / `AGENT_WALLET_DISABLE_AUTOCREATE=1` flag that makes the server fail-loud at startup when no wallet exists is the proper long-term fix; until that ships upstream, the doc-side enforcement above is the defense in depth.
@@ -715,8 +716,8 @@ npm install && npm run build
# TL_TRONGRID_URL=https://nile.trongrid.io
#
# 3. If no wallet exists, choose one path:
-# Option A: call tl_wallet_create after startup
-# Option B: create one locally, then set AGENT_WALLET_PASSWORD
+# Automatic creation (local development): call tl_wallet_create after startup
+# Manual creation (recommended for production): create one locally, then set AGENT_WALLET_PASSWORD
# 4. Use with Claude Code
# "Check my TRX balance"
@@ -732,16 +733,14 @@ npm install && npm run build
### Compatibility & migration policy
-- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, `error.code` values, or `meta.schemaVersion` semantics. Post-1.0: standard semver — major-only breaking changes.
+- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, or `error.code` values. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- Tool names (`tl_chain_send`, `tl_chain_swap_v3`, `tl_multisig_*`, `tl_gasfree_*`, `tl_evaluate`, etc.)
- `error.code` enum (SSOT: [TronLink MCP Core — Error Codes](tronlink-mcp-core.md#error-codes))
- - `error.retryable` semantics
- - `meta.schemaVersion` major component
- Required env var names (`TL_TRONGRID_URL`, `TL_MULTISIG_SECRET_KEY`, `AGENT_WALLET_PASSWORD`, …)
- **Volatile contracts** (may change at any time):
- Prose `message` text, log line formats, stderr output
- Internal Knowledge Store keys (consumers should not parse them)
- Pre-check error detail strings (branch on `code`, not on `details.reason`)
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag exposed via `list_tools`; removal lands no earlier than the cycle after that.
-- **Verifying after upgrade.** Re-call `list_tools` and confirm the tool names + `inputSchema` you depend on are still present before resuming the workflow. Compare `meta.schemaVersion` against the value cached at session start.
+- **Deprecations.** [@tronlink/mcp-server-tronlink 0.1.1](https://www.npmjs.com/package/@tronlink/mcp-server-tronlink/v/0.1.1) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Verifying after upgrade.** Record the installed server and Core versions. Recheck tool names and `inputSchema` with `tools/list`, then verify your client handles both `ok: true` and `ok: false` for a read-only tool.
diff --git a/docs/ai-support/mcp-server-tronlink.zh.md b/docs/ai-support/mcp-server-tronlink.zh.md
index 54eab39..a1a0aad 100644
--- a/docs/ai-support/mcp-server-tronlink.zh.md
+++ b/docs/ai-support/mcp-server-tronlink.zh.md
@@ -8,7 +8,7 @@
**核心亮点:**
- 双模架构:**Playwright**(浏览器自动化)+ **Direct API**(链上操作)
-- 32 个内置 Flow Recipe,带预检查和依赖解析
+- 24 个内置 Flow Recipe,带预检查和依赖解析
- 基于加密 `agent-wallet` 的非托管本地交易签名
- 多签管理,支持实时 WebSocket 监控
- 通过 GasFree 服务集成实现零 Gas TRC20 转账
@@ -27,7 +27,7 @@ flowchart TD
Multi["TronLinkMultiSigCapability (5 个工具)"]
GasFree["TronLinkGasFreeCapability (3 个工具)"]
Util["实用能力
Build · StateSnapshot · TRON Crypto"]
- Flow["Flow Recipes
(32 个内置流程配方)"]
+ Flow["Flow Recipes
(24 个内置流程配方)"]
Ext["TronGrid API / 多签服务 / GasFree 服务"]
Chain["TRON 区块链"]
Agent -- "MCP 协议 — stdio / JSON-RPC 2.0" --> Server
@@ -174,11 +174,13 @@ hexToAddress() 0x41... → T 地址
---
-## Flow Recipes(32 个内置流程)
+## Flow Recipes(24 个内置流程) {#flow-recipes}
预配置的多步骤工作流,带依赖检查和参数模板。
-### Playwright 流程
+调用 `tl_list_flows` 可查看运行中服务的注册清单。
+
+### Playwright 流程(4 个) {#playwright-flows}
| 流程 | 说明 |
|------|------|
| `switchNetworkFlow` | 切换到主网/Nile/Shasta |
@@ -248,7 +250,7 @@ hexToAddress() 0x41... → T 地址
| 变量 | 说明 |
|------|------|
-| `AGENT_WALLET_PASSWORD` | 钱包加密密码(自动创建时可省略;手动或已有钱包时需要) |
+| `AGENT_WALLET_PASSWORD` | 钱包加密密码(手动创建的钱包需提供;本地自动创建的钱包可复用已保存的随机密码) |
| `AGENT_WALLET_DIR` | 自定义钱包目录 |
| `TL_OWNER_WALLET_ID` | 多签 owner 使用的钱包 ID |
| `TL_COSIGNER_WALLET_ID` | 多签 cosigner 使用的钱包 ID |
@@ -290,15 +292,13 @@ Claude Code 自动检测:
}
```
-如果本地还没有钱包,服务启动后会提示两条路径:
+**手动创建(生产推荐)**。新建钱包时运行 `agent-wallet start local_secure --generate --wallet-id main`。对于该钱包或已有钱包,通过凭据管理器将其密码导出到启动 Claude Code(已核对 2.1.141)的环境变量 `AGENT_WALLET_PASSWORD`。在服务的 `env` 对象中添加下列配置,Claude Code 在启动服务时展开变量。 [Claude Code MCP](https://code.claude.com/docs/en/mcp#environment-variable-expansion-in-mcp-json)
-1. 自动创建:调用 `tl_wallet_create`
-2. 手动创建:
- 1. 运行 `agent-wallet start local_secure --generate --wallet-id main`
- 2. 把 `AGENT_WALLET_PASSWORD` 写进 `.mcp.json`
- 3. 重启 MCP 服务
+```json
+{ "AGENT_WALLET_PASSWORD": "${AGENT_WALLET_PASSWORD}" }
+```
-如果选择自动创建,服务会生成随机密码,把密码保存到 `~/.agent-wallet/runtime_secrets.json`,创建一个加密的 `main` 钱包,并继续当前会话。
+**自动创建(本地开发)**。省略上述密码配置项。在尚无钱包时调用 `tl_wallet_create`,服务会生成随机密码,明文保存到 `~/.agent-wallet/runtime_secrets.json` 以便重启后复用。将文件权限限制为仅所有者可读写(`chmod 600`),并保护备份。
下面是更完整的 Nile 配置。其中的路由地址是 SunSwap 官方的 Nile Router([V2](https://docs.sun.io/protocols/sunswap-v2/reference/contract/)、[V3](https://docs.sun.io/protocols/sunswap-v3/reference/contract/));请勿把主网路由地址填进 Nile 配置。`tl_chain_swap`(V2)会把报价 API 最优路径中的代币路径交给 V2 路由执行,路径包含非 V2 池子时会失败(例如 Nile 上的 TRX→USDT)。Shasta 的 URL 会使用主网默认值,因此 Shasta 上无法兑换:
@@ -314,7 +314,6 @@ Claude Code 自动检测:
"TL_MODE": "prod",
"TL_HEADLESS": "false",
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -341,7 +340,6 @@ Claude Code 自动检测:
"cwd": ".",
"env": {
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -388,7 +386,7 @@ mcp-server-tronlink/
│ │ ├── state-snapshot.ts # UI 状态提取
│ │ └── tron-crypto.ts # 地址派生、签名、Base58
│ └── flows/
-│ ├── index.ts # 流程注册(32 个配方)
+│ ├── index.ts # 流程注册(24 个配方)
│ ├── switch-network.ts # 网络切换流程
│ ├── transfer-trx.ts # 转账流程
│ ├── multisig.ts # 6 个多签流程
@@ -406,7 +404,7 @@ mcp-server-tronlink/
## 依赖项
-锁定到 `mcp-server-tronlink@0.1.1` 的 `package.json`。升级钱包、MCP 或密码学库 major 版本时务必重新核对。
+依赖范围取自 `mcp-server-tronlink@0.1.1` 的 `package.json`。升级钱包、MCP 或密码学库 major 版本时务必重新核对。
| 包名 | 版本 | 用途 |
|------|------|------|
@@ -414,14 +412,14 @@ mcp-server-tronlink/
| `@noble/hashes` | ^2.0.1 | Keccak-256、SHA256 |
| `@tronlink/tronlink-mcp-core` | ^0.1.0 | 核心 MCP 服务框架 |
| `playwright` | ^1.49.0 | 浏览器自动化 |
-| `@bankofai/agent-wallet` | ^2.3.0 | 加密本地钱包管理(`local_secure`)——**已钉版本,不用 `latest`**,确保钱包行为可复现 |
+| `@bankofai/agent-wallet` | ^2.3.0 | 加密本地钱包管理(`local_secure`)。允许安装 2.3.0 至 3.0.0 之前的兼容版本。用 `npm ls @bankofai/agent-wallet` 查看实际安装版本。 |
| `ws` | ^8.18.0 | WebSocket(多签监控) |
---
## 工具契约与副作用
-**输入/输出 schema 与错误契约。** 每个工具的输入/输出 schema 及结构化错误信封由底层框架定义——见 [TronLink MCP Core](tronlink-mcp-core.md#error-codes) 的 SSOT 错误码表(`code` / `retryable` / `hint` / 典型触发)。每个响应均带 `meta.schemaVersion`,major 版本内字段含义稳定。Agent 应基于 `error.code` 与 `error.retryable` 分支,**不要**解析人类可读的 `message`。
+**工具结果与错误。** 服务端使用 Core 0.1.0 时,先检查 Core 响应中的 `ok`。失败时,根据 `error.code` 在 [Core 错误码表](tronlink-mcp-core.zh.md#error-codes) 中查找重试条件。错误响应包含 `error.message`,也可能包含 `error.details`。对于结果未知的写操作,先核对交易状态,再决定是否重试。
**逐工具输入 schema 可在运行时发现。** 每个工具的参数都由 core 用 Zod 校验,并通过 MCP `list_tools` 方法以 JSON `inputSchema` 形式暴露,因此客户端无需阅读本页即可枚举参数名、类型和必填项。下方表格按能力归纳工具;`list_tools` 才是权威的机器可读来源。
@@ -440,7 +438,7 @@ mcp-server-tronlink/
### 精选工具 schema(文档侧镜像)
-以下是最关键工具输入的**文档侧镜像**——当 agent 需要在没有打开 MCP 会话的情况下写工具调用站点时使用。运行时 `list_tools` 仍是权威源:那里有完整的 Zod 元信息(描述、`default` 等)以及 `meta.schemaVersion`。下方字段抄自 `@tronlink/tronlink-mcp-core` `src/mcp-server/schemas.ts`,遵循 JSON Schema Draft 7。**未**镜像全部 52 个工具——以 core 仓库为 SSOT。
+下表摘录了部分工具的输入参数。对实际安装的服务调用 `tools/list`,从各工具的 `inputSchema` 读取参数说明和默认值。以下示例使用 JSON Schema Draft 7。
> 下方各块的字段名和 required 标记由文档 CI 与上游 `schemas.ts` 自动比对;如有不一致,以 `list_tools` 为准。
@@ -567,7 +565,7 @@ mcp-server-tronlink/
| 边界 | 保证 | Agent / 运维方义务 |
|---|---|---|
-| **Prompt 注入** | 工具输入按原始值作为调用参数使用,server 不会把工具输入拼接进任何向 LLM 二次提交的 prompt。**但**从链上或第三方 API 拿回来的字符串(账户备注、合约 revert 原因、交易 note 等)**可能含攻击者控制内容**,必须视为不可信。 | 不要让 agent 基于 read 工具返回的 prose 自动路由到 Remote Write。分支必须基于结构化字段(`txId`、`code`、`retryable`)。 |
+| **Prompt 注入** | 工具输入按原始值作为调用参数使用,server 不会把工具输入拼接进任何向 LLM 二次提交的 prompt。**但**从链上或第三方 API 拿回来的字符串(账户备注、合约 revert 原因、交易 note 等)**可能含攻击者控制内容**,必须视为不可信。 | 不要让 agent 基于 read 工具返回的 prose 自动路由到 Remote Write。分支必须基于结构化字段(`txId`、`error.code`)。 |
| **出站 host 白名单(SSRF)** | server 只向 3 个配置端点发起 HTTPS——`TL_TRONGRID_URL`(TronGrid;SunSwap 路由合约也通过它的 `triggersmartcontract` 接口调用)、`TL_MULTISIG_BASE_URL`、`TL_GASFREE_BASE_URL`——以及内置的 SunSwap 报价 API(主网 `rot.endjgfsv.link`,Nile `tnrouter.endjgfsv.link`,不可配置)。工具不接收会被原样请求的用户 URL。 | 生产环境把这些 env 钉死到已知 host,并把报价 API host 加入出站白名单;禁止 LLM 输入回填任何 `*_BASE_URL`。 |
| **API key 处理(token passthrough)** | `TL_TRONGRID_API_KEY`、`TL_MULTISIG_SECRET_KEY`、`TL_GASFREE_API_SECRET` 仅在启动时从 env 读取,仅用于出站;**不**会出现在任何工具响应、错误 `details` 或 Knowledge Store 记录中。server 不接受 MCP 客户端传入的 Authorization header 并转发到上游。 | 审计 MCP host 配置对 env 的捕获(部分 host 会落日志);secret 放进 host 的 secret manager,不要写进会提交 git 的 `.mcp.json`。 |
| **浏览器 JS 执行** | `tl_evaluate` 会在受控 Playwright 浏览器上下文中执行任意 JS。这是 **High-risk / Destructive** 原语——可读 DOM、点击隐藏元素、外泄状态、绕过 UI 上的 HITL。 | 严格不需要时,从 MCP host 的工具白名单中禁用 `tl_evaluate`。绝不要把它暴露给远程/多用户 MCP 部署。 |
@@ -579,7 +577,7 @@ mcp-server-tronlink/
兑换属于 **远程写**,且对接公开 DEX 路由器,因此暴露在 **价格滑点** 与 **三明治攻击 / MEV** 之下:在报价和执行之间池子价格变动时,实际成交可能比报价更差。
-- **必须设置 minOut / 滑点上限。** 通过 `list_tools` 查看 `tl_chain_swap_v3` 的输入 schema(`SwapV3Params`),核对实际的 minimum-output / 滑点字段名;**不要**依赖未声明的默认值,缺省或 0 的 minOut 一律视为不安全。
+- **必须显式设置 `slippage`。** `tl_chain_swap_v3` 没有最小输出参数,服务端根据 `slippage`(百分比,默认 0.5)计算最小输出。**不要**依赖默认值;请与用户确认滑点,并在 `list_tools` 的 schema 中核对该字段。
- **执行前现取报价。** 通过 Skills `tron-swap` 的 `swap-quote` / `swap-route`(或同等接口)取最新报价/路径,选定可接受的滑点容忍度并显式传入。
- **核对 router。** 请将 `TL_SUNSWAP_ROUTER` / `TL_SUNSWAP_V3_ROUTER` 设置为 SunSwap 官方合约地址中对应网络的 Router(见环境变量);过期或错误的 router 会把资金路由到非预期目标。
- **不可自动重试。** swap 失败或结果未知都属于远程写——先在链上确认再决定是否重发(`TL_CHAIN_SWAP_FAILED` 不可重试)。
@@ -631,9 +629,9 @@ mcp-server-tronlink/
Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签名。解锁这把钱包有两条路径,请按目的明确选择。
-**路径 A — 手动(生产推荐)。** 离线创建钱包,将 `AGENT_WALLET_PASSWORD` 放进 MCP host 的 secret manager,再启动 server。密码仅存在于进程内存,server 不写任何文件。
+**手动创建(生产推荐)。** 离线创建钱包,将 `AGENT_WALLET_PASSWORD` 放进 MCP host 的 secret manager,再启动 server。此路径从运行环境读取提供的密码。
-**路径 B — 自动创建(仅适合本地开发)。** 启动时若无钱包且 agent 调用了 `tl_wallet_create`,server 将:
+**自动创建(仅适合本地开发)。** 启动时若无钱包且 agent 调用了 `tl_wallet_create`,server 将:
1. 生成随机密码。
2. **将密码以明文写入 `~/.agent-wallet/runtime_secrets.json`**,以便重启后能复用同一钱包。
@@ -642,7 +640,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
| 方面 | 行为 |
|---|---|
| **文件** | `~/.agent-wallet/runtime_secrets.json`(含密码的明文 JSON) |
-| **建议权限** | `chmod 600`——文件在用户 `$HOME` 下创建,但**没有 umask 兜底**,首次运行后请手工核查。 |
+| **建议权限** | 0.1.1 新建文件时指定权限 `0600`。启动后请核对实际权限。 |
| **Git 隔离** | `~/.agent-wallet/` 默认在任何仓库之外。若把 `AGENT_WALLET_DIR` 指到仓库内部,必须显式加 `.gitignore`。 |
| **Knowledge Store 脱敏边界** | Knowledge Store 自动脱敏 `password`、`mnemonic`、`private_key`、`seed` 等字段;**不**读取或处理 `runtime_secrets.json`。该文件与 Knowledge Store 互相独立。 |
| **日志 / stderr** | 自动生成的密码不会落日志;文件路径可能出现在启动输出中。 |
@@ -650,11 +648,11 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
**生产建议。**
-- 优先路径 A。`AGENT_WALLET_PASSWORD` 来自 host 的 secret manager(Claude Desktop env、vault 等)。
-- 必须用路径 B 时(如临时 CI),把 `AGENT_WALLET_DIR` 指到任务结束即销毁的 tmpfs。
+- 优先手动创建。`AGENT_WALLET_PASSWORD` 来自 host 的 secret manager(如 vault)。
+- 必须用自动创建时(如临时 CI),把 `AGENT_WALLET_DIR` 指到任务结束即销毁的 tmpfs。
- 涉及真实资金的工具,生产环境优先选 `mcp-tronlink-signer`(浏览器审批、不落盘密码),避免 Direct-API。
-**如何强制路径 A(文档侧的当下做法)。**
+**如何强制手动创建(文档侧的当下做法)。**
1. **server 启动前**离线创建钱包:
@@ -663,7 +661,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
# 此处输入的密码请单独保管——它是唯一的副本
```
-2. 让密码通过 MCP host 的 secret manager 注入到 server 的 `env`:
+2. 使用 Claude Code 时,通过凭据管理器将密码导出到客户端启动环境,并在服务配置中引用变量:
```jsonc
// .mcp.json — secret 来自 host env,而不是这个文件本身
@@ -680,7 +678,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
3. **禁止 agent 调用 `tl_wallet_create`。** 用与 `tl_evaluate` 相同的方式禁用(Claude Code `permissions.deny`、Claude Desktop `disabledTools`,或客户端侧基于 `list_tools` 用名字 `tl_wallet_create` 过滤)。
-4. 首次启动后验证:`list_tools` 中不应出现 `tl_wallet_create`;`~/.agent-wallet/runtime_secrets.json` 不存在即说明路径 B 没有走过。
+4. 首次启动后验证:`list_tools` 中不应出现 `tl_wallet_create`;`~/.agent-wallet/runtime_secrets.json` 不存在即说明自动创建没有走过。
**待解决(代码侧)。** 长期方案是在 server 启动时加 `--no-auto-create` / `AGENT_WALLET_DISABLE_AUTOCREATE=1` 开关,使无钱包时直接 fail-loud。上游 PR ship 之前,上面这套文档级强制方案是 defense-in-depth。
@@ -707,10 +705,10 @@ npm install && npm run build
export TL_TRONGRID_URL="https://nile.trongrid.io"
# 3. 如果本地还没有钱包,二选一:
-# 方案 A:在 MCP 会话里调用 tl_wallet_create
-# 方案 B:本地执行
+# 自动创建(本地开发):在 MCP 会话里调用 tl_wallet_create
+# 手动创建(生产推荐):本地执行
# agent-wallet start local_secure --generate --wallet-id main
-# 然后把同一个密码写进 .mcp.json 的 AGENT_WALLET_PASSWORD
+# 通过凭据管理器设置 Claude Code 启动环境中的 AGENT_WALLET_PASSWORD,并按上述手动创建配置引用该变量
# 4. 配合 Claude Code 使用
# 配置好 .mcp.json 后自然语言使用:
@@ -727,16 +725,14 @@ export TL_TRONGRID_URL="https://nile.trongrid.io"
### 兼容性与迁移策略
-- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更工具名、输入 schema、`error.code` 值或 `meta.schemaVersion` 语义。1.0 之后:标准 semver,仅 major 允许破坏。
+- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更工具名、输入 schema 或 `error.code` 值。1.0 之后:标准 semver,仅 major 允许破坏。
- **稳定契约**(patch 不会动):
- 工具名(`tl_chain_send`、`tl_chain_swap_v3`、`tl_multisig_*`、`tl_gasfree_*`、`tl_evaluate` 等)
- `error.code` 枚举(SSOT:[TronLink MCP Core 错误码](tronlink-mcp-core.md#error-codes))
- - `error.retryable` 语义
- - `meta.schemaVersion` 的 major 分量
- 必需环境变量名(`TL_TRONGRID_URL`、`TL_MULTISIG_SECRET_KEY`、`AGENT_WALLET_PASSWORD` 等)
- **不稳定契约**(随时可能变化):
- `message` 自然语言文本、日志行格式、stderr 输出
- 内部 Knowledge Store key(消费者不应解析)
- 预检查的错误 detail 文本(分支用 `code`,别用 `details.reason`)
-- **废弃窗口。** 工具或入参字段被废弃时,下一 minor 至少保留旧形式与新形式并存 **一个 minor 周期**,`list_tools` 会带 `meta.deprecated` 标记;移除最早在再下一周期。
-- **升级后校验。** 重新 `list_tools` 确认依赖的工具名 + `inputSchema` 仍在,再继续工作流;将 `meta.schemaVersion` 与会话开始时缓存的值对比。
+- **弃用检查。** [@tronlink/mcp-server-tronlink 0.1.1](https://www.npmjs.com/package/@tronlink/mcp-server-tronlink/v/0.1.1) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
+- **升级后校验。** 记录已安装的 Server 和 Core 版本,通过 `tools/list` 核对依赖的工具名和 `inputSchema`,再验证客户端能处理只读工具的 `ok: true` 和 `ok: false` 两种响应。
diff --git a/docs/ai-support/mcp-tronlink-signer.en.md b/docs/ai-support/mcp-tronlink-signer.en.md
index d2bfb35..9783dfb 100644
--- a/docs/ai-support/mcp-tronlink-signer.en.md
+++ b/docs/ai-support/mcp-tronlink-signer.en.md
@@ -147,7 +147,7 @@ In v0.1.4, errors are returned as an MCP tool result with `isError: true` and a
|---|---|---|
| **Prompt injection** | Tool inputs are consumed verbatim as call arguments; the server does not re-prompt an LLM with them. The TronLink approval page renders parsed transaction fields, not the agent's free-text. | Treat any on-chain string returned (memos, revert reasons) as untrusted; branch on `txId` / `status`, not on prose. |
| **Local HTTP listener** | The local approval server **binds to `127.0.0.1` only** (port `TRON_HTTP_PORT`, default 3386, auto-increments on conflict). It never accepts off-host connections. Each server session has a unique ID; old browser tabs from previous sessions are invalidated automatically. | Do not port-forward 3386 over a network. Do not run two copies of this server with the same `TRON_HTTP_PORT` on a shared box. |
-| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [Networks](#environment-variables) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
+| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [network endpoints](../reference/networks.md#networks) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
| **API key handling (token passthrough)** | `TRON_API_KEY` is read from env at startup and used only on the outbound leg to TronGrid. It is **not** returned in any tool response, error `details`, or MCP resource. The server does not accept Authorization headers from MCP clients and forward them upstream. | Store the key in the MCP host's secret manager, not in plain `mcpServers` config committed to git. |
| **HITL is mandatory for signing** | Every signing tool (`send_trx`, `send_trc20`, `sign_message`, `sign_typed_data`, `sign_transaction`) opens the TronLink approval page. **There is no programmatic bypass.** Private keys never leave TronLink. | Operators do not need to enforce HITL — it is structural. Do not attempt to harden by removing the browser layer. |
| **Browser tab hijacking** | The approval page authenticates each request against the server session ID and ignores stale tabs. Heartbeat detection closes the session on browser disconnect. | If the same user runs multiple agents, ensure each spawns its own signer instance; cross-instance request mixing is prevented by session ID, but UI confusion is not. |
@@ -201,7 +201,7 @@ Co-released with `tronlink-signer@0.1.2`. **Major UX overhaul** on the approval
### Compatibility & migration policy
- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change MCP tool names or input schemas. Post-1.0: standard semver — major-only breaking changes.
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag in the schema; removal lands no earlier than the cycle after that.
+- **Deprecations.** [mcp-tronlink-signer 0.1.4](https://www.npmjs.com/package/mcp-tronlink-signer/v/0.1.4) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
- **Stable contracts.** Tool names and `status` values (`success` / `pending` / `failed`) are part of the public surface — they don't change in a patch.
- **Volatile contracts.** Error `message` text (match the known values under [Errors](#errors) and treat others as unknown), log line formats, and the layout of the browser approval page are **not** part of the public surface and may change at any time.
- **Verifying after upgrade.** Re-call `list_tools` and confirm the names + schemas you depend on are still present before resuming a workflow.
diff --git a/docs/ai-support/mcp-tronlink-signer.zh.md b/docs/ai-support/mcp-tronlink-signer.zh.md
index e152f3c..ce805fc 100644
--- a/docs/ai-support/mcp-tronlink-signer.zh.md
+++ b/docs/ai-support/mcp-tronlink-signer.zh.md
@@ -149,7 +149,7 @@ v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一
|---|---|---|
| **Prompt 注入** | 工具输入按原始值作为调用参数,server 不会再次提交给 LLM。TronLink 审批页渲染的是解析后的交易字段,不是 agent 的自由文本。 | 链上拿到的字符串(备注、revert 原因)视为不可信;分支应基于 `txId` / `status`,而非 prose。 |
| **本地 HTTP listener** | 本地审批 server **仅绑定 `127.0.0.1`**(端口 `TRON_HTTP_PORT`,默认 3386,被占用时自增),永远不接受跨主机连接。每个 server session 有唯一 ID,前一次 session 的浏览器标签会被自动失效。 | 不要把 3386 端口转发到外网。同一台机器不要用相同 `TRON_HTTP_PORT` 跑两份。 |
-| **出站 host 白名单(SSRF)** | signer 只与 [Networks](#environment-variables) 列出的 TronGrid 端点以及本地浏览器通信,工具不接受会被原样请求的用户 URL。 | 生产环境钉死 `TRON_NETWORK`、`TRON_API_KEY`。 |
+| **出站 host 白名单(SSRF)** | signer 只与 [网络端点](../reference/networks.md#networks) 列出的 TronGrid 端点以及本地浏览器通信,工具不接受会被原样请求的用户 URL。 | 生产环境钉死 `TRON_NETWORK`、`TRON_API_KEY`。 |
| **API key 处理(token passthrough)** | `TRON_API_KEY` 仅在启动时从 env 读取,仅用于到 TronGrid 的出站;**不**会出现在任何工具响应、错误 `details` 或 MCP resource 中。server 不接受 MCP 客户端传入的 Authorization header 并转发到上游。 | API key 放进 MCP host 的 secret manager,不要写进会提交 git 的 `mcpServers` 配置。 |
| **签名必须 HITL** | 所有签名工具(`send_trx`、`send_trc20`、`sign_message`、`sign_typed_data`、`sign_transaction`)都会打开 TronLink 审批页,**不存在程序化绕过**。私钥始终留在 TronLink。 | 不需要运维额外强制 HITL——这是结构性保证。不要试图通过移除浏览器层来"加固"。 |
| **浏览器标签劫持** | 审批页基于 server session ID 验证每次请求,过期的标签会被忽略;心跳检测会在断连时关闭 session。 | 同一用户跑多个 agent 时,请让每个 agent 启动自己的 signer 实例;跨实例的请求串扰由 session ID 屏蔽,但 UI 层混淆不防。 |
@@ -207,7 +207,7 @@ v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一
### 兼容性与迁移策略
- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更 MCP 工具名或输入 schema。1.0 之后:标准 semver,仅 major 允许破坏。
-- **废弃窗口。** 当某工具或入参字段被废弃时,下一 minor 至少保留旧形式与新形式并存 **一个 minor 周期**,schema 内置 `meta.deprecated` 标记;移除最早发生在再下一周期。
+- **弃用检查。** [mcp-tronlink-signer 0.1.4](https://www.npmjs.com/package/mcp-tronlink-signer/v/0.1.4) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
- **稳定契约。** 工具名、`status` 值(`success` / `pending` / `failed`)属于公开面,patch 不会动。
- **不稳定契约。** 错误 `message` 文本(匹配[错误](#errors)中列出的已知取值,其他按未知处理)、日志行格式、审批页的视觉布局 **不属于** 公开面,随时可能变化。
- **升级后校验。** 升级后 **必须** 重新 `list_tools` 确认你依赖的名字 + schema 仍存在,再继续工作流。
diff --git a/docs/ai-support/tronlink-cli.en.md b/docs/ai-support/tronlink-cli.en.md
index cbb1628..82ac291 100644
--- a/docs/ai-support/tronlink-cli.en.md
+++ b/docs/ai-support/tronlink-cli.en.md
@@ -327,7 +327,10 @@ In `--json` mode, v1.0.1 writes failures to **stderr** and exits with `1`:
2. For read operations with `--address`: queries TronGrid directly
3. For write/read without `--address`: connects to the TronLink browser extension for wallet info
4. Builds unsigned transaction using local TronWeb `transactionBuilder`
-5. Pre-flight check: runs on all write commands (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+5. Pre-flight check: depends on the command (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+
+ In v1.0.1, `withdraw` queries the payer’s `unfrozenV2` entries and errors before signing if no matured TRX is available. `reward` calls `getReward(address)` and returns without signing if the amount is zero or less (JSON status `No Rewards`). A failed lookup stops either command before signing.
+
6. Sends transaction to TronLink for signing (browser approval page)
7. Broadcasts: signer broadcasts by default, or CLI broadcasts locally with `--local-broadcast`. In both modes the CLI polls `getUnconfirmedTransactionInfo` until the tx is packed into a block (~3s), and surfaces OUT_OF_ENERGY / REVERT / FAILED as errors
8. Outputs result
@@ -431,11 +434,15 @@ tronlink reward --json
### Example: AI Transfer Flow
```bash
-# 1. Check balance first
-tronlink balance --address TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL --network mainnet --json
+# Set PAYER to the address selected in TronLink and RECIPIENT to the destination.
+# If the wallet account or network changes, cancel and check the new balance first.
+NETWORK=mainnet
+
+# 1. Check the payer's balance
+tronlink balance --address "${PAYER:?set PAYER}" --network "$NETWORK" --json
# 2. Send 10 TRX (opens browser for signing, wait for return)
-tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network mainnet --json
+tronlink transfer --type trx --toAddress "${RECIPIENT:?set RECIPIENT}" --amount 10 --network "$NETWORK" --json
# 3. Verify result — output includes txId and explorer URL
# { "Status": "Success", "TxID": "abc...", "Explorer": "https://tronscan.org/#/transaction/abc..." }
diff --git a/docs/ai-support/tronlink-cli.zh.md b/docs/ai-support/tronlink-cli.zh.md
index 6aad82e..48b3c24 100644
--- a/docs/ai-support/tronlink-cli.zh.md
+++ b/docs/ai-support/tronlink-cli.zh.md
@@ -6,7 +6,7 @@
所有交易均在本地构建,并通过 TronLink 浏览器扩展进行签名 — 私钥始终不会离开 TronLink。
-## 环境要求
+## 环境要求 {#requirements}
- Node.js >= 20
- 已安装 TronLink 浏览器扩展
@@ -19,7 +19,7 @@
数据截至 2026-05;来源:各包 `package.json`。
-## 安装
+## 安装 {#installation}
```bash
# 通过 npm 安装
@@ -33,7 +33,7 @@ npm link
安装完成后,可在全局使用 `tronlink` 命令。
-## 全局选项
+## 全局选项 {#global-options}
| 选项 | 默认值 | 说明 |
| ---- | ------ | ---- |
@@ -45,9 +45,9 @@ npm link
所有选项名称均**不区分大小写**(例如 `--toAddress`、`--TOADDRESS`、`--toaddress` 完全等价)。
-## 命令
+## 命令 {#commands}
-### 查询(读操作)
+### 查询(读操作) {#query-read}
读命令支持两种模式:
@@ -74,7 +74,7 @@ tronlink resource # 连接钱包
**Nile 查询代币**:TRX, USDT
**Shasta 查询代币**:TRX
-### 转账
+### 转账 {#transfer}
```bash
# TRX(金额单位为 TRX,而非 sun)
@@ -107,7 +107,7 @@ tronlink transfer --type trc721 --contract TContractAddr --toAddress TRecipient
| trc20 | `--toAddress`, `--amount`, `--contract` | `--tokenId` |
| trc721 | `--toAddress`, `--contract`, `--tokenId` | `--amount`, `--decimals` |
-### 调用智能合约
+### 调用智能合约 {#trigger-smart-contract}
调用任意智能合约方法。`--args` 是一个 JSON 数组,按位置与 `--method` 中的参数类型对应。
@@ -156,7 +156,7 @@ tronlink trigger --contract TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t \
- 写操作在签名前会先在链上做一次 pre-flight 模拟(`triggerConstantContract`)。合约 revert、call-value + 手续费余额不足、超出 fee-limit 都会在交易上链前被拦截。
- `--constant` 跳过签名与广播。如果不关心 owner 地址,可传 `--address` 避免唤起钱包授权。返回结果不会自动解码 — 请用任意 Solidity ABI 解码器解析返回的 hex。
-### 质押(Stake 2.0)
+### 质押(Stake 2.0) {#staking-stake-20}
```bash
# 质押 TRX 以获取能量或带宽
@@ -169,7 +169,7 @@ tronlink unstake --amount --resource [--network nile
tronlink withdraw [--network nile]
```
-### 资源代理
+### 资源代理 {#resource-delegation}
```bash
# 代理能量或带宽(锁定期单位为天,支持小数如 1.5)
@@ -181,7 +181,7 @@ tronlink delegate --toAddress --amount --resource --amount --resource [--network nile]
```
-### 投票
+### 投票 {#voting}
```bash
# 为超级代表投票(格式:address:count,支持多个)
@@ -198,7 +198,7 @@ tronlink vote --votes TXxx:5 TYyy:3 TZzz:2
tronlink reward
```
-## 交易签名
+## 交易签名 {#transaction-signing}
写操作(转账、质押、代理、投票等)需要在浏览器中通过 TronLink 进行授权:
@@ -213,7 +213,7 @@ tronlink reward
取消某个命令(Ctrl+C)只会取消该笔交易,其他排队中的交易不受影响。
-## 交易预览
+## 交易预览 {#transaction-preview}
所有写操作在签名前都会显示预览:
@@ -230,7 +230,7 @@ Transaction Preview
Awaiting TronLink approval...
```
-## 广播
+## 广播 {#broadcast}
默认情况下,签名后的交易由签名器(TronLink)广播。使用 `--local-broadcast` 可让 CLI 通过自身的 TronWeb 实例进行本地广播:
@@ -246,6 +246,8 @@ tronlink transfer --type trx --toAddress TYqx5gm3p3wLDE9Bv8TBJAbK4ELNbSLfJV --am
若网络抖动导致 CLI 本地广播与签名器残留的广播都打到节点(例如断线重连、同一 nonce 的两次 CLI 调用),第二次提交会被节点拒绝——TRON 节点按交易 ID 去重,结果只会是一次入块 + 一次 `DUP_TRANSACTION_ERROR` 类失败,绝不会出现两次链上效果。已确认入块后再看到此类错误视为良性;尚未确认前出现则按结果未知的网络失败处理(CLI 退出 `1`),先用区块浏览器核对再决定是否重试。
+## 输入校验 {#input-validation}
+
所有输入在连接 TronLink 前会进行校验:
- **金额**:仅支持非负数字,不允许科学计数法或多个小数点
@@ -264,7 +266,7 @@ tronlink transfer --type trx --toAddress TYqx5gm3p3wLDE9Bv8TBJAbK4ELNbSLfJV --am
无效输入会在任何钱包交互发生之前立即被拒绝并提示明确错误。
-## 输出格式
+## 输出格式 {#output-formats}
**表格(默认)**:人类可读的表格输出。
@@ -282,13 +284,13 @@ tronlink transfer --type trx --toAddress TYqx5gm3p3wLDE9Bv8TBJAbK4ELNbSLfJV --am
读操作在同一顶层对象下返回查询数据(余额、资源等)。字段名在同一大版本内保持稳定。
-## 退出码
+## 退出码 {#exit-codes}
CLI v1.0.1 成功时退出 `0`,任何失败均退出 `1`,没有按失败类别区分的退出码。不要仅根据退出状态区分参数错误、用户拒绝、超时、链上失败或网络失败。
> **重试策略。** 读命令可以重试。写/签名命令失败或结果未知时,不要自动重试;先确认上一笔交易是否已经上链。
-## 错误
+## 错误 {#errors}
v1.0.1 在 `--json` 模式下将失败信息写入 **stderr**,并以 `1` 退出:
@@ -298,7 +300,7 @@ v1.0.1 在 `--json` 模式下将失败信息写入 **stderr**,并以 `1` 退
`error` 是描述失败原因的字符串,不是对象。本版本没有结构化的 `error.code` 或 `error.retryable` 字段。该文本不是稳定契约——例如在 TronLink 插件弹窗中拒绝时,会原样透传 `Confirmation declined by user`。请将 stderr 与 stdout 上的成功 JSON 分别捕获。
-## 安全与副作用
+## 安全与副作用 {#safety-side-effects}
| 副作用 | 命令 |
| --- | --- |
@@ -309,7 +311,7 @@ v1.0.1 在 `--json` 模式下将失败信息写入 **stderr**,并以 `1` 退
- **写操作不自动重试:** 见上方重试策略。
- **默认低风险:** 优先用测试网(`--network nile` / `shasta`);只有动用真实资金时才用 `--network mainnet`。
-## 支持的网络
+## 支持的网络 {#supported-networks}
| 网络 | API 节点 | 区块链浏览器 |
| ---- | -------- | ------------ |
@@ -317,28 +319,31 @@ v1.0.1 在 `--json` 模式下将失败信息写入 **stderr**,并以 `1` 退
| nile | `https://nile.trongrid.io` | `https://nile.tronscan.org` |
| shasta | `https://api.shasta.trongrid.io` | `https://shasta.tronscan.org` |
-## 工作原理
+## 工作原理 {#how-it-works}
1. CLI 解析命令并校验所有输入
2. 对于带 `--address` 的读操作:直接通过 TronGrid 查询
3. 对于写操作或不带 `--address` 的读操作:连接 TronLink 浏览器扩展以获取钱包信息
4. 使用本地 TronWeb `transactionBuilder` 构建未签名交易
-5. Pre-flight 校验:所有写命令(transfer、stake、unstake、delegate、reclaim、vote、trigger)在签名前会执行此步——校验 TRX / 代币 / 已质押 / 已委托余额,模拟合约调用以捕获 revert,估算能量与带宽消耗,校验 SR 地址(vote)、NFT 所有权(TRC721)、委托解锁时间(reclaim)
+5. Pre-flight 校验:以下命令(transfer、stake、unstake、delegate、reclaim、vote、trigger)在签名前会执行此步——校验 TRX / 代币 / 已质押 / 已委托余额,模拟合约调用以捕获 revert,估算能量与带宽消耗,校验 SR 地址(vote)、NFT 所有权(TRC721)、委托解锁时间(reclaim)
+
+ v1.0.1 中,`withdraw` 查询付款账户的 `unfrozenV2`,没有到期可提取的 TRX 时在签名前报错。`reward` 调用 `getReward(address)`,金额小于等于零时直接结束(JSON 状态为 `No Rewards`)。任一查询失败都会在签名前终止命令。
+
6. 将交易发送给 TronLink 进行签名(浏览器授权页面)
7. 广播:默认由签名器广播;使用 `--local-broadcast` 时由 CLI 在本地广播。两种模式下 CLI 都会轮询 `getUnconfirmedTransactionInfo` 直至交易被打包入块(约 3 秒),并将 OUT_OF_ENERGY / REVERT / FAILED 作为错误抛出
8. 输出结果
-## AI / 智能体使用
+## AI / 智能体使用 {#ai-agent-usage}
TronLink CLI 通过 `--json` 输出支持 AI 智能体集成。所有命令都会返回结构化 JSON,便于解析。
-### 前置条件
+### 前置条件 {#prerequisites}
- 已全局安装 `tronlink`(`npm i -g @tronlink/tronlink-cli`)
- 已安装并解锁 TronLink 浏览器扩展
- 浏览器处于运行状态(写操作会打开 TronLink 进行签名)
-### 使用规则
+### 使用规则 {#rules}
1. 始终追加 `--json` 以获取机器可读输出
2. 写操作(转账、质押、投票等)会打开浏览器供用户签名 — 需等待命令返回(默认超时:5 分钟)
@@ -346,9 +351,9 @@ TronLink CLI 通过 `--json` 输出支持 AI 智能体集成。所有命令都
4. 通过 `--network` 指定网络;如果省略,所有命令都默认使用主网
5. 取消命令(Ctrl+C)只会取消该笔交易,不会终止签名会话
-### AI 命令参考
+### AI 命令参考 {#ai-command-reference}
-#### 查询(无需签名)
+#### 查询(无需签名) {#query-no-signing-needed}
```bash
# 查询所有代币余额
@@ -364,7 +369,7 @@ tronlink balance --address --tokenId --network mainnet --json
tronlink resource --address --network mainnet --json
```
-#### 转账(需要签名)
+#### 转账(需要签名) {#transfer-requires-signing}
```bash
# TRX
@@ -380,7 +385,7 @@ tronlink transfer --type trc10 --tokenId --toAddress --amount
tronlink transfer --type trc721 --contract --toAddress --tokenId --json
```
-#### 调用智能合约
+#### 调用智能合约 {#trigger-smart-contract_1}
```bash
# 写操作(会唤起 TronLink 进行签名)
@@ -394,7 +399,7 @@ tronlink trigger --contract \
--args '[""]' --constant --address --json
```
-#### 质押
+#### 质押 {#staking}
```bash
tronlink stake --amount --resource energy --json
@@ -402,21 +407,21 @@ tronlink unstake --amount --resource energy --json
tronlink withdraw --json
```
-#### 资源代理
+#### 资源代理 {#resource-delegation_1}
```bash
tronlink delegate --toAddress --amount --resource energy --json
tronlink reclaim --fromAddress --amount --resource energy --json
```
-#### 投票
+#### 投票 {#voting_1}
```bash
tronlink vote --votes --json
tronlink reward --json
```
-### 常用代币合约
+### 常用代币合约 {#common-token-contracts}
| 代币 | 网络 | 合约地址 |
| ---- | ---- | -------- |
@@ -424,20 +429,24 @@ tronlink reward --json
| USDD | mainnet | TXDk8mbtRbXeYuMNS83CfKPaYYT8XWv9Hz |
| USDC | mainnet | TEkxiTehnzSmSe2XqrBj4w32RUN966rdz8 |
-### 示例:AI 转账流程
+### 示例:AI 转账流程 {#example-ai-transfer-flow}
```bash
-# 1. 先查询余额
-tronlink balance --address TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL --network mainnet --json
+# 将 PAYER 设为 TronLink 当前付款地址,RECIPIENT 设为收款地址。
+# 若账户或网络变化,请取消操作,重新查询实际付款账户的余额。
+NETWORK=mainnet
+
+# 1. 查询付款账户余额
+tronlink balance --address "${PAYER:?set PAYER}" --network "$NETWORK" --json
# 2. 发送 10 TRX(会打开浏览器签名,需等待返回)
-tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network mainnet --json
+tronlink transfer --type trx --toAddress "${RECIPIENT:?set RECIPIENT}" --amount 10 --network "$NETWORK" --json
# 3. 验证结果 — 输出包含 txId 和浏览器链接
# { "Status": "Success", "TxID": "abc...", "Explorer": "https://tronscan.org/#/transaction/abc..." }
```
-### 注意事项
+### 注意事项 {#notes}
- 所有写命令都会阻塞,直到用户在 TronLink 浏览器弹窗中批准或拒绝
- 如用户拒绝或签名超时(5 分钟),命令会以错误退出
@@ -445,13 +454,13 @@ tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network
- 使用 `--timeout ` 可调整签名超时时间
- 金额内部使用基于字符串的运算 — 不存在浮点精度问题
-## 版本与许可证
+## 版本与许可证 {#version-license}
- **包:** `@tronlink/tronlink-cli` v1.0.1
- **许可证:** MIT —— `SPDX-License-Identifier: MIT`
- **变更记录 / 发布:** [https://github.com/TronLink/tronlink-cli/releases](https://github.com/TronLink/tronlink-cli/releases) —— 截至当前 v1.0.x 尚无 GitHub tag 发布;打 tag 之前请直接看 commit 历史。
-### 兼容性与迁移策略
+### 兼容性与迁移策略 {#compatibility-migration-policy}
CLI 已进入 **v1.0.x**,适用标准 semver——只有 **major** 升级允许破坏脚本依赖的公开面。
diff --git a/docs/ai-support/tronlink-mcp-core.en.md b/docs/ai-support/tronlink-mcp-core.en.md
index 29f0a24..7ac9fc3 100644
--- a/docs/ai-support/tronlink-mcp-core.en.md
+++ b/docs/ai-support/tronlink-mcp-core.en.md
@@ -357,7 +357,7 @@ All tools use the `tl_` prefix. Organized into 13 categories:
## Standardized Response Format
-All tools return a consistent structure:
+In [Core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0), inspect `ok` to select `result` or `error`. On failure, read `error.code` and `error.message`. `error.details` is optional. Response metadata contains `timestamp`, `sessionId`, and `durationMs`.
```typescript
// Success
@@ -366,7 +366,7 @@ All tools return a consistent structure:
result: { /* tool-specific data */ },
meta: {
timestamp: "2026-03-09T10:15:23.456Z",
- sessionId: "tl-1741504523",
+ sessionId: "tl-1773051323",
durationMs: 234
}
}
@@ -377,17 +377,15 @@ All tools return a consistent structure:
error: {
code: "TL_CLICK_FAILED", // stable code — see table below
message: "Element not found",
- retryable: false, // explicit hint for agents
- hint: "Re-snapshot the page and retry with a fresh a11yRef.",
details: { /* optional */ }
},
- meta: { timestamp, sessionId, durationMs, schemaVersion: "1.0" }
+ meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1773051323", durationMs: 234 }
}
```
### Error Codes
-This is the single source of truth (SSOT) for error codes returned by every tool in this framework. Downstream servers built on this framework (`mcp-server-tronlink`) inherit these codes and may extend them; `mcp-tronlink-signer` is a separate server and does not use them. `retryable` reflects framework-level safety; an agent **must** still apply the side-effect classification of the calling tool — never auto-retry a Remote Write whose outcome is unknown, regardless of `retryable`.
+This table is the single source of truth for Core error codes and their retry semantics. Look up `error.code` in the table below for retry guidance and recovery steps. **Retryable** and **Hint** are documentation columns. Core 0.1.0 omits `error.retryable`, `error.hint`, and `meta.schemaVersion` from the response. For a Remote Write with an unknown outcome, verify the transaction before considering another attempt. Downstream servers such as `mcp-server-tronlink` can extend this table. The independent `mcp-tronlink-signer` server uses its own errors.
| Code | Retryable | Hint | Typical trigger |
|------|:---:|------|-----------------|
@@ -403,8 +401,8 @@ This is the single source of truth (SSOT) for error codes returned by every tool
| `TL_WAIT_TIMEOUT` | true | Increase the timeout or wait on a different selector. | `tl_wait_for`, `tl_wait_for_notification` |
| `TL_SCREENSHOT_FAILED` | true | Transient; retry. | `tl_screenshot`, `tl_describe_screen` |
| `TL_CAPABILITY_NOT_AVAILABLE` | false | The session was launched without this capability; reconfigure and relaunch. | Any tool that requires an optional capability |
-| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. | `tl_chain_get_*` |
-| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake`, `tl_chain_resource` |
+| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. **Exception:** `tl_chain_resource` also returns this code when a delegate/undelegate write fails, so treat it as `TL_CHAIN_SEND_FAILED` and check the transaction before re-issuing. | `tl_chain_get_*`, `tl_chain_resource` |
+| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake` |
| `TL_CHAIN_SWAP_FAILED` | false | Same as send — confirm the previous tx did not land before retrying. | `tl_chain_swap`, `tl_chain_swap_v3` |
| `TL_GASFREE_QUERY_FAILED` | true | Transient; retry. | `tl_gasfree_get_account`, `tl_gasfree_get_transactions` |
| `TL_GASFREE_SEND_FAILED` | false | Do **not** auto-retry; query the GasFree service for the latest status. | `tl_gasfree_send` |
@@ -416,7 +414,7 @@ This is the single source of truth (SSOT) for error codes returned by every tool
Custom codes added by downstream servers must follow these rules:
- Never reuse a code listed above with a different meaning.
-- `retryable` is required for every new code.
+- Document the retry policy and recovery step for each new code.
- Meaning is stable within a major version.
- New codes are documented in the consuming server's docs, not silently introduced.
@@ -640,16 +638,16 @@ npm run clean # Remove dist/
### Compatibility & migration policy
-This package is **the SSOT** for tool schemas, error codes, and `meta.schemaVersion` consumed by `mcp-server-tronlink` and any downstream MCP server built on this core. The compatibility surface is therefore wider than a typical library:
+This package defines the tool schemas, error codes, and response envelope used by `mcp-server-tronlink` and other servers built on Core.
- **Semver.** Pre-1.0: a **minor** bump may change the `ISessionManager` interface, capability shapes, or `Tool[]` registration order; a **patch** will not. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- - The `error.code` enum (the SSOT exported as `ERROR_CODES`) — adding a new code is non-breaking; renaming or removing one is breaking.
- - The `{ ok, result/error, meta }` response envelope and `meta.schemaVersion` major component.
+ - The `error.code` enum (the SSOT exported as `ErrorCodes`) — adding a new code is non-breaking; renaming or removing one is breaking.
+ - The `{ ok, result/error, meta }` response envelope.
- Tool names and the **shape** of each tool's `inputSchema` (adding optional fields is non-breaking; renaming or making a field required is breaking).
- The 9 capability interfaces (`OnChainCapability`, `MultiSigCapability`, …) — adding an optional method is non-breaking.
- **Volatile contracts** (may change at any time):
- Internal helper exports under `src/internal/*`, `Knowledge Store` keys, recipe-runner internals.
- Pre-check error `details` strings (branch on `code`, not `details.reason`).
-- **Deprecation window.** A deprecated tool / field / capability method stays present for at least one minor cycle alongside its replacement, marked with `meta.deprecated` in `list_tools` output; removal lands no earlier than the cycle after.
-- **Adopting downstream.** Bump the `@tronlink/tronlink-mcp-core` peer / dependency only after re-running your downstream's `list_tools` snapshot test against the new core; assert `meta.schemaVersion` major matches the version your harness was written for.
+- **Deprecations.** [@tronlink/tronlink-mcp-core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Upgrading Core.** Record the installed package version. Compare `tools/list` against the tool names and input schemas your client uses, then check that the client handles a successful result and an error from a read-only tool.
diff --git a/docs/ai-support/tronlink-mcp-core.zh.md b/docs/ai-support/tronlink-mcp-core.zh.md
index 54b6671..71f12dd 100644
--- a/docs/ai-support/tronlink-mcp-core.zh.md
+++ b/docs/ai-support/tronlink-mcp-core.zh.md
@@ -357,7 +357,7 @@ interface GasFreeCapability {
## 标准化响应格式
-所有工具返回一致的结构:
+[Core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) 的调用方先检查 `ok`,再读取 `result` 或 `error`。失败时读取 `error.code` 和 `error.message`,`error.details` 为可选字段。响应元数据包含 `timestamp`、`sessionId` 和 `durationMs`。
```typescript
// 成功
@@ -366,7 +366,7 @@ interface GasFreeCapability {
result: { /* 工具特定数据 */ },
meta: {
timestamp: "2026-03-09T10:15:23.456Z",
- sessionId: "tl-1741504523",
+ sessionId: "tl-1773051323",
durationMs: 234
}
}
@@ -377,11 +377,9 @@ interface GasFreeCapability {
error: {
code: "TL_CLICK_FAILED", // 稳定错误码 — 见下表
message: "Element not found",
- retryable: false, // 给 agent 的显式提示
- hint: "重新生成可达性快照并用新的 a11yRef 重试。",
details: { /* 可选 */ }
},
- meta: { timestamp, sessionId, durationMs, schemaVersion: "1.0" }
+ meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1773051323", durationMs: 234 }
}
```
@@ -389,7 +387,7 @@ interface GasFreeCapability {
### 错误码
-这是本框架所有工具返回错误码的**唯一数据源**(SSOT)。基于本框架的下游 server(`mcp-server-tronlink`)继承这些错误码并可扩展自有错误码;`mcp-tronlink-signer` 是独立的 server,不使用这些错误码。`retryable` 反映框架层面的安全性,agent 仍**必须**叠加调用工具的副作用分级——无论 `retryable` 为何,**结果未确认的 Remote Write 绝不能自动重试**。
+本表是 Core 错误码及其重试规则的唯一权威来源(SSOT)。根据返回的 `error.code` 查下表,判断是否可重试以及如何恢复。**Retryable** 和 **Hint** 是文档中的两列。Core 0.1.0 的响应不包含 `error.retryable`、`error.hint` 或 `meta.schemaVersion`。远程写操作结果未知时,先核对交易状态,再决定是否重试。基于 Core 的下游服务(如 `mcp-server-tronlink`)可以扩展此表;独立的 `mcp-tronlink-signer` 使用自己的错误格式。
| 错误码 | Retryable | Hint | 典型触发 |
|---|:---:|---|---|
@@ -405,8 +403,8 @@ interface GasFreeCapability {
| `TL_WAIT_TIMEOUT` | true | 提高超时或换一个 selector。 | `tl_wait_for`、`tl_wait_for_notification` |
| `TL_SCREENSHOT_FAILED` | true | 偶发故障;可重试。 | `tl_screenshot`、`tl_describe_screen` |
| `TL_CAPABILITY_NOT_AVAILABLE` | false | 当前 session 未注入该 capability;重配后重启。 | 依赖可选 capability 的工具 |
-| `TL_CHAIN_QUERY_FAILED` | true | TronGrid 暂时不可用或限流;退避后重试。 | `tl_chain_get_*` |
-| `TL_CHAIN_SEND_FAILED` | false | **禁止**自动重试。先用 `tl_chain_get_tx` 确认上一笔是否落账。 | `tl_chain_send`、`tl_chain_stake`、`tl_chain_resource` |
+| `TL_CHAIN_QUERY_FAILED` | true | TronGrid 暂时不可用或限流;退避后重试。**例外:** `tl_chain_resource` 的代理/取消代理写操作失败时也返回此码,应按 `TL_CHAIN_SEND_FAILED` 处理,先核对交易再决定是否重新发起。 | `tl_chain_get_*`、`tl_chain_resource` |
+| `TL_CHAIN_SEND_FAILED` | false | **禁止**自动重试。先用 `tl_chain_get_tx` 确认上一笔是否落账。 | `tl_chain_send`、`tl_chain_stake` |
| `TL_CHAIN_SWAP_FAILED` | false | 同上——重试前必须确认前一笔未落账。 | `tl_chain_swap`、`tl_chain_swap_v3` |
| `TL_GASFREE_QUERY_FAILED` | true | 偶发故障;可重试。 | `tl_gasfree_get_account`、`tl_gasfree_get_transactions` |
| `TL_GASFREE_SEND_FAILED` | false | **禁止**自动重试;先向 GasFree 查询最新状态。 | `tl_gasfree_send` |
@@ -418,7 +416,7 @@ interface GasFreeCapability {
下游 server 扩展自定义错误码必须满足:
- 不复用上表错误码表达不同含义。
-- 每个新错误码必须声明 `retryable`。
+- 为每个新增错误码写明重试条件和恢复步骤。
- major 版本内含义稳定。
- 新错误码在使用方文档说明,禁止悄悄引入。
@@ -609,16 +607,16 @@ npm run clean # 删除 dist/
### 兼容性与迁移策略
-本包是 `mcp-server-tronlink` 及任何下游 MCP server 在工具 schema、错误码、`meta.schemaVersion` 上的 **SSOT**,兼容面比普通库更宽:
+本包定义了 `mcp-server-tronlink` 及其他下游服务使用的工具 schema、错误码和响应结构。
- **语义化版本。** 1.0 之前:**minor** 升级可能改 `ISessionManager` 接口、能力 shape、`Tool[]` 注册顺序;**patch** 不会。1.0 之后:标准 semver,仅 major 允许破坏。
- **稳定契约**(patch 不会动):
- - `error.code` 枚举(导出为 `ERROR_CODES`,SSOT)——新增 code 非破坏;改名或删除是破坏。
- - `{ ok, result/error, meta }` 响应包络与 `meta.schemaVersion` 的 major 分量。
+ - `error.code` 枚举(导出为 `ErrorCodes`,SSOT)——新增 code 非破坏;改名或删除是破坏。
+ - `{ ok, result/error, meta }` 响应结构。
- 工具名与各工具 `inputSchema` 的**结构**——新增可选字段非破坏;改名或将字段改必填是破坏。
- 9 个能力接口(`OnChainCapability`、`MultiSigCapability`…)——新增可选方法非破坏。
- **不稳定契约**(随时可能变化):
- `src/internal/*` 下的内部 helper 导出、Knowledge Store key、recipe-runner 内部。
- 预检查错误 `details` 文本(分支用 `code`,别用 `details.reason`)。
-- **废弃窗口。** 废弃的工具 / 字段 / 能力方法在 `list_tools` 中带 `meta.deprecated` 标记,至少保留 **一个 minor 周期** 与替代并存,移除最早发生在再下一周期。
-- **下游升级。** 升级 `@tronlink/tronlink-mcp-core` 之前,先在下游对新 core 跑一遍 `list_tools` 快照测试;断言 `meta.schemaVersion` major 与你的 harness 编写时一致。
+- **弃用检查。** [@tronlink/tronlink-mcp-core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
+- **下游升级。** 记录实际安装的包版本。用 `tools/list` 核对客户端依赖的工具名和输入 schema,再用只读工具的成功与失败响应检验客户端的处理逻辑。
diff --git a/docs/ai-support/tronlink-signer.en.md b/docs/ai-support/tronlink-signer.en.md
index 1b03218..c99089e 100644
--- a/docs/ai-support/tronlink-signer.en.md
+++ b/docs/ai-support/tronlink-signer.en.md
@@ -12,18 +12,26 @@ npm install tronlink-signer
## Quick Start
+On Nile, select a funded test account and set the Node.js environment variable `RECIPIENT` to your test recipient’s address. This example requests approval to send 1 test TRX.
+
```ts
import { TronSigner } from "tronlink-signer";
+const recipient = process.env.RECIPIENT;
+if (!recipient) throw new Error("Set RECIPIENT to the Nile recipient address");
const signer = new TronSigner();
await signer.start();
-const { address, network } = await signer.connectWallet();
-const { txId, status } = await signer.sendTrx("TXxx...", 1); // status: "success" | "pending" | "failed"
-const { txId: txId2, status: s2 } = await signer.signTransaction(tx, "nile", true); // broadcast + auto-confirm
-const { balance } = await signer.getBalance("TXxx...");
-
-await signer.stop();
+try {
+ const { address } = await signer.connectWallet("nile");
+ const { balance } = await signer.getBalance(address, "nile");
+ console.log(address, balance);
+ // Signer takes TRX, so this sends 1 TRX.
+ const { txId, status } = await signer.sendTrx(recipient, 1, "nile");
+ console.log(txId, status);
+} finally {
+ await signer.stop();
+}
```
## API
@@ -102,25 +110,51 @@ Signs a raw transaction. When `broadcast` is `true`, the signed transaction is b
| `broadcast` | `boolean` | Whether to broadcast after signing (default: `false`) |
| `options` | `SignerOptions` | Optional — cancellation, confirmation control, broadcast callback |
-```ts
+To build an unsigned Nile transfer in Node.js, install `tronlink-signer` and `tronweb@6`. Select the funded Nile payer in TronLink and set `RECIPIENT` to the intended Nile recipient address. Run this setup followed by one calling pattern in the same ES module.
+
+```js
+import { TronSigner } from "tronlink-signer";
+import { TronWeb } from "tronweb";
+
+const signer = new TronSigner();
+const tronWeb = new TronWeb({ fullHost: "https://nile.trongrid.io" });
+const recipient = process.env.RECIPIENT;
+if (!TronWeb.isAddress(recipient)) throw new Error("Set RECIPIENT to a TRON address");
+await signer.start();
+const { address } = await signer.connectWallet("nile");
+// The builder takes SUN, so this creates a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronWeb.transactionBuilder.sendTrx(recipient, 10, address);
+```
+
+Choose one of the following calling patterns.
+
+```js
// Sign only
-const { signedTransaction } = await signer.signTransaction(tx);
+const { signedTransaction } = await signer.signTransaction(tx, "nile");
+```
+```js
// Sign, broadcast, and wait for confirmation (default)
const { signedTransaction, txId, status, error } = await signer.signTransaction(tx, "nile", true);
// status === "success" — confirmed on-chain
// status === "pending" — broadcast succeeded but not confirmed within timeout
// status === "failed" — on-chain execution failed; `error` carries the reason
+```
+```js
// Broadcast without waiting for confirmation
const result = await signer.signTransaction(tx, "nile", true, { confirm: false });
+```
+```js
// Get notified as soon as the tx enters the mempool
const result = await signer.signTransaction(tx, "nile", true, {
onBroadcasted: ({ txId }) => console.log("Broadcast:", txId),
});
```
+Wrap connection, construction and the selected call in `try / finally`, and call `await signer.stop()` in `finally` as in Quick Start. If a broadcast outcome is unknown, look up the transaction ID before taking further action.
+
### Broadcast Result
Broadcasting methods (`sendTrx`, `sendTrc20`, and `signTransaction` with `broadcast: true`) return a `BroadcastResult`:
diff --git a/docs/ai-support/tronlink-signer.zh.md b/docs/ai-support/tronlink-signer.zh.md
index bd758a8..55038eb 100644
--- a/docs/ai-support/tronlink-signer.zh.md
+++ b/docs/ai-support/tronlink-signer.zh.md
@@ -12,18 +12,26 @@ npm install tronlink-signer
## 快速开始
+在 Nile 选择有测试币的账户,并将 Node.js 环境变量 `RECIPIENT` 设为测试收款地址。此示例会请求授权转出 1 个测试 TRX。
+
```ts
import { TronSigner } from "tronlink-signer";
+const recipient = process.env.RECIPIENT;
+if (!recipient) throw new Error("Set RECIPIENT to the Nile recipient address");
const signer = new TronSigner();
await signer.start();
-const { address, network } = await signer.connectWallet();
-const { txId, status } = await signer.sendTrx("TXxx...", 1); // status: "success" | "pending" | "failed"
-const { txId: txId2, status: s2 } = await signer.signTransaction(tx, "nile", true); // 广播 + 自动确认
-const { balance } = await signer.getBalance("TXxx...");
-
-await signer.stop();
+try {
+ const { address } = await signer.connectWallet("nile");
+ const { balance } = await signer.getBalance(address, "nile");
+ console.log(address, balance);
+ // Signer 以 TRX 为单位,这里发送 1 TRX。
+ const { txId, status } = await signer.sendTrx(recipient, 1, "nile");
+ console.log(txId, status);
+} finally {
+ await signer.stop();
+}
```
## API
@@ -102,25 +110,51 @@ const { signature } = await signer.signTypedData({
| `broadcast` | `boolean` | 签名后是否广播(默认:`false`) |
| `options` | `SignerOptions` | 可选 — 取消、确认控制、广播回调 |
-```ts
+在 Node.js 中构建 Nile 未签名转账前,请安装 `tronlink-signer` 和 `tronweb@6`,在 TronLink 选择有测试币的 Nile 付款账户,并将 `RECIPIENT` 设为预期的 Nile 收款地址。在同一个 ES 模块中运行以下准备代码,再选一种调用方式。
+
+```js
+import { TronSigner } from "tronlink-signer";
+import { TronWeb } from "tronweb";
+
+const signer = new TronSigner();
+const tronWeb = new TronWeb({ fullHost: "https://nile.trongrid.io" });
+const recipient = process.env.RECIPIENT;
+if (!TronWeb.isAddress(recipient)) throw new Error("Set RECIPIENT to a TRON address");
+await signer.start();
+const { address } = await signer.connectWallet("nile");
+// 交易构建器以 SUN 为单位,这里构建 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+const tx = await tronWeb.transactionBuilder.sendTrx(recipient, 10, address);
+```
+
+以下为不同调用方式,请选择一种使用。
+
+```js
// 仅签名
-const { signedTransaction } = await signer.signTransaction(tx);
+const { signedTransaction } = await signer.signTransaction(tx, "nile");
+```
+```js
// 签名、广播并等待确认(默认行为)
const { signedTransaction, txId, status, error } = await signer.signTransaction(tx, "nile", true);
// status === "success" — 已在链上确认
// status === "pending" — 广播成功但在超时时间内未被确认
// status === "failed" — 链上执行失败;`error` 包含失败原因
+```
+```js
// 广播但不等待确认
const result = await signer.signTransaction(tx, "nile", true, { confirm: false });
+```
+```js
// 在交易进入内存池时立即收到通知
const result = await signer.signTransaction(tx, "nile", true, {
onBroadcasted: ({ txId }) => console.log("Broadcast:", txId),
});
```
+参照快速开始,用 `try / finally` 包住连接、构建及所选调用,在 `finally` 中执行 `await signer.stop()`。广播结果未知时先按交易 ID 查询状态。
+
### 广播结果
diff --git a/docs/ai-support/tronlink-skills.en.md b/docs/ai-support/tronlink-skills.en.md
index 26e468e..35beaed 100644
--- a/docs/ai-support/tronlink-skills.en.md
+++ b/docs/ai-support/tronlink-skills.en.md
@@ -4,13 +4,13 @@
**GitHub**: [https://github.com/TronLink/tronlink-skills](https://github.com/TronLink/tronlink-skills)
-> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `7d2d58cb`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.1**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
+> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `b12b5868`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.3**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
**TronLink Wallet Skills** is an AI Agent skill set that provides complete TRON blockchain wallet and DeFi functionality through natural language. Designed for Claude Code, Cursor, OpenCode, Codex CLI, and other AI agents.
**Key Highlights:**
- **6 skills, 33 commands** covering wallet, token research, market data, swaps, resources, and staking
-- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.1 — see [Dependencies](#dependencies)), no `npm install` needed
+- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.3 — see [Dependencies](#dependencies)), no `npm install` needed
- **TRON-specific domain knowledge** — dedicated handling of Energy + Bandwidth resource model
- **Multi-platform support** — Claude Code, Cursor, OpenCode, Codex CLI, LangChain/CrewAI
- **Read-only & safe** — all commands are query-only, no private keys or signing involved
@@ -41,7 +41,7 @@ Natural Language Input
AI Agent (Claude Code / Cursor / OpenCode / Custom)
|
v
-tron_api.mjs (Node.js 24.22.1, native fetch, zero dependencies)
+tron_api.mjs (Node.js 24.22.3, native fetch, zero dependencies)
├── Zero npm dependencies
├── TronGrid HTTP API (public or with API key)
└── Tronscan API for token metadata
@@ -69,7 +69,7 @@ Wallet queries and account information.
**Features:** Handles both Base58Check (T...) and hex address formats, supports known token symbols, auto-converts decimals.
-**When NOT to use:** Sending TRX/tokens — these are read-only; use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md). For deep token-level analytics (rug-pull / liquidity locks), prefer `tron-token`.
+**When NOT to use:** To transfer TRX or TRC-20 tokens with browser approval, use [Signer SDK](tronlink-signer.en.md) `sendTrx` or `sendTrc20`. For a local agent wallet, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_send`. Use `tron-token` for token risk and liquidity analysis.
### 2. tron-token (7 commands)
@@ -120,7 +120,7 @@ DEX swap quotes and route optimization.
**Features:** Aggregates liquidity from multiple sources, estimates Energy cost, handles multi-hop routes.
-**When NOT to use:** Executing the swap — quotes are read-only; the swap itself goes through [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_swap_v3`) or the signer SDK. Historical trade data — `tron-market`.
+**When NOT to use:** To execute a swap, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and a user-approved `slippage`. Use `tron-market` for historical trade data.
### 5. tron-resource (6 commands)
@@ -137,7 +137,7 @@ Energy & Bandwidth management — TRON-specific.
**Features:** Decision tree logic for cost optimization, tracks daily free bandwidth, calculates TRX burn equivalent.
-**When NOT to use:** Actually freezing TRX to acquire Energy/Bandwidth — that's a Remote Write; use the signer SDK / MCP Server. SR voting strategy after freezing — see `tron-staking`.
+**When NOT to use:** To freeze TRX for Energy or Bandwidth, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` with `action="freeze"`. Use `tron-staking` to research SRs before voting.
### 6. tron-staking (3 commands)
@@ -151,13 +151,13 @@ Stake 2.0 queries and SR information.
**Features:** Stake 2.0 status queries, APY calculation, SR commission tracking.
-**When NOT to use:** Performing the freeze/vote/unfreeze actions — those are Remote Writes; route through the signer SDK / MCP Server. Calculating Energy cost per operation — `tron-resource`.
+**When NOT to use:** Cast votes with [TronLink CLI](tronlink-cli.en.md) `tronlink vote` and claim voting rewards with `tronlink reward`. To freeze or unfreeze TRX, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake`. Use `tron-resource` for energy estimates.
---
## Skill ↔ MCP Tool Map
-`scripts/mcp_server.mjs` (the wrapper from [Method 2](#method-2-mcp-server)) exposes **25 of the 33 commands** as MCP tools — every signature, every input field, every output shape is generated from the same `tron_api.mjs` implementation, so the CLI and the MCP tool are guaranteed equivalent. The 8 CLI-only commands stay reachable through Method 1 (skill prompt) and Method 3 (direct CLI). Use this table when an agent needs to route a user request to a specific tool or when you're inspecting `tools/list` output.
+In the v1.0.x command set, `scripts/mcp_server.mjs` exposes **25 of 33 CLI commands** as MCP tools. At the default-branch commit `b12b5868`, it exposes 39 of 40 commands; only `swap-route` is CLI-only, so the “CLI-only” markers below apply to v1.0.x. The wrapper runs the corresponding CLI command and returns text in an MCP tool result. The remaining eight commands are available through the Skills or the CLI.
| Skill | CLI command | MCP tool name | Side effect | Retryable |
|---|---|---|---|:---:|
@@ -195,7 +195,7 @@ Stake 2.0 queries and SR information.
| `tron-staking` | `staking-info` | `tron_staking_info` | Network Read | Yes |
| `tron-staking` | `staking-apy` | `tron_staking_apy` | Network Read | Yes |
-**Totals.** 33 CLI commands · 25 MCP tools · 8 CLI-only commands. Every command is read-only — no signing, no broadcast, no fund movement. To execute a transaction, route to [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_*`) or [signer SDK](tronlink-signer.md) (`sendTrx`, `sendTrc20`, `sign*`).
+The v1.0.x table covers 33 read-only CLI commands, including 25 available over MCP. Use the routing examples below for transactions.
### Intent → Skill → Tool Routing
@@ -229,16 +229,16 @@ If the request implies **changing on-chain state** (transfer, swap execution, fr
### ❌ When NOT to route here (negative examples)
-Skills are **read-only**. If the user intent implies a signed / Remote Write action, do **not** dispatch to a skill — the underlying command will succeed but only as a query/estimate, and the user's actual goal will go unfulfilled. Route to the signer SDK or `mcp-server-tronlink` instead:
+Use Skills for queries and estimates. For actions that sign or broadcast, choose the route below. The [TronLink CLI](tronlink-cli.en.md) and signer SDK use browser approval. MCP Server direct chain tools sign with the local agent wallet, so the host must obtain confirmation before the call.
| User says (intent) | ❌ Wrong route (looks plausible, but read-only) | ✅ Correct route |
|---|---|---|
-| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.md) `tl_chain_send` |
-| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | `mcp-server-tronlink` `tl_chain_stake` (Remote Write, HITL) |
-| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | `mcp-server-tronlink` `tl_chain_stake` / signer SDK `signTransaction` |
-| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [signer SDK](tronlink-signer.md) `signTransaction` or `mcp-server-tronlink` `tl_chain_send` |
-| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | `mcp-server-tronlink` `tl_chain_swap_v3` (Remote Write, HITL, set `minOut`) |
-| "Claim my staking rewards" | `tron-staking staking-info` — only shows the pending balance. | `mcp-server-tronlink` `tl_chain_stake` (withdraw / claim) or signer SDK |
+| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.en.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.en.md) `tl_chain_send` |
+| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` (`action="freeze"`, `amount_trx=1000`, `resource="ENERGY"`) |
+| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | [TronLink CLI](tronlink-cli.en.md) `tronlink vote --votes :5000`. A vote replaces all of the account’s current votes; to keep votes for other SRs, list them in the same command. |
+| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [TronLink CLI](tronlink-cli.en.md) `tronlink trigger --contract --method 'approve(address,uint256)' --args '["","1000000"]'`. Use the token and router on the selected network. The router is the spender. For 6-decimal USDT, `1000000` authorizes 1 USDT. |
+| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and an explicitly approved `slippage` (%) |
+| "Claim my voting rewards" | `tron-staking staking-info` — only shows the pending balance. | [TronLink CLI](tronlink-cli.en.md) `tronlink reward` |
**Heuristic.** If the user's verb is *send / freeze / unfreeze / vote / unvote / approve / swap (execute) / claim / sign / broadcast*, the answer never starts in this Skills set. Skills can still **precede** the write (quote, estimate cost, validate address, check balance) — just don't claim a Skills call finished the user's request.
@@ -292,8 +292,8 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
- Freeze TRX → Get Energy or Bandwidth → Vote for SR → Earn rewards
- Unfreezing has **14-day wait** before withdrawal
- Votes reset if you unfreeze; must re-vote after re-freezing
-- 1 frozen TRX ≈ 4.5 Energy/day — **dynamic**: depends on total network stake; use `tron-resource estimate-energy` for the live value. Effective figure as of 2026-05.
-- Voting rewards claimable every 6 hours
+- Energy obtained by staking depends on the network’s current stake. Estimate the quota per TRX from `TotalEnergyLimit / TotalEnergyWeight` on the target network. `estimate-energy` estimates a contract call’s consumption. [GetAccountResource](https://developers.tron.network/reference/getaccountresource)
+- Voting rewards can be claimed once every 24 hours
---
@@ -303,8 +303,11 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
```bash
# Clone and use directly
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
claude # Auto-discovers SKILL.md files
```
@@ -316,8 +319,8 @@ No `npm install` needed for read-only operations.
# Register as MCP server
claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
-# Provides 25 MCP tools callable by Claude Desktop / Claude Code
-# (see "Skill ↔ MCP Tool Map" above for the per-command mapping; 8 commands are CLI-only)
+# Provides 39 MCP tools at b12b5868 (25 in v1.0.x), callable by Claude Desktop / Claude Code
+# (only swap-route is CLI-only at b12b5868; see "Skill ↔ MCP Tool Map" above for the v1.0.x mapping)
```
### Method 3: Manual CLI
@@ -325,10 +328,16 @@ claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
```bash
# Direct command execution
node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs swap-quote --from TRX --to USDT --amount 100
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs swap-quote --from-token TRX --to-token USDT --amount 100
```
+#### Handling Skills CLI and MCP errors
+
+In Skills v1.1.0 (`b12b5868`), an unknown CLI command or a missing required option exits with `1` and writes a diagnostic to stderr. A command can also exit with `0` and return an error in stdout. For example, `staking-apy --amount 0` returns JSON with `error`, `status: 400`, and `parameter: "amount"`. For a data query, check the exit status first, then parse stdout and check for `error` before using the result. [Skills CLI implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/tron_api.mjs)
+
+For MCP `tools/call`, check for a JSON-RPC error first (an unknown tool returns `-32602`). For a recognized tool, parse the JSON in `result.content[0].text` and check its `error` field. The wrapper can return command failures in this text with no `isError` flag. [Skills MCP implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/mcp_server.mjs)
+
### Method 4: Other AI Platforms
| Platform | Integration |
@@ -385,7 +394,10 @@ def tron_call(cmd: str) -> dict:
["node", "scripts/tron_api.mjs", *cmd.split()],
cwd="/absolute/path/to/tronlink-skills",
)
- return json.loads(out)
+ result = json.loads(out)
+ if isinstance(result, dict) and "error" in result:
+ raise RuntimeError(result["error"])
+ return result
tron_wallet_balance = Tool.from_function(
func=lambda addr: tron_call(f"wallet-balance --address {addr}"),
@@ -483,7 +495,7 @@ tronlink-skills/
| Dependency | Required? | Purpose |
|------------|-----------|---------|
-| Node.js 24.22.1 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.1 && nvm use 24.22.1` before installing. |
+| Node.js 24.22.3 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.3 && nvm use 24.22.3` before installing. |
| npm install | Not needed | All operations work without any npm dependencies |
---
@@ -496,7 +508,7 @@ tronlink-skills/
| Side effects | Every command is **Network Read**: it calls public APIs but changes no state. All commands are safe to retry; no human-in-the-loop confirmation is needed |
| No secrets required | Only optional TRONGRID_API_KEY for higher rate limits |
| Rate limits | Public TronGrid API; use TRONGRID_API_KEY for higher limits |
-| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). To execute a transaction (transfer, swap, stake), use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md) — these skills never sign or broadcast |
+| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). |
---
@@ -527,28 +539,31 @@ Both formats are supported and auto-normalized across all commands:
```bash
# 1. Clone
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
# 2. Use with Claude Code (no install needed for reads)
claude
-> "What's the TRX balance of TAddress...?"
-> "Show me the top trending tokens on TRON"
-> "How much Energy do I need to send USDT?"
-> "What's the best way to get Energy — freeze, rent, or burn?"
-
-# 3. Or use directly
-node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs optimize-cost --address TAddress...
+# "What's the TRX balance of TAddress...?"
+# "Show me the top trending tokens on TRON"
+# "How much Energy do I need to send USDT?"
+# "What's the best way to get Energy — freeze, rent, or burn?"
+
+# 3. Alternatively, run these in the shell. Set ACCOUNT to the address to query.
+node scripts/tron_api.mjs wallet-balance --address "${ACCOUNT:?set ACCOUNT}"
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs optimize-cost --address "${ACCOUNT:?set ACCOUNT}"
```
## Version & License
- **Package:** `tronlink-skills` v1.0.1 — the version the command tables on this page describe.
-- **Default branch:** v1.1.0 (commit `7d2d58cb`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
- - 7 additional read-only commands, also exposed as `tron_` MCP tools: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
- - Node.js is pinned to exactly 24.22.1 (`.nvmrc`, `engines`); `install.sh` exits on any other version.
+- **Default branch:** v1.1.0 (commit `b12b5868`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
+ - 7 additional read-only commands, also exposed as `tron_` MCP tools. At this commit `mcp_server.mjs` exposes 39 of the 40 commands; only `swap-route` is CLI-only. The new commands: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
+ - For this commit, [`.nvmrc`](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/.nvmrc) specifies Node.js 24.22.3. To reproduce [commit `7d2d58cb`](https://github.com/TronLink/tronlink-skills/blob/7d2d58cb/.nvmrc), use Node.js 24.22.1. Run `nvm install && nvm use` in the checked-out repository to select its pinned version.
- **License:** MIT — `SPDX-License-Identifier: MIT`
- **Changelog / releases:** [https://github.com/TronLink/tronlink-skills/releases](https://github.com/TronLink/tronlink-skills/releases) — no GitHub-tagged releases yet for v1.0.x; track changes by commit until the first tag.
@@ -559,12 +574,11 @@ Skills are at **v1.0.x**, so standard semver applies — only **major** bumps ma
- **Stable contracts** (won't change in a minor or patch):
- The 33 CLI command names and their required / optional flags (`tron_api.mjs [...]`).
- The 25 MCP tool names listed in [Skill ↔ MCP Tool Map](#skill-mcp-tool-map) (`tron_*` form) and their `inputSchema` keys.
- - Exit codes: `0` success, `1` query error / invalid input, `2` unsupported / unknown command.
- The `Network Read` side-effect classification — no command will ever become a Remote Write without a major bump.
- **Volatile contracts** (may change in a minor):
- The exact field layout of JSON `stdout` payloads — new fields can be added in any minor; renames or removals are major. Use a tolerant parser.
- Built-in token-symbol shortcut list (`USDT`, `USDC`, `WTRX`, …) — symbols may be added in any minor; existing mappings won't be repointed in a minor.
- Heuristics and thresholds (`whale-transfers` default cutoff, `optimize-cost` decision tree weights, etc.).
-- **Subset relationship.** The MCP tool subset (currently 25 of 33) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
+- **Subset relationship.** The MCP tool subset (25 of 33 in v1.0.x; 39 of 40 at `b12b5868`) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
- **Deprecation window.** A command / tool marked deprecated continues to work for at least one minor cycle. Removal lands no earlier than the next major.
- **Verifying after upgrade.** Re-run `tron_api.mjs --help` and (if using MCP) `tools/list` to confirm the names you depend on are still present. The MCP `serverInfo.version` exposed during `initialize` should match the bumped `package.json` version.
diff --git a/docs/ai-support/tronlink-skills.zh.md b/docs/ai-support/tronlink-skills.zh.md
index 3834cb9..952131f 100644
--- a/docs/ai-support/tronlink-skills.zh.md
+++ b/docs/ai-support/tronlink-skills.zh.md
@@ -4,13 +4,13 @@
**GitHub**: [https://github.com/TronLink/tronlink-skills](https://github.com/TronLink/tronlink-skills)
-> **版本范围。** 本页的命令说明(6 大技能、33 个命令)基于 **v1.0.x** 编写。默认分支(即 `git clone` 和 `install.sh` 安装的版本)现为 **v1.1.0**(commit `7d2d58cb`):新增 7 个只读命令(共 40 个),并要求精确版本 **Node.js 24.22.1**。详见文末「版本与许可证」;以你本地安装版本的 `tron_api.mjs --help` / MCP `tools/list` 为准。
+> **版本范围。** 本页的命令说明(6 大技能、33 个命令)基于 **v1.0.x** 编写。默认分支(即 `git clone` 和 `install.sh` 安装的版本)现为 **v1.1.0**(commit `b12b5868`):新增 7 个只读命令(共 40 个),并要求精确版本 **Node.js 24.22.3**。详见文末「版本与许可证」;以你本地安装版本的 `tron_api.mjs --help` / MCP `tools/list` 为准。
**TronLink Wallet Skills** 是一套 AI Agent 技能集,通过自然语言提供完整的 TRON 区块链钱包和 DeFi 功能。专为 Claude Code、Cursor、OpenCode、Codex CLI 及其他 AI 代理设计。
**核心亮点:**
- **6 大技能,33 个命令**,涵盖钱包、代币研究、市场数据、兑换、资源和质押
-- **零 npm 依赖**:使用原生 Node.js `fetch` 和 `crypto`(要求精确版本 Node.js 24.22.1,见下方「依赖项」),无需 `npm install`
+- **零 npm 依赖**:使用原生 Node.js `fetch` 和 `crypto`(要求精确版本 Node.js 24.22.3,见下方「依赖项」),无需 `npm install`
- **TRON 专属领域知识** — 专门处理能量 + 带宽资源模型
- **多平台支持** — Claude Code、Cursor、OpenCode、Codex CLI、LangChain/CrewAI
- **纯只读安全设计**:所有命令均为查询操作,不涉及私钥或签名
@@ -41,7 +41,7 @@ TronLink Skills 以深度 TRON 领域知识填补了这一空白。
AI 代理 (Claude Code / Cursor / OpenCode / 自定义)
|
v
-tron_api.mjs (Node.js 24.22.1, 原生 fetch, 零依赖)
+tron_api.mjs (Node.js 24.22.3, 原生 fetch, 零依赖)
├── 零 npm 依赖
├── TronGrid HTTP API(公共或带 API Key)
└── Tronscan API 用于代币元数据
@@ -69,7 +69,7 @@ tron_api.mjs (Node.js 24.22.1, 原生 fetch, 零依赖)
**特点:** 同时支持 Base58Check(T...)和 hex 地址格式,内置常用代币符号,自动转换精度。
-**何时不要用:** 发送 TRX / 代币——这些命令是只读的,请走 [signer SDK](tronlink-signer.md) 或 [MCP Server TronLink](mcp-server-tronlink.md)。代币层面的深度分析(rug-pull / 流动性锁定)请用 `tron-token`。
+**何时不要用:** 转出 TRX 或 TRC-20 代币并由用户在浏览器中批准时,使用 [Signer SDK](tronlink-signer.zh.md) 的 `sendTrx` 或 `sendTrc20`。使用本地 agent 钱包时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_send`。代币风险与流动性分析使用 `tron-token`。
### 2. tron-token(7 个命令)
@@ -120,7 +120,7 @@ DEX 兑换报价与路由优化。
**特点:** 聚合多源流动性、估算能量成本、处理多跳路由。
-**何时不要用:** 真正执行 swap——报价是只读的,实际兑换走 [MCP Server TronLink](mcp-server-tronlink.md)(`tl_chain_swap_v3`)或 signer SDK;历史成交数据——`tron-market`。
+**何时不要用:** 执行兑换时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_swap_v3`,将 `action` 设为 `"execute"`,并按用户确认的滑点百分比填写 `slippage`。历史成交数据使用 `tron-market`。
### 5. tron-resource(6 个命令)
@@ -137,7 +137,7 @@ DEX 兑换报价与路由优化。
**特点:** 成本优化决策树逻辑、追踪每日免费带宽、计算 TRX 燃烧等值。
-**何时不要用:** 真正冻结 TRX 获取能量/带宽——那是 Remote Write,请走 signer SDK / MCP Server;冻结后的 SR 投票策略——见 `tron-staking`。
+**何时不要用:** 冻结 TRX 获取能量或带宽时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`,将 `action` 设为 `"freeze"`。投票前查询超级代表信息可使用 `tron-staking`。
### 6. tron-staking(3 个命令)
@@ -151,7 +151,7 @@ Stake 2.0 查询与 SR 信息。
**特点:** Stake 2.0 状态查询、APY 计算、SR 佣金追踪。
-**何时不要用:** 执行 freeze / 投票 / 解冻动作——这些是 Remote Write,请走 signer SDK / MCP Server;单次操作能量成本——`tron-resource`。
+**何时不要用:** 投票使用 [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink vote`,领取投票奖励使用同一 CLI 的 `tronlink reward`。冻结或解冻 TRX 使用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`。估算能量消耗使用 `tron-resource`。
---
@@ -159,7 +159,7 @@ Stake 2.0 查询与 SR 信息。
## Skill ↔ MCP 工具映射
-`scripts/mcp_server.mjs`(即[方式二](#mcp)的封装)将 **33 个 CLI 命令中的 25 个** 暴露为 MCP 工具——签名、输入字段、输出结构都由同一份 `tron_api.mjs` 实现派生,因此 CLI 与 MCP 工具保证等价。剩余 8 个 CLI-only 命令仍可通过方式一(skill 提示词)和方式三(直接 CLI)使用。需要按用户提问路由到具体工具,或核对 `tools/list` 输出时,请用下表。
+在 v1.0.x 命令集中,`scripts/mcp_server.mjs` 将 **33 个 CLI 命令中的 25 个** 暴露为 MCP 工具。在默认分支提交 `b12b5868` 中,40 个命令里有 39 个暴露为 MCP 工具,只有 `swap-route` 仅限 CLI;下表中的“仅 CLI”标记针对 v1.0.x。包装层运行对应的 CLI 命令,以文本形式返回 MCP 工具结果。其余 8 个命令可通过 Skills 或 CLI 使用。
| Skill | CLI 命令 | MCP 工具名 | 副作用 | 可重试 |
|---|---|---|---|:---:|
@@ -197,7 +197,7 @@ Stake 2.0 查询与 SR 信息。
| `tron-staking` | `staking-info` | `tron_staking_info` | Network Read | 可 |
| `tron-staking` | `staking-apy` | `tron_staking_apy` | Network Read | 可 |
-**汇总。** 33 个 CLI 命令 · 25 个 MCP 工具 · 8 个仅 CLI 命令。所有命令都是只读——不签名、不广播、不动资金。若需执行交易,请路由到 [MCP Server TronLink](mcp-server-tronlink.md)(`tl_chain_*`)或 [signer SDK](tronlink-signer.md)(`sendTrx`、`sendTrc20`、`sign*`)。
+上表涵盖 v1.0.x 的 33 个只读 CLI 命令,其中 25 个也可通过 MCP 调用。需要发起交易时,按下方路由示例选择工具。
### 用户提问 → Skill → 工具路由
@@ -231,16 +231,16 @@ Stake 2.0 查询与 SR 信息。
### ❌ 不要走这里(反例)
-Skills 是**只读**的。如果用户意图涉及签名或 Remote Write,**不要**派发到 skill——底层命令会成功,但只是做了查询/估算,用户真正的目标并没有完成。这种意图请改路由到 signer SDK 或 `mcp-server-tronlink`:
+Skills 提供查询和估算。涉及签名或广播时,按下表选择工具。[TronLink CLI](tronlink-cli.zh.md) 和 signer SDK 通过浏览器请求用户批准。MCP Server 的直连链上工具使用本地 agent 钱包签名,宿主应用须在调用前取得用户确认。
| 用户提问(意图) | ❌ 误路由(看起来合理,但只读) | ✅ 正确路由 |
|---|---|---|
-| 「给 `T…` 转 100 TRX」 | `tron-wallet wallet-balance` 就停下——只查了余额,没转。 | [signer SDK](tronlink-signer.md) `sendTrx`(HITL)或 [`mcp-server-tronlink`](mcp-server-tronlink.md) `tl_chain_send` |
-| 「冻 1000 TRX 换能量」 | `tron-resource optimize-cost`——只算了建议,没冻。 | `mcp-server-tronlink` `tl_chain_stake`(Remote Write、HITL) |
-| 「给 SR `T…` 投 5000 票」 | `tron-staking sr-list`——只读了 SR 列表,没投票。 | `mcp-server-tronlink` `tl_chain_stake` / signer SDK `signTransaction` |
-| 「给 SunSwap 路由器授权 USDT 额度」 | `tron-token token-info` / `contract-info`——纯元数据查询,没发送 approve。 | [signer SDK](tronlink-signer.md) `signTransaction` 或 `mcp-server-tronlink` `tl_chain_send` |
-| 「现在把 100 TRX 换成 USDT」 | `tron-swap swap-quote`——只报了价,没执行。 | `mcp-server-tronlink` `tl_chain_swap_v3`(Remote Write、HITL,必传 `minOut`) |
-| 「领我的质押奖励」 | `tron-staking staking-info`——只看了待领数量。 | `mcp-server-tronlink` `tl_chain_stake`(withdraw / claim)或 signer SDK |
+| 「给 `T…` 转 100 TRX」 | `tron-wallet wallet-balance` 就停下——只查了余额,没转。 | [signer SDK](tronlink-signer.zh.md) `sendTrx`(HITL)或 [`mcp-server-tronlink`](mcp-server-tronlink.zh.md) `tl_chain_send` |
+| 「冻 1000 TRX 换能量」 | `tron-resource optimize-cost`——只算了建议,没冻。 | [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`(`action="freeze"`,`amount_trx=1000`,`resource="ENERGY"`) |
+| 「给 SR `T…` 投 5000 票」 | `tron-staking sr-list`——只读了 SR 列表,没投票。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink vote --votes :5000`。投票会替换该账户当前的全部投票;如需保留对其他 SR 的投票,请在同一条命令中一并列出。 |
+| 「给 SunSwap 路由器授权 USDT 额度」 | `tron-token token-info` / `contract-info`——纯元数据查询,没发送 approve。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink trigger --contract --method 'approve(address,uint256)' --args '["","1000000"]'`。代币合约和路由器地址须对应所选网络。路由器是被授权方;USDT 精度为 6 时,`1000000` 表示授权 1 USDT。 |
+| 「现在把 100 TRX 换成 USDT」 | `tron-swap swap-quote`——只报了价,没执行。 | [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_swap_v3`(`action="execute"`,`slippage` 填用户确认的滑点百分比) |
+| 「领取我的投票奖励」 | `tron-staking staking-info`——只看了待领数量。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink reward` |
**判断口诀。** 用户动词只要出现 *send / freeze / unfreeze / vote / unvote / approve / swap(执行)/ claim / sign / broadcast*,答案就**不在**这个 Skills 集里起步。Skills 仍然可以做**前置**(报价、估算成本、校验地址、查余额)——只是别声称"Skills 调用完成了用户的请求"。
@@ -294,8 +294,8 @@ tron-resource(检查状态)→ tron-resource(估算成本)→ tron-resou
- 冻结 TRX → 获取能量或带宽 → 投票给 SR → 赚取奖励
- 解冻需 **14 天等待期** 才能提取
- 解冻后投票重置;重新冻结后需重新投票
-- 1 冻结 TRX ≈ 每天 4.5 能量——**动态值**:取决于全网总质押量;实时数请用 `tron-resource estimate-energy`。数据截至 2026-05。
-- 投票奖励每 6 小时可领取一次
+- 质押所得能量取决于目标网络当前的质押总量。用该网络的 `TotalEnergyLimit / TotalEnergyWeight` 估算每质押 1 TRX 可获得的额度。`estimate-energy` 用于估算合约调用消耗。[GetAccountResource](https://developers.tron.network/reference/getaccountresource)
+- 投票奖励每 24 小时可领取一次
---
@@ -305,8 +305,11 @@ tron-resource(检查状态)→ tron-resource(估算成本)→ tron-resou
```bash
# 克隆后直接使用
-git clone
+# v1.1.0 需要 Git、nvm 和 Node.js 24.22.3;交互步骤还需安装 Claude Code。
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
claude # 自动发现 SKILL.md 文件
```
@@ -318,8 +321,8 @@ claude # 自动发现 SKILL.md 文件
# 注册为 MCP 服务器
claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
-# 提供 25 个 MCP 工具,可被 Claude Desktop / Claude Code 直接调用
-# (逐项对照见上文 "Skill ↔ MCP 工具映射";剩余 8 个命令仅 CLI 可用)
+# b12b5868 提供 39 个 MCP 工具(v1.0.x 为 25 个),可被 Claude Desktop / Claude Code 直接调用
+# (b12b5868 中只有 swap-route 仅限 CLI;v1.0.x 的逐项对照见上文 "Skill ↔ MCP 工具映射")
```
### 方式三:命令行直接使用
@@ -327,10 +330,16 @@ claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
```bash
# 直接执行命令
node scripts/tron_api.mjs wallet-balance --address T地址...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs swap-quote --from TRX --to USDT --amount 100
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs swap-quote --from-token TRX --to-token USDT --amount 100
```
+#### 处理 Skills CLI 和 MCP 错误
+
+在 Skills v1.1.0(`b12b5868`)中,未知 CLI 命令或缺少必填参数会向 stderr 输出原因,并以 `1` 退出。命令也可能以 `0` 退出,同时在 stdout 返回错误。例如,`staking-apy --amount 0` 返回的 JSON 包含 `error`、`status: 400` 和 `parameter: "amount"`。调用查询命令时,先检查退出码,再解析 stdout 中的 JSON;确认没有 `error` 后再使用结果。[Skills CLI 实现](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/tron_api.mjs)
+
+通过 MCP 调用 `tools/call` 时,先检查 JSON-RPC 错误(未知工具返回 `-32602`)。对于已识别的工具,再解析 `result.content[0].text` 中的 JSON,检查其中的 `error` 字段。包装层可以在这段文本中返回命令错误,同时省略 `isError` 标记。[Skills MCP 实现](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/mcp_server.mjs)
+
### 方式四:其他 AI 平台
| 平台 | 集成方式 |
@@ -387,7 +396,10 @@ def tron_call(cmd: str) -> dict:
["node", "scripts/tron_api.mjs", *cmd.split()],
cwd="/absolute/path/to/tronlink-skills",
)
- return json.loads(out)
+ result = json.loads(out)
+ if isinstance(result, dict) and "error" in result:
+ raise RuntimeError(result["error"])
+ return result
tron_wallet_balance = Tool.from_function(
func=lambda addr: tron_call(f"wallet-balance --address {addr}"),
@@ -485,7 +497,7 @@ tronlink-skills/
| 依赖 | 是否必需? | 用途 |
|------|-----------|------|
-| Node.js 24.22.1(精确版本;默认分支 v1.1.0) | 是 | 运行时(原生 fetch、crypto)。默认分支通过 `.nvmrc` 与 `package.json` 的 `engines` 固定该版本;`install.sh` 检测到其他版本会直接报错退出。安装前先执行 `nvm install 24.22.1 && nvm use 24.22.1`。 |
+| Node.js 24.22.3(精确版本;默认分支 v1.1.0) | 是 | 运行时(原生 fetch、crypto)。默认分支通过 `.nvmrc` 与 `package.json` 的 `engines` 固定该版本;`install.sh` 检测到其他版本会直接报错退出。安装前先执行 `nvm install 24.22.3 && nvm use 24.22.3`。 |
| npm install | 不需要 | 所有操作均无需安装任何 npm 依赖 |
---
@@ -498,7 +510,7 @@ tronlink-skills/
| 副作用 | 每个命令都是 **Network Read**:调用公共 API,但不改变任何状态。所有命令均可安全重试,无需人工确认(HITL) |
| 无需密钥 | 仅可选 TRONGRID_API_KEY 用于提高请求频率 |
| 频率限制 | 公共 TronGrid API;使用 TRONGRID_API_KEY 获取更高限额 |
-| 错误处理 | 失败均为查询类错误:限流(可重试,需退避)、网络错误(可重试)、地址/参数非法(不可重试——修正输入)。如需执行交易(转账、兑换、质押),请使用 [signer SDK](tronlink-signer.md) 或 [MCP Server TronLink](mcp-server-tronlink.md)——这些技能本身从不签名或广播 |
+| 错误处理 | 失败均为查询类错误:限流(可重试,需退避)、网络错误(可重试)、地址/参数非法(不可重试——修正输入)。 |
---
@@ -529,28 +541,31 @@ tronlink-skills/
```bash
# 1. 克隆
-git clone
+# v1.1.0 需要 Git、nvm 和 Node.js 24.22.3;交互步骤还需安装 Claude Code。
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
# 2. 配合 Claude Code 使用(只读操作无需安装)
claude
-> "查一下 T地址... 的 TRX 余额"
-> "展示 TRON 上最热门的代币"
-> "发送 USDT 需要多少能量?"
-> "获取能量最好的方式是什么——冻结、租赁还是燃烧?"
-
-# 3. 或直接使用命令行
-node scripts/tron_api.mjs wallet-balance --address T地址...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs optimize-cost --address T地址...
+# "查一下 T地址... 的 TRX 余额"
+# "展示 TRON 上最热门的代币"
+# "发送 USDT 需要多少能量?"
+# "获取能量最好的方式是什么——冻结、租赁还是燃烧?"
+
+# 3. 也可在 shell 中直接执行。将 ACCOUNT 设为待查询地址。
+node scripts/tron_api.mjs wallet-balance --address "${ACCOUNT:?set ACCOUNT}"
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs optimize-cost --address "${ACCOUNT:?set ACCOUNT}"
```
## 版本与许可证
- **包:** `tronlink-skills` v1.0.1——本页命令表所描述的版本。
-- **默认分支:** v1.1.0(commit `7d2d58cb`,`package.json` 中 `version: 1.1.0`),`git clone` / `install.sh` 安装的就是该版本。与 v1.0.1 相比,影响 agent 的差异:
- - 新增 7 个只读命令(同时以 `tron_` 形式暴露为 MCP 工具):`wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`。共 40 个命令,仍全部为 Network Read。
- - Node.js 固定为精确版本 24.22.1(`.nvmrc`、`engines`);`install.sh` 检测到其他版本会直接退出。
+- **默认分支:** v1.1.0(commit `b12b5868`,`package.json` 中 `version: 1.1.0`),`git clone` / `install.sh` 安装的就是该版本。与 v1.0.1 相比,影响 agent 的差异:
+ - 新增 7 个只读命令(同时以 `tron_` 形式暴露为 MCP 工具)。该提交中 `mcp_server.mjs` 将 40 个命令中的 39 个暴露为 MCP 工具,只有 `swap-route` 仅限 CLI。新增命令:`wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`。共 40 个命令,仍全部为 Network Read。
+ - 此提交的 [`.nvmrc`](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/.nvmrc) 指定 Node.js 24.22.3。复现[旧提交 `7d2d58cb`](https://github.com/TronLink/tronlink-skills/blob/7d2d58cb/.nvmrc) 时使用 Node.js 24.22.1。在检出的仓库根目录运行 `nvm install && nvm use`,即可按该提交的配置选择版本。
- **许可证:** MIT —— `SPDX-License-Identifier: MIT`
- **变更记录 / 发布:** [https://github.com/TronLink/tronlink-skills/releases](https://github.com/TronLink/tronlink-skills/releases) —— 截至当前 v1.0.x 尚无 GitHub tag 发布;打 tag 之前请直接看 commit 历史。
@@ -561,12 +576,11 @@ Skills 已进入 **v1.0.x**,适用标准 semver——只有 **major** 升级
- **稳定契约**(minor / patch 不会动):
- 33 个 CLI 命令名与其必填 / 可选 flag(`tron_api.mjs [...]`)。
- [Skill ↔ MCP 工具映射](#skill-mcp-tool-map) 列出的 25 个 MCP 工具名(`tron_*` 形式)及其 `inputSchema` 字段名。
- - Exit code:`0` 成功,`1` 查询错误 / 参数非法,`2` 未支持 / 未知命令。
- `Network Read` 副作用分级——任何命令未经 major 升级都不会变成 Remote Write。
- **不稳定契约**(minor 允许变化):
- JSON `stdout` 输出的具体字段——新增字段任意 minor 都允许;改名或删除属于 major。请用宽容解析。
- 内置代币 symbol 快捷表(`USDT`、`USDC`、`WTRX`…)——minor 允许新增 symbol;已存在的映射 minor 不会重指。
- 启发式与阈值(`whale-transfers` 默认阈值、`optimize-cost` 决策树权重等)。
-- **子集关系。** MCP 工具子集(目前 25 / 33)可能在 minor 中 **扩大**(CLI-only 命令被新增为 MCP 工具);不会在 minor 中 **缩小**。
+- **子集关系。** MCP 工具子集(v1.0.x 为 25 / 33;`b12b5868` 为 39 / 40)可能在 minor 中 **扩大**(CLI-only 命令被新增为 MCP 工具);不会在 minor 中 **缩小**。
- **废弃窗口。** 被标 deprecated 的命令 / 工具至少在 **一个 minor 周期** 内继续可用;移除最早发生在下一个 major。
- **升级后校验。** 重新 `tron_api.mjs --help`,使用 MCP 时再跑 `tools/list`,确认依赖的名字仍在。MCP `initialize` 阶段返回的 `serverInfo.version` 应与升级后的 `package.json` 版本一致。
diff --git a/docs/dapp/getting-started.en.md b/docs/dapp/getting-started.en.md
index e241f7c..469f846 100644
--- a/docs/dapp/getting-started.en.md
+++ b/docs/dapp/getting-started.en.md
@@ -107,27 +107,39 @@ The following self-contained HTML example detects TronLink via TIP-6963, request
async function connect() {
if (!tronProvider) return alert("TronLink not found!");
try {
- const accounts = await tronProvider.request({
- method: "eth_requestAccounts",
- });
- console.log("Connected:", accounts[0]);
-
- const tronweb = tronProvider.tronWeb;
- const from = tronweb.defaultAddress.base58;
- const to = "TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP"; // replace with the actual recipient address
+ await tronProvider.request({ method: "eth_requestAccounts" });
+ } catch (error) {
+ if (error?.code === 4001) return console.info("Connection declined");
+ return console.error("Authorization failed", error);
+ }
- // Build a 10 SUN TRX transfer (amount unit is SUN: 1 TRX = 1_000_000 SUN)
- const tx = await tronweb.transactionBuilder.sendTrx(to, 10, from);
+ const tronweb = tronProvider.tronWeb;
+ let tx;
+ try {
+ const to = "REPLACE_WITH_RECIPIENT_ADDRESS";
+ // Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+ tx = await tronweb.transactionBuilder.sendTrx(to, 10, tronweb.defaultAddress.base58);
+ } catch (error) {
+ return console.error("Could not build transfer", error);
+ }
- // Pops up the TronLink confirmation window
- const signedTx = await tronweb.trx.sign(tx);
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return console.info("Signing declined");
+ return console.error("Signing failed", error);
+ }
- // Broadcast to the network
- const broadcastTx = await tronweb.trx.sendRawTransaction(signedTx);
- console.log(broadcastTx);
+ try {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ return console.error(receipt.code, message);
+ }
+ console.log("Check on-chain confirmation for", signedTx.txID);
} catch (error) {
- // { code: 4001, message: "User rejected the request." } when the user declines
- console.error(error);
+ console.error("Broadcast outcome unknown. Check transaction before retrying", signedTx.txID, error);
}
}
diff --git a/docs/dapp/getting-started.zh.md b/docs/dapp/getting-started.zh.md
index fb84fe9..f19cf15 100644
--- a/docs/dapp/getting-started.zh.md
+++ b/docs/dapp/getting-started.zh.md
@@ -105,27 +105,39 @@ async function getTronWeb() {
async function connect() {
if (!tronProvider) return alert("未检测到 TronLink!");
try {
- const accounts = await tronProvider.request({
- method: "eth_requestAccounts",
- });
- console.log("已连接:", accounts[0]);
-
- const tronweb = tronProvider.tronWeb;
- const from = tronweb.defaultAddress.base58;
- const to = "TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP"; // 请替换为真实的收款地址
+ await tronProvider.request({ method: "eth_requestAccounts" });
+ } catch (error) {
+ if (error?.code === 4001) return console.info("连接请求被拒绝");
+ return console.error("授权失败", error);
+ }
- // 构建一笔 10 SUN 的 TRX 转账(金额单位为 SUN:1 TRX = 1_000_000 SUN)
- const tx = await tronweb.transactionBuilder.sendTrx(to, 10, from);
+ const tronweb = tronProvider.tronWeb;
+ let tx;
+ try {
+ const to = "替换为实际收款地址";
+ // 构建一笔 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+ tx = await tronweb.transactionBuilder.sendTrx(to, 10, tronweb.defaultAddress.base58);
+ } catch (error) {
+ return console.error("构建转账失败", error);
+ }
- // 弹出 TronLink 确认窗口
- const signedTx = await tronweb.trx.sign(tx);
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return console.info("用户拒绝签名");
+ return console.error("签名失败", error);
+ }
- // 广播到网络
- const broadcastTx = await tronweb.trx.sendRawTransaction(signedTx);
- console.log(broadcastTx);
+ try {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ return console.error(receipt.code, message);
+ }
+ console.log("请查询该交易的链上确认状态", signedTx.txID);
} catch (error) {
- // 用户拒绝时为 { code: 4001, message: "User rejected the request." }
- console.error(error);
+ console.error("广播结果未知,重试前先按交易 ID 查询", signedTx.txID, error);
}
}
diff --git a/docs/dapp/message-signing.en.md b/docs/dapp/message-signing.en.md
index 46eb9e7..41cb6e5 100644
--- a/docs/dapp/message-signing.en.md
+++ b/docs/dapp/message-signing.en.md
@@ -18,7 +18,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
### Parameters
@@ -38,12 +44,7 @@ If the user chooses to sign in the pop-up window, the DApp will get the signed h
0xb0e0b150b9b10dc348f25c7f38fc87f16e18c0d230d23946aac519a5ad9e45937f656012d33c09e9d9dec00b03fbb304e797f8991bb823dce676ac91e03a55991b
```
-If an error occurs, the following information will be returned:
-
-```text
-
- Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
## Interaction
diff --git a/docs/dapp/message-signing.zh.md b/docs/dapp/message-signing.zh.md
index adcd227..87c3d65 100644
--- a/docs/dapp/message-signing.zh.md
+++ b/docs/dapp/message-signing.zh.md
@@ -18,7 +18,13 @@ try {
// 用同一个字符串验签,返回签名者的 base58 地址
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+}
```
### 参数
@@ -39,11 +45,7 @@ try {
0xb0e0b150b9b10dc348f25c7f38fc87f16e18c0d230d23946aac519a5ad9e45937f656012d33c09e9d9dec00b03fbb304e797f8991bb823dce676ac91e03a55991b
```
-如果报错,则会返回如下信息:
-
-```text
- Uncaught (in promise) Invalid transaction provided
-```
+消息为空或钱包签名失败时可能返回 `Invalid transaction provided`。用户拒签时返回 `Confirmation declined by user`。其他失败请查看具体错误原因。
## 交互流程
diff --git a/docs/dapp/multi-sign-transfer.en.md b/docs/dapp/multi-sign-transfer.en.md
index ceec34d..a90328d 100644
--- a/docs/dapp/multi-sign-transfer.en.md
+++ b/docs/dapp/multi-sign-transfer.en.md
@@ -8,48 +8,124 @@ For this section, you may refer to [General Transfer](transfer.en.md)
## Query active permissions
-`multiSign` requires a valid `permissionId` for an **active** permission on the signing account. Active permissions are returned by `tronWeb.trx.getAccount(address)` under the `active_permission[]` field; each entry exposes `id`, `permission_name`, `threshold`, and the `keys[]` array (address + weight). Owner permissions have a fixed `id` of `0` and are exposed under `owner_permission` separately.
+Choose the account that holds the funds. If the connected signer owns the funds, use its address. For a co-signer, enter the controlled account’s address. Read that owner’s permissions on the transaction network and select an entry whose keys include the signer and whose operations allow TRX transfers. Use its actual `id`.
```javascript
const tronweb = window.tron.tronWeb;
-const account = await tronweb.trx.getAccount(tronweb.defaultAddress.base58);
-// account.active_permission is the array — pick the id whose keys[] includes
-// the address you intend to sign with, and whose weight + threshold allow the tx.
-const activePermissions = account.active_permission ?? [];
-console.log(activePermissions.map(p => ({ id: p.id, name: p.permission_name, threshold: p.threshold })));
+const owner = "REPLACE_WITH_OWNER_ADDRESS";
+const account = await tronweb.trx.getAccount(owner);
+console.table(account.active_permission);
```
-Use the resulting `id` as `permissionId` below.
-
## Specification
-### Example
+### Sign and check the weight
+
+Use these helpers with the authorized TronWeb instance on the transaction network. Before broadcasting, the node checks the signatures against the transaction owner’s current permission. [GetSignWeight](https://developers.tron.network/reference/getsignweight)
```javascript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TRKb2nAnCBfwxnLxgoKJro6VbyA6QmsuXq";
-// fromAddress = the account whose active permission controls the funds (the tx owner).
-// It is not necessarily the connected signer: if the connected account is only a
-// co-signer listed in that permission's keys[], set fromAddress to the controlled account.
-const fromAddress = tronweb.defaultAddress.base58;
-const activePermissionId = 2; // obtained via tronWeb.trx.getAccount(fromAddress).active_permission
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId }
-); // Step 1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // Step 2
- const res = await tronweb.trx.sendRawTransaction(signedTx); // Step 3
- if (!res.result) {
- // Node rejections are returned, not thrown — see Errors below.
- console.error(res.code, res.message && tronweb.toUtf8(res.message));
+function validateSignWeight(check, permissionId) {
+ const { permission, result, current_weight: weight } = check ?? {};
+ if (result?.code === "PERMISSION_ERROR") throw new Error("Recheck owner and permission");
+ if (!result || typeof result !== "object" || Array.isArray(result) ||
+ !permission || !Number.isSafeInteger(permission.threshold) ||
+ permission.threshold <= 0 || !Number.isSafeInteger(weight) || weight < 0 ||
+ !/^[0-9a-f]{64}$/i.test(permission.operations)) {
+ throw new Error("Permission or weight unavailable");
+ }
+ // TransferContract is operation 1 in the active permission bitmap.
+ const allowsTransfer = (parseInt(permission.operations.slice(0, 2), 16) & 2) !== 0;
+ if (permission.type !== "Active" || permission.id !== permissionId || !allowsTransfer) {
+ throw new Error("Recheck owner and permission");
+ }
+ return { code: result.code, weight, threshold: permission.threshold };
+}
+
+async function checkAndBroadcast(tronweb, signedTx, permissionId) {
+ const check = await tronweb.trx.getSignWeight(signedTx);
+ const { code, weight, threshold } = validateSignWeight(check, permissionId);
+ if (code === "NOT_ENOUGH_PERMISSION" && weight < threshold) {
+ return { status: "collect", signedTx };
+ }
+
+ // The node may omit the default ENOUGH_PERMISSION code.
+ if ((code !== undefined && code !== "ENOUGH_PERMISSION") || weight < threshold) {
+ throw new Error("Signature weight check failed");
+ }
+
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ throw new Error([receipt.code, message].filter(Boolean).join(" ") || "Broadcast rejected");
}
-} catch (e) {}
+ return { status: "submitted", txID: signedTx.txID };
+}
+
+async function signAndCheck(tronweb, tx) {
+ const permissionId = tx.raw_data.contract[0].Permission_id;
+ if (!Number.isSafeInteger(permissionId) || permissionId < 2) {
+ throw new Error("An active permission ID is required");
+ }
+
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.multiSign(tx, undefined, permissionId);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return { status: "declined" };
+ throw error;
+ }
+
+ return checkAndBroadcast(tronweb, signedTx, permissionId);
+}
```
-If the user chooses “Reject” in the pop-up window, an exception will be thrown, which the developer can catch for further processing. If the user chooses “Sign” in the pop-up window, the DApp receives and broadcasts the signed transaction.
+### First signer
+
+Replace the recipient address and use the permission ID selected from the owner’s active permissions above.
+
+```javascript
+const recipient = "REPLACE_WITH_RECIPIENT_ADDRESS";
+const permissionId = 2; // Replace with the selected permission ID.
+if (!account.active_permission?.some(p => p.id === permissionId)) {
+ throw new Error("Select an active permission of the transaction owner");
+}
+
+// Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronweb.transactionBuilder.sendTrx(recipient, 10, owner, { permissionId });
+const outcome = await signAndCheck(tronweb, tx);
+```
+
+### Additional co-signers
+
+When the outcome has status `collect`, pass its `signedTx` to the next authorized co-signer using your DApp’s handoff flow. Each co-signer connects their wallet on the same network. Before signing, check that the transaction data matches its `txID`, show the co-signer the decoded owner, recipient, amount and expiration, and continue only after they confirm. Pass `coSignTransfer` the received transaction object and a `confirmTransfer` callback that resolves to `true` once the co-signer approves. `signAndCheck` calls `multiSign` on that object so the existing signatures and transaction ID carry forward.
+
+```javascript
+function describeTransfer(tronweb, tx) {
+ // The signature covers txID, so confirm raw_data hashes to it before showing details.
+ const txCheck = tronweb.utils?.transaction?.txCheck;
+ if (!txCheck || !txCheck(tx)) throw new Error("Transaction data does not match its txID");
+ const contract = tx.raw_data.contract[0];
+ if (contract.type !== "TransferContract") throw new Error("Not a TRX transfer");
+ const { owner_address, to_address, amount } = contract.parameter.value;
+ return {
+ owner: tronweb.address.fromHex(owner_address),
+ recipient: tronweb.address.fromHex(to_address),
+ amount: `${tronweb.fromSun(amount)} TRX`,
+ permissionId: contract.Permission_id,
+ expires: new Date(tx.raw_data.expiration).toISOString(),
+ };
+}
+
+async function coSignTransfer(partiallySignedTx, confirmTransfer) {
+ const tronweb = window.tron.tronWeb;
+ const details = describeTransfer(tronweb, partiallySignedTx);
+ // Show the details in your UI; sign only after the co-signer confirms them.
+ if (!(await confirmTransfer(details))) return { status: "declined" };
+ return signAndCheck(tronweb, partiallySignedTx);
+}
+```
-Note that the broadcast only collects one signature in this call — a fully signed multi-sig tx requires the threshold to be met across multiple `multiSign` calls (one per co-signer). Track the partially-signed transaction off-chain (or via the MCP `tl_multisig_*` tools) until the threshold is reached, then broadcast.
+Repeat the handoff on `collect`. On `declined`, stop the current signing attempt. If the weight lookup fails or required fields are missing, pause and run the full weight check again after recovery. If the permission was revoked or no longer allows this operation, verify the owner and permission ID, rebuild the transaction and collect fresh signatures. If broadcast times out, look up the transaction ID before another submission.
## Errors
@@ -58,7 +134,7 @@ Note that the broadcast only collects one signature in this call — a fully sig
| Code | Meaning | Where it comes from | Retryable? |
| :---: | --- | --- | :---: |
| `'Confirmation declined by user'` (string) | User clicked **Reject** in the signing popup | `tronWeb.trx.multiSign(...)` | No — user declined |
-| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `fromAddress` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(fromAddress).active_permission` and rebuild the transaction |
+| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `owner` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(owner).active_permission` and rebuild the transaction |
| `code: 'SIGERROR'`, other `Validate signature error: …` messages | Signatures do not satisfy the permission — e.g. total weight below `threshold`, or a signer that is not in its `keys[]` | Return value of `sendRawTransaction(...)` (not thrown) | No — collect the missing signatures (one `multiSign` call per co-signer) |
| `REVERT` / `OUT_OF_ENERGY` / `FAILED` | Broadcast succeeded but execution failed on-chain | `getTransactionInfo(txid)` | **No — the tx is final; never auto-retry** |
diff --git a/docs/dapp/multi-sign-transfer.zh.md b/docs/dapp/multi-sign-transfer.zh.md
index 7e20039..05bf282 100644
--- a/docs/dapp/multi-sign-transfer.zh.md
+++ b/docs/dapp/multi-sign-transfer.zh.md
@@ -1,6 +1,6 @@
# 多签转账
-## 简介
+## 简介 {#overview}
此处可参考[普通转账](transfer.zh.md)
@@ -8,59 +8,133 @@
## 查询账户的 active permissions
-`multiSign` 需要传入一个**有效的** `permissionId`。账户的 active permissions 通过 `tronWeb.trx.getAccount(address)` 返回的 `active_permission[]` 数组取得,每个 entry 暴露 `id`、`permission_name`、`threshold` 以及 `keys[]`(地址 + 权重)。owner 权限 id 固定为 `0`,在 `owner_permission` 字段下单独返回。
+选择持有资金的账户。如果当前签名人就是 owner,可使用其地址;共同签名人应填写被控制账户的地址。在交易所属网络查询该 owner 的权限,选择包含签名人且允许 TRX 转账的活动权限,使用该条目自身的 `id`。
```javascript
const tronweb = window.tron.tronWeb;
-const account = await tronweb.trx.getAccount(tronweb.defaultAddress.base58);
-// account.active_permission 是数组——挑选 keys[] 里包含你要签名地址、
-// 且 weight + threshold 足够覆盖本次交易的 id。
-const activePermissions = account.active_permission ?? [];
-console.log(activePermissions.map(p => ({ id: p.id, name: p.permission_name, threshold: p.threshold })));
+const owner = "REPLACE_WITH_OWNER_ADDRESS";
+const account = await tronweb.trx.getAccount(owner);
+console.table(account.active_permission);
```
-把查出来的 `id` 作为下面的 `permissionId` 传入。
+## 技术规范 {#specification}
-## 技术规范
+### 签名并检查累计权重 {#sign-and-check-the-weight}
-### 代码示例
+在交易所用网络上,将已授权的 TronWeb 实例传给以下函数。广播前,由节点根据交易 owner 当前的权限检查签名。[GetSignWeight](https://developers.tron.network/reference/getsignweight)
```javascript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TRKb2nAnCBfwxnLxgoKJro6VbyA6QmsuXq";
-// fromAddress = 资金所在、由该 active 权限控制的账户(交易 owner)。
-// 它不一定是当前连接的签名账户:若当前账户只是该权限 keys[] 里的共同签名人,
-// 请把 fromAddress 改成被控制的账户地址。
-const fromAddress = tronweb.defaultAddress.base58;
-const activePermissionId = 2; // 通过 tronWeb.trx.getAccount(fromAddress).active_permission 查出
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId }
-); // 步骤1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- const res = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- if (!res.result) {
- // 节点拒绝以返回值给出,不会抛异常——见下方错误码。
- console.error(res.code, res.message && tronweb.toUtf8(res.message));
+function validateSignWeight(check, permissionId) {
+ const { permission, result, current_weight: weight } = check ?? {};
+ if (result?.code === "PERMISSION_ERROR") throw new Error("请核对交易 owner 和权限");
+ if (!result || typeof result !== "object" || Array.isArray(result) ||
+ !permission || !Number.isSafeInteger(permission.threshold) ||
+ permission.threshold <= 0 || !Number.isSafeInteger(weight) || weight < 0 ||
+ !/^[0-9a-f]{64}$/i.test(permission.operations)) {
+ throw new Error("无法确认权限或累计权重");
+ }
+ // 活动权限位图中的第 1 位对应 TransferContract。
+ const allowsTransfer = (parseInt(permission.operations.slice(0, 2), 16) & 2) !== 0;
+ if (permission.type !== "Active" || permission.id !== permissionId || !allowsTransfer) {
+ throw new Error("请核对交易 owner 和权限");
+ }
+ return { code: result.code, weight, threshold: permission.threshold };
+}
+
+async function checkAndBroadcast(tronweb, signedTx, permissionId) {
+ const check = await tronweb.trx.getSignWeight(signedTx);
+ const { code, weight, threshold } = validateSignWeight(check, permissionId);
+ if (code === "NOT_ENOUGH_PERMISSION" && weight < threshold) {
+ return { status: "collect", signedTx };
+ }
+
+ // 节点可能省略默认的 ENOUGH_PERMISSION 状态码。
+ if ((code !== undefined && code !== "ENOUGH_PERMISSION") || weight < threshold) {
+ throw new Error("签名权重检查失败");
+ }
+
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ throw new Error([receipt.code, message].filter(Boolean).join(" ") || "广播被拒绝");
+ }
+ return { status: "submitted", txID: signedTx.txID };
+}
+
+async function signAndCheck(tronweb, tx) {
+ const permissionId = tx.raw_data.contract[0].Permission_id;
+ if (!Number.isSafeInteger(permissionId) || permissionId < 2) {
+ throw new Error("请填写有效的活动权限 ID");
+ }
+
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.multiSign(tx, undefined, permissionId);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return { status: "declined" };
+ throw error;
}
-} catch (e) {}
+
+ return checkAndBroadcast(tronweb, signedTx, permissionId);
+}
+```
+
+### 第一位签名人 {#first-signer}
+
+替换收款地址,并填写上面从交易 owner 的活动权限中选出的 ID。
+
+```javascript
+const recipient = "REPLACE_WITH_RECIPIENT_ADDRESS";
+const permissionId = 2; // 替换为所选活动权限的 ID。
+if (!account.active_permission?.some(p => p.id === permissionId)) {
+ throw new Error("请选择交易 owner 的活动权限");
+}
+
+// 构建一笔 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+const tx = await tronweb.transactionBuilder.sendTrx(recipient, 10, owner, { permissionId });
+const outcome = await signAndCheck(tronweb, tx);
```
-如果用户在弹窗中选择【拒绝】,则会抛出异常,开发者可捕获此异常进行业务处理。
+### 后续共同签名人 {#additional-co-signers}
+
+结果为 `collect` 时,通过 DApp 的交接流程将其中的 `signedTx` 传给下一位有权限的共同签名人。每位共同签名人在同一网络连接钱包。签名前,先确认交易数据与其 `txID` 一致,再解析 owner、收款地址、金额和过期时间并展示给共同签名人,确认无误后再继续。调用 `coSignTransfer` 时传入收到的交易对象,以及一个在共同签名人确认后返回 `true` 的 `confirmTransfer` 回调。`signAndCheck` 会在该对象上调用 `multiSign`,保留已有签名和交易 ID。
-如果用户在弹窗中选择【签名】,DApp 可以拿到签名后的交易,继续进行广播。
+```javascript
+function describeTransfer(tronweb, tx) {
+ // 签名针对 txID,展示前先确认 raw_data 的哈希与其一致。
+ const txCheck = tronweb.utils?.transaction?.txCheck;
+ if (!txCheck || !txCheck(tx)) throw new Error("交易数据与 txID 不一致");
+ const contract = tx.raw_data.contract[0];
+ if (contract.type !== "TransferContract") throw new Error("不是 TRX 转账");
+ const { owner_address, to_address, amount } = contract.parameter.value;
+ return {
+ owner: tronweb.address.fromHex(owner_address),
+ recipient: tronweb.address.fromHex(to_address),
+ amount: `${tronweb.fromSun(amount)} TRX`,
+ permissionId: contract.Permission_id,
+ expires: new Date(tx.raw_data.expiration).toISOString(),
+ };
+}
+
+async function coSignTransfer(partiallySignedTx, confirmTransfer) {
+ const tronweb = window.tron.tronWeb;
+ const details = describeTransfer(tronweb, partiallySignedTx);
+ // 在 DApp 界面中展示这些信息,共同签名人确认后再签名。
+ if (!(await confirmTransfer(details))) return { status: "declined" };
+ return signAndCheck(tronweb, partiallySignedTx);
+}
+```
-注意:此次调用只收集**一个**签名——完整的多签交易需要凑齐 `threshold`,通常对应**多次** `multiSign` 调用(每个 co-signer 一次)。在凑齐前应在链下(或通过 MCP 的 `tl_multisig_*` 工具)跟踪部分签名的交易,凑齐后再广播。
+返回 `collect` 时继续交接,返回 `declined` 时停止本次签名。权重查询失败或缺少必要字段时暂停,恢复后重新执行完整权重检查。权限被撤销或已不允许本次操作时,核对交易 owner 和权限 ID,重建交易并重新收集全部签名。广播超时则先按交易 ID 查询结果。
-## 错误码
+## 错误码 {#errors}
**错误结构:** 在 TronLink 注入的 `tronWeb` 上(插件 4.0.0 起),用户拒绝 `trx.sign`、`trx.multiSign` 或 `trx.signMessageV2` 时,Promise 以**纯字符串** `'Confirmation declined by user'` reject——不是 `Error` 对象,也没有数字 `code`。`{ code: 4001, message: 'User rejected the request.' }` 对象只由 `window.tron.request(...)` 方法(如 `eth_requestAccounts`)返回。其他失败(钱包未解锁、载荷非法、观察钱包等)返回其他值——参见[处理拒签](../reference/error-code-map.md#handling-rejections)。不要自动重试签名。
| 码 | 含义 | 来源 | 可重试? |
| :---: | --- | --- | :---: |
| `'Confirmation declined by user'`(字符串) | 用户在签名弹窗里点【拒绝】 | `tronWeb.trx.multiSign(...)` | 否——用户拒绝 |
-| `code: 'SIGERROR'`,`message` 解码为 `Validate signature error: permission isn't exit` | `fromAddress` 上不存在该 `permissionId`(填错或已撤销)。`sendTrx` **不会**校验权限,由节点在广播时拒绝 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——重新查 `getAccount(fromAddress).active_permission` 后重建交易 |
+| `code: 'SIGERROR'`,`message` 解码为 `Validate signature error: permission isn't exit` | `owner` 上不存在该 `permissionId`(填错或已撤销)。`sendTrx` **不会**校验权限,由节点在广播时拒绝 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——重新查 `getAccount(owner).active_permission` 后重建交易 |
| `code: 'SIGERROR'`,其他 `Validate signature error: …` 信息 | 签名不满足该权限——如总权重低于 `threshold`,或签名人不在其 `keys[]` 中 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——补齐缺少的签名(每个 co-signer 一次 `multiSign`) |
| `REVERT` / `OUT_OF_ENERGY` / `FAILED` | 广播成功但链上执行失败 | `getTransactionInfo(txid)` | **否——交易已 final,永远不要自动重试** |
diff --git a/docs/llms-full.en.txt b/docs/llms-full.en.txt
index c93053b..d1bb85b 100644
--- a/docs/llms-full.en.txt
+++ b/docs/llms-full.en.txt
@@ -2,11 +2,11 @@
> Concatenation of all English documentation pages for single-fetch LLM ingestion. Generated by scripts/gen_llms_full.py. See ./llms.txt for the curated index.
-- Generated: 2026-11-04T10:12:58Z
-- Commit: 56f294d79923
+- Generated: 2026-11-26T12:11:13Z
+- Commit: 7d9fecacf230
- Language: en
-- Pages: 24
-- Token estimate: ~61,555 (chars / 4)
+- Pages: 27
+- Token estimate: ~67,446 (chars / 4)
---
@@ -143,27 +143,39 @@ The following self-contained HTML example detects TronLink via TIP-6963, request
async function connect() {
if (!tronProvider) return alert("TronLink not found!");
try {
- const accounts = await tronProvider.request({
- method: "eth_requestAccounts",
- });
- console.log("Connected:", accounts[0]);
-
- const tronweb = tronProvider.tronWeb;
- const from = tronweb.defaultAddress.base58;
- const to = "TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP"; // replace with the actual recipient address
+ await tronProvider.request({ method: "eth_requestAccounts" });
+ } catch (error) {
+ if (error?.code === 4001) return console.info("Connection declined");
+ return console.error("Authorization failed", error);
+ }
- // Build a 10 SUN TRX transfer (amount unit is SUN: 1 TRX = 1_000_000 SUN)
- const tx = await tronweb.transactionBuilder.sendTrx(to, 10, from);
+ const tronweb = tronProvider.tronWeb;
+ let tx;
+ try {
+ const to = "REPLACE_WITH_RECIPIENT_ADDRESS";
+ // Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+ tx = await tronweb.transactionBuilder.sendTrx(to, 10, tronweb.defaultAddress.base58);
+ } catch (error) {
+ return console.error("Could not build transfer", error);
+ }
- // Pops up the TronLink confirmation window
- const signedTx = await tronweb.trx.sign(tx);
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return console.info("Signing declined");
+ return console.error("Signing failed", error);
+ }
- // Broadcast to the network
- const broadcastTx = await tronweb.trx.sendRawTransaction(signedTx);
- console.log(broadcastTx);
+ try {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ return console.error(receipt.code, message);
+ }
+ console.log("Check on-chain confirmation for", signedTx.txID);
} catch (error) {
- // { code: 4001, message: "User rejected the request." } when the user declines
- console.error(error);
+ console.error("Broadcast outcome unknown. Check transaction before retrying", signedTx.txID, error);
}
}
@@ -277,7 +289,14 @@ img {
}
-For every action below, the `param` value of `tronlinkoutside://pull.activity?param={}` is the protocol data in JSON format. Note: the JSON string must be URL-encoded before being placed in the link.
+The `param` query parameter contains URL-encoded JSON. Each sample link encodes the request shown below it. For your integration, replace the sample values and generate a new URL.
+
+```javascript
+const buildDeepLink = (request) =>
+ "tronlinkoutside://pull.activity?param=" + encodeURIComponent(JSON.stringify(request));
+```
+
+For login, transfer and signing, use your DApp URL and callback, the target chain ID, and a fresh action ID. For transaction signing, set `data` to the JSON string of a newly built transaction. The sample transaction contains an expired timestamp.
## Open Wallet
@@ -286,7 +305,7 @@ For every action below, the `param` value of `tronlinkoutside://pull.activity?pa
Available since TronLink v4.10.0.
```html
-Open Tronlink
+Open Tronlink
```
`param` (request):
@@ -306,7 +325,7 @@ Available since TronLink v4.10.0.
Available since TronLink v4.10.0.
```html
-Open DApp
+Open DApp
```
`param` (request) — `url` is the target DApp:
@@ -325,14 +344,14 @@ Available since TronLink v4.10.0.
Available since TronLink v4.11.0.
```html
-Login/Request Address
+Login/Request Address
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -361,14 +380,14 @@ Callback:
Available since TronLink v4.11.0.
```html
-Transfer
+Transfer
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -404,14 +423,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign transaction
+Sign transaction
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -445,14 +464,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign message
+Sign message
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -481,40 +500,38 @@ Callback:
## Result Code
-> Note: `tokenId` and `contract` are mutually exclusive in a transfer request — supplying both returns code `10025`.
-
-| Code | Message |
-|:-------|:-------|
-| 0 | success |
-| 10001 | Incorrect JSON format |
-| 10002 | Missing Action |
-| 10003 | Unknown Action |
-| 10004 | Missing ActionId |
-| 10005 | Incorrect DApp URL format |
-| 10006 | Incorrect CallbackUrl format |
-| 10007 | Empty DApp name |
-| 10008 | Version number not supported |
-| 10009 | Current network not supported |
-| 10010 | The URL is not supported to open TronLink |
-| 10011 | Unknown SignType |
-| 10012 | Incorrect Transaction format |
-| 10013 | Incorrect Method format |
-| 10014 | Incorrect Message format |
-| 10015 | Incorrect toAddress |
-| 10016 | No wallet created in TronLink |
-| 10017 | Incorrect fromAddress |
-| 10018 | Incorrect contractAddress |
-| 10019 | Incorrect chainId |
-| 10020 | Incorrect amount |
-| 10021 | The initiating address does not match the current wallet |
-| 10022 | Incorrect loginAddress |
-| 10023 | System contract not support |
-| 10024 | Incorrect tokenId |
-| 10025 | TokenId & Contract address should not exist together |
-| 300 | Transaction canceled |
-| 301 | Transaction executed in TronLink |
-| 302 | Broadcast failure - returned with incorrect info |
-| -1 | Unknown reason |
+| Code | Message | Notes |
+|:-------|:-------|:-------|
+| 0 | success | |
+| 10001 | Incorrect JSON format | |
+| 10002 | Missing Action | |
+| 10003 | Unknown Action | |
+| 10004 | Missing ActionId | |
+| 10005 | Incorrect DApp URL format | |
+| 10006 | Incorrect CallbackUrl format | |
+| 10007 | Empty DApp name | |
+| 10008 | Version number not supported | |
+| 10009 | Current network not supported | |
+| 10010 | The URL is not supported to open TronLink | |
+| 10011 | Unknown SignType | |
+| 10012 | Incorrect Transaction format | |
+| 10013 | Incorrect Method format | |
+| 10014 | Incorrect Message format | |
+| 10015 | Incorrect toAddress | |
+| 10016 | No wallet created in TronLink | |
+| 10017 | Incorrect fromAddress | |
+| 10018 | Incorrect contractAddress | |
+| 10019 | Incorrect chainId | |
+| 10020 | Incorrect amount | |
+| 10021 | The initiating address does not match the current wallet | |
+| 10022 | Incorrect loginAddress | |
+| 10023 | System contract not support | |
+| 10024 | Incorrect tokenId | |
+| 10025 | TokenId & Contract address should not exist together | Conflicting asset identifiers in a transfer request. |
+| 300 | Transaction canceled | |
+| 301 | Transaction executed in TronLink | |
+| 302 | Broadcast failure - returned with incorrect info | |
+| -1 | Unknown reason | |
## JSON Schema Reference
@@ -609,7 +626,13 @@ Every `param` shares this prefix:
}
```
-**Transfer** request — `tokenId` (TRX / TRC10) and `contract` (TRC20) are **mutually exclusive**; supplying both returns `10025`. Set the unused one to `""` (empty string):
+**Transfer** uses the field values below. Send the unused field as an empty string, following the transfer sample and the DeepLink demo request format. Omitting the unused key produces a request that differs from these samples; this page does not define how the App treats an omitted key, so keep both keys present.
+
+| Asset | `tokenId` | `contract` |
+|---|---|---|
+| TRX | `"0"` | `""` |
+| TRC10 | Decimal token ID as a string | `""` |
+| TRC20 | `""` | Token contract address |
```json
{
@@ -623,8 +646,8 @@ Every `param` shares this prefix:
"from": { "type": "string", "description": "Sender TRON address (base58)" },
"to": { "type": "string", "description": "Recipient TRON address (base58)" },
"loginAddress": { "type": "string", "description": "Address that authorized this session — must match the current wallet (otherwise code 10021)" },
- "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX; pass '' when sending TRC20" },
- "contract": { "type": "string", "description": "TRC20 contract address; pass '' when sending TRX / TRC10" },
+ "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX" },
+ "contract": { "type": "string", "description": "TRC20 contract address" },
"amount": { "type": "string", "description": "Decimal string in human units (e.g. '1.5'); the app handles decimals" },
"memo": { "type": "string", "description": "Optional transaction memo" },
"dappName": { "type": "string" },
@@ -728,9 +751,11 @@ The full set of values is in the [Result Code](#result-code) table above. Branch
## TronLink Integration
-TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with TronLink DApps and the TRON network.
+TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with the TronLink App and the TRON network.
+
+Once the in-app browser has supplied an authorized TronWeb instance, the transaction-building steps in [Start Developing](../dapp/getting-started.md) apply. That guide demonstrates provider discovery (TIP-6963), authorization (`eth_requestAccounts`) and events for the browser extension. Check support for each of those interfaces on the target App version.
-Details: [Go to DApp](../../dapp/getting-started)
+From an external mobile browser, use [DeepLink](deeplink.md) to open TronLink.
## DApp Explorer
@@ -754,6 +779,112 @@ Tron DApp running in the DApp Explorer injects iTron objects automatically to of
---
+
+
+# Android Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-android-core](https://github.com/TronLink/tronlink-android-core)
+
+Integrate the wallet functions used by TronLink Android to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+The library requires Android API level 21 or later; the Java version is set in the upstream [build configuration](https://github.com/TronLink/tronlink-android-core/blob/main/core/build.gradle). Add JitPack to the repositories Gradle uses to resolve dependencies (Groovy DSL).
+
+```groovy
+repositories {
+ maven { url "https://jitpack.io" }
+}
+```
+
+Add the AAR to the app module’s dependencies. Replace `` with a tag from the [releases](https://github.com/TronLink/tronlink-android-core/releases), normally the latest.
+
+```groovy
+dependencies {
+ implementation 'com.github.TronLink:tronlink-android-core:@aar'
+}
+```
+
+## Create a wallet
+
+Create a wallet in your app and read its TRON address.
+
+```java
+import org.tron.walletserver.Wallet;
+
+// Inside an application method
+Wallet wallet = new Wallet(true);
+String address = wallet.getAddress();
+```
+
+The wallet tests also show how to restore an address from a mnemonic or private key. For transaction signing, see the transaction tests. The tests include no message-signing example; the library implements it in `org.tron.common.bip32.Sign` (`signPrefixedMessage`, `signPrefixedMessageV2`). [Wallet examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/WalletCoreUnitTest.java) · [Transaction signing examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/TransactionCoreUnitTest.java) · [`Sign.java`](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/main/java/org/tron/common/bip32/Sign.java)
+
+## Verify the AAR
+
+Verification requires the exact AAR signed by TronLink and its matching detached `.asc` signature. JitPack and the GitHub releases do not provide signature files, so obtain the signed AAR and matching signature from the maintainers. See the [upstream verification instructions](https://github.com/TronLink/tronlink-android-core#integrity-check).
+
+Download the [public key](https://keys.openpgp.org/vks/v1/by-fingerprint/7B910EA80207596075E6D7BA5D34F7A6550473BA) as `tronlink-build.asc`. Check the signing subkey fingerprint against the one in the upstream instructions, `7B910EA80207596075E6D7BA5D34F7A6550473BA`. Once it matches, import the key and verify the two files supplied by the maintainers, substituting their filenames below.
+
+```bash
+gpg --show-keys --with-subkey-fingerprint tronlink-build.asc
+gpg --import tronlink-build.asc
+gpg --verify release.aar.asc release.aar
+```
+
+## Privacy
+
+Embedding the library does not start usage reporting. The reporting code in `org.tron.metrics` records and uploads data only after the host app wires up its repositories and calls `DataUploader.init(...)` and `upload(...)`. Read the upstream [privacy policy](https://github.com/TronLink/tronlink-android-core/blob/main/PRIVACY-POLICY.md) before enabling it.
+
+## Version & License
+
+The examples and links on this page follow the upstream `main` branch. When you pin an older tag, check that its APIs match. [Apache License 2.0](https://github.com/TronLink/tronlink-android-core/blob/main/LICENSE)
+
+---
+
+
+
+# iOS Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-iOS-core](https://github.com/TronLink/tronlink-iOS-core)
+
+Use TronLink’s native iOS wallet module to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+Add the dependency to your app target in the Podfile. The minimum iOS version and the Swift version are declared in the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec).
+
+```ruby
+pod 'tronlink-iOS-core'
+```
+
+Run `pod install`, open the generated `.xcworkspace` in Xcode, and import the module in Swift.
+
+```swift
+import TLCore
+```
+
+## Run the example project
+
+To explore the wallet APIs in the upstream Xcode project, install its pods from the example directory.
+
+```bash
+git clone https://github.com/TronLink/tronlink-iOS-core.git
+cd tronlink-iOS-core/Example
+pod install
+```
+
+Open the workspace in `Example/`. The Swift tests show wallet creation, transaction and message signing, and how to export a private key or mnemonic. [Swift wallet examples](https://github.com/TronLink/tronlink-iOS-core/blob/main/Example/Tests/Tests.swift)
+
+## Privacy
+
+Installing the pod or creating a wallet does not start a statistics upload. The host app must invoke the reporter and implement the upload callback in `TRXMetricsDataSource`. To enable uploads, the app must also identify its environment as production or pre-release. The same check applies to Debug and Release builds. In TronLink iOS, Basic Mode suppresses reporting, as do watch-only wallets and Shasta activity. [iOS privacy policy](https://github.com/TronLink/tronlink-iOS-core/blob/main/PRIVACY-POLICY.md)
+
+## Version & License
+
+For the current version, see the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec). [Apache License 2.0](https://github.com/TronLink/tronlink-iOS-core/blob/main/LICENSE)
+
+---
+
# Proactively Request TronLink Plugin Features
@@ -773,7 +904,10 @@ This method follows the Ethereum **EIP-1102** protocol.
```javascript
try {
await window.tron.request({method: 'eth_requestAccounts'});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Connection declined");
+ else console.error("Authorization failed", error);
+}
```
#### Return Value
@@ -898,10 +1032,17 @@ const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+} catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+}
+if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+}
```
When executing `await tronweb.trx.sign(tx);`, TronLink displays a confirmation popup.
@@ -926,24 +1067,7 @@ Refer to **Normal Transfer** above.
#### Code Example
-```typescript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
-const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
-const activePermissionId = 2;
-
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
-);
-
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
-```
-
-Rejecting triggers an exception; signing returns the signed transaction for broadcasting.
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting.
> **Legacy (not recommended):** [Legacy: multiSign via window.tronLink](#legacy-multisign-via-windowtronlink)
@@ -969,7 +1093,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
#### Parameter
@@ -990,11 +1120,7 @@ If signed successfully:
0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c
```
-If an error occurs:
-
-```typescript
-Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
### Interaction Flow
@@ -1139,7 +1265,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
#### Parameters
@@ -1366,12 +1495,27 @@ Retained for back-compat; new integrations should use `eth_requestAccounts`.
```json
{
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": { "type": "integer", "enum": [200, 4000, 4001] },
- "message": { "type": "string" }
- }
+ "oneOf": [
+ {
+ "const": ""
+ },
+ {
+ "type": "object",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [200, 4000, 4001]
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ ]
}
```
@@ -1397,15 +1541,22 @@ Therefore, the DApp must perform the **Connect Website** request first and wait
#### Code Example
```typescript
-const res = await tronWeb.request(
+const res: RequestAccountsResponse = await window.tronLink.request(
{
method: 'tron_requestAccounts',
params: {
websiteIcon: '',
websiteName: '',
- } as RequestAccountParams,
+ } as RequestAccountsParams,
}
);
+if (res === "") {
+ console.info("Unlock TronLink");
+} else if (res.code === 200) {
+ console.info("Connected");
+} else {
+ console.info(res.code, res.message);
+}
```
#### Parameters
@@ -1418,14 +1569,14 @@ interface RequestAccountsParams {
```
- **method:** fixed string `tron_requestAccounts`
-- **params:** `RequestAccountParams` type:
+- **params:** `RequestAccountsParams` type:
- `websiteIcon`: DApp website icon URI (displayed in connected site list)
- `websiteName`: DApp website name
#### Return Value
```typescript
-interface ReqestAccountsResponse {
+type RequestAccountsResponse = "" | {
code: 200 | 4000 | 4001,
message: string
}
@@ -1449,34 +1600,24 @@ if (window.tronLink.ready) {
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+ let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+ }
+ if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+ }
}
```
## Legacy: multiSign via window.tronLink
-```typescript
-if (window.tronLink.ready) {
- const tronweb = tronLink.tronWeb;
- const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
- const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
- const activePermissionId = 2;
-
- const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
- );
-
- try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
-}
-```
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting. For the legacy provider, obtain `tronweb` from `window.tronLink.tronWeb` once `window.tronLink.ready` is true.
## Legacy: signMessageV2 via window.tronLink
@@ -1488,7 +1629,13 @@ if (window.tronLink.ready) {
try {
const message = "Sign in to Example DApp\nNonce: 8f3a2c"; // plain UTF-8 text
const signedString = await tronweb.trx.signMessageV2(message);
- } catch (e) {}
+ } catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+ }
}
```
@@ -1500,42 +1647,48 @@ if (window.tronLink.ready) {
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc10',
options: { address: '1002000' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC20
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc20',
options: { address: 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC721
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc721',
options: { address: 'TVtaUnsgKXhTfqSFRnHCsSXzPiXmm53nZt' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
```
@@ -1548,7 +1701,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
---
@@ -1811,7 +1967,7 @@ window.tron.on('disconnect', (providerRpcError) => {
})
```
-> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message) or [rejectWeb (postMessage)](#user-rejected-connection-message)
+> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message)
---
@@ -2086,6 +2242,56 @@ Modified hash:
---
+
+
+# Extension Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-extension-core](https://github.com/TronLink/tronlink-extension-core)
+
+`@tronlink/core` is the JavaScript and TypeScript wallet library used by the TronLink extension. Embed it in a wallet application to derive TRON and EVM accounts and sign locally. For a DApp that asks the user’s installed extension to connect or sign, use the [extension provider](active-requests.en.md).
+
+## Installation
+
+Install the npm package. It includes CommonJS and ES module entry points and TypeScript declarations.
+
+```bash
+npm install @tronlink/core
+```
+
+See the upstream prerequisites for the required Node.js, pnpm (development) and TypeScript versions. Browser builds need polyfills for Node modules such as `buffer`, `crypto`, and `stream`. [Prerequisites](https://github.com/TronLink/tronlink-extension-core/blob/main/README.md#prerequisites) · [Upstream webpack configuration](https://github.com/TronLink/tronlink-extension-core/blob/main/webpack.config.js)
+
+## Derive a TRON address
+
+Generate a mnemonic, derive the first account’s first address path, then use the derived private key to obtain the address.
+
+```ts
+import { BaseWallet, TronWallet } from '@tronlink/core';
+
+const wallet = new TronWallet();
+const mnemonic = BaseWallet.generateRandomMnemonic();
+const path = wallet.derivePath({ accountIndex: 0, addressIndex: 0 });
+const privateKey = wallet.derivePrivateKey({ mnemonic, path });
+const address = wallet.getAddressBy({ privateKey });
+```
+
+For an EVM address, use `EvmWallet` and call its `derivePath` before deriving the key. [TRON and EVM account example](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/create_account.ts)
+
+## Signing
+
+Both wallet classes support transaction, message, and typed-data signing. For TRON, pass a prepared transaction to `wallet.signTransaction({ privateKey, data: rawTransaction })`. For an EVM transaction, supply the chain configuration and unsigned transaction in `data`. Signing returns the result locally. Broadcasting is a separate step. [TRON signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/tron_signature.ts) · [EVM signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/evm_signature.ts)
+
+## Ledger and usage statistics
+
+Ledger signing requires a browser that exposes `navigator.hid`. Use `LedgerTrxSigner` with the device’s TRX app and `LedgerEvmSigner` with its ETH app.
+
+Importing the package, deriving an address, or signing locally does not start a statistics upload. To send a report, the host calls `checkAndReportXY(deps)` and supplies the upload callback. The optional `userStatistics` module groups mainnet activity by day and amount range, using UUIDs assigned to addresses on the device. [Privacy and reporting details](https://github.com/TronLink/tronlink-extension-core/blob/main/PRIVACY.md)
+
+## Version & License
+
+For the current version, see the [package manifest](https://github.com/TronLink/tronlink-extension-core/blob/main/package.json). [Apache License 2.0](https://github.com/TronLink/tronlink-extension-core/blob/main/LICENSE)
+
+---
+
# MCP Server TronLink
@@ -2098,7 +2304,7 @@ Modified hash:
**Key Highlights:**
- Dual-mode architecture: **Playwright** (browser automation) + **Direct API** (on-chain operations)
-- 32 built-in Flow Recipes with pre-checks and dependency resolution
+- 24 built-in Flow Recipes with pre-checks and dependency resolution
- Non-custodial local transaction signing via encrypted `agent-wallet`
- Multi-signature management with real-time WebSocket monitoring
- Gas-free TRC20 transfers via GasFree service integration
@@ -2117,7 +2323,7 @@ flowchart TD
Multi["TronLinkMultiSigCapability (5 tools)"]
GasFree["TronLinkGasFreeCapability (3 tools)"]
Util["Utility Capabilities
Build · StateSnapshot · TRON Crypto"]
- Flow["Flow Recipes
(32 built-in, pre-checked)"]
+ Flow["Flow Recipes
(24 built-in, pre-checked)"]
Ext["TronGrid API / Multi-Sig Service / GasFree Service"]
Chain["TRON Blockchain"]
Agent -- "MCP Protocol — stdio / JSON-RPC 2.0" --> Server
@@ -2264,11 +2470,13 @@ Uses `@noble/curves` (secp256k1 ECDSA) and `@noble/hashes` (Keccak-256, SHA256).
---
-## Flow Recipes (32 Built-In)
+## Flow Recipes (24 Built-In)
Pre-configured multi-step workflows with dependency checks and parameter templates.
-### Playwright Flows
+Call `tl_list_flows` for the registry in the running server.
+
+### Playwright Flows (4)
| Flow | Description |
|------|-------------|
| `switchNetworkFlow` | Switch to Mainnet/Nile/Shasta |
@@ -2338,7 +2546,7 @@ Pre-configured multi-step workflows with dependency checks and parameter templat
| Variable | Description |
|----------|-------------|
-| `AGENT_WALLET_PASSWORD` | Encryption password (optional if using `tl_wallet_create`; required for manual or existing wallets) |
+| `AGENT_WALLET_PASSWORD` | Encryption password (supply for manually provisioned wallets; local auto-created wallets reuse their saved password) |
| `AGENT_WALLET_DIR` | Custom wallet storage directory |
| `TL_OWNER_WALLET_ID` | Owner wallet ID for multisig signing |
| `TL_COSIGNER_WALLET_ID` | Co-signer wallet ID for multisig |
@@ -2380,12 +2588,13 @@ Auto-detected by Claude Code:
}
```
-If no wallet exists yet, startup shows two paths:
+**Manual creation (recommended for production).** For a new wallet, run `agent-wallet start local_secure --generate --wallet-id main`. For this or an existing wallet, load its password into the launch environment of Claude Code (tested with 2.1.141) as `AGENT_WALLET_PASSWORD` using your secret manager. Add the following entry to the server’s `env` object. Claude Code expands the reference when starting the server. [Claude Code MCP](https://code.claude.com/docs/en/mcp#environment-variable-expansion-in-mcp-json)
-- Auto-create in the running MCP session: call `tl_wallet_create`
-- Manual setup: create the wallet locally with `agent-wallet start local_secure --generate --wallet-id main`, then set `AGENT_WALLET_PASSWORD` and restart
+```json
+{ "AGENT_WALLET_PASSWORD": "${AGENT_WALLET_PASSWORD}" }
+```
-If you choose auto-create, the server generates a random password, saves it to `~/.agent-wallet/runtime_secrets.json`, creates an encrypted `main` wallet, and continues with the current session.
+**Automatic creation (local development).** Leave the password entry out. With no wallet present, call `tl_wallet_create`. The server generates a random password and stores it in plaintext in `~/.agent-wallet/runtime_secrets.json` for reuse after restart. Restrict the file to its owner (`chmod 600`) and protect backups.
The following is a fuller Nile configuration. The router addresses are SunSwap's official Nile Routers ([V2](https://docs.sun.io/protocols/sunswap-v2/reference/contract/), [V3](https://docs.sun.io/protocols/sunswap-v3/reference/contract/)); do not copy Mainnet router addresses into a Nile configuration. `tl_chain_swap` (V2) executes the token path of the quote API's best route through the V2 router, so it fails when the route includes non-V2 pools (for example TRX→USDT on Nile). A Shasta URL selects the Mainnet defaults, so swaps do not work on Shasta:
@@ -2401,7 +2610,6 @@ The following is a fuller Nile configuration. The router addresses are SunSwap's
"TL_MODE": "prod",
"TL_HEADLESS": "false",
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2428,7 +2636,6 @@ If you only need direct API tools and do not need browser automation, you can ke
"cwd": ".",
"env": {
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2486,7 +2693,7 @@ mcp-server-tronlink/
│ │ ├── state-snapshot.ts # UI state extraction
│ │ └── tron-crypto.ts # Address derivation, signing, Base58
│ └── flows/
-│ ├── index.ts # Flow registry (32 recipes)
+│ ├── index.ts # Flow registry (24 recipes)
│ ├── switch-network.ts # Network switching flows
│ ├── transfer-trx.ts # Transfer flows
│ ├── multisig.ts # 6 multi-sig flows
@@ -2504,7 +2711,7 @@ mcp-server-tronlink/
## Dependencies
-Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
+Ranges from the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
| Package | Version | Purpose |
|---------|---------|---------|
@@ -2512,14 +2719,14 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
| `@noble/hashes` | ^2.0.1 | Keccak-256, SHA256 |
| `@tronlink/tronlink-mcp-core` | ^0.1.0 | Core MCP server framework |
| `playwright` | ^1.49.0 | Browser automation |
-| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`) — pinned, not `latest`, to keep wallet behavior reproducible |
+| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`). The range allows versions from 2.3.0 up to, excluding, 3.0.0. Check the installed version with `npm ls @bankofai/agent-wallet`. |
| `ws` | ^8.18.0 | WebSocket (multi-sig monitoring) |
---
## Tool Contract & Side Effects
-**Input/output schemas and error contract.** Each tool's input/output schema and the structured error envelope are defined by the underlying framework — see [TronLink MCP Core](tronlink-mcp-core.md#error-codes) for the SSOT error code table (`code` / `retryable` / `hint` / triggered_by). Every response carries `meta.schemaVersion`; field meanings are stable within a major version. Agents should branch on `error.code` and `error.retryable`, never on the human-readable `message`.
+**Tool results and errors.** When the server uses Core 0.1.0, inspect `ok` in the Core response. On failure, use `error.code` to look up retry guidance in the [Core error-code table](tronlink-mcp-core.en.md#error-codes). The response includes `error.message` and may include `error.details`. For writes with an unknown outcome, check the transaction status before retrying.
**Per-tool input schemas are discoverable at runtime.** Every tool's parameters are Zod-validated in core and exposed as a JSON `inputSchema` via the MCP `list_tools` method, so a client can enumerate names, types, and required fields without reading this page. The tables below summarize tools by capability; `list_tools` is the authoritative, machine-readable source.
@@ -2536,7 +2743,7 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
### Selected tool schemas (inline mirror)
-These are **docs-side mirrors** of the most critical tool inputs — useful when an agent is writing a tool-call call site without an MCP session open. Runtime `list_tools` remains the authoritative source: the schemas there carry full Zod metadata (descriptions, `default`, etc.) plus `meta.schemaVersion`. Fields below are derived from `@tronlink/tronlink-mcp-core` `src/mcp-server/schemas.ts` and follow JSON Schema Draft 7. The full set of 52 tool schemas is **not** reproduced here — see core for the SSOT.
+The following tables summarize selected tool inputs. Call `tools/list` on the installed server to read each tool’s `inputSchema`, including its parameter descriptions and defaults. The examples below use JSON Schema Draft 7.
> Docs CI checks the field names and required flags of every block below against upstream `schemas.ts`; if they ever disagree, `list_tools` wins.
@@ -2663,7 +2870,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
| Boundary | Guarantee | Agent / operator obligation |
|---|---|---|
-| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `code`, `retryable`) for branching. |
+| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `error.code`) for branching. |
| **Outbound host allowlist (SSRF)** | The server only originates HTTPS to the three configured endpoints — `TL_TRONGRID_URL` (TronGrid; SunSwap router contracts are also called through its `triggersmartcontract` endpoint), `TL_MULTISIG_BASE_URL`, `TL_GASFREE_BASE_URL` — plus the built-in SunSwap quote API (`rot.endjgfsv.link` on Mainnet, `tnrouter.endjgfsv.link` on Nile; not configurable). Tools never accept user-supplied URLs that get fetched verbatim. | Pin these env vars to known hosts in production, and include the quote API host in any egress allowlist; do not let LLM input populate any `*_BASE_URL`. |
| **API key handling (token passthrough)** | `TL_TRONGRID_API_KEY`, `TL_MULTISIG_SECRET_KEY`, `TL_GASFREE_API_SECRET` are read from env at startup and used only on the outbound leg. They are **not** returned in any tool response, error `details`, or Knowledge Store record. The server does not accept Authorization headers from MCP clients and forward them upstream. | Audit env capture in your MCP host config (some hosts log env); store secrets in the host's secret manager, not in `.mcp.json` committed to git. |
| **Browser JS execution** | `tl_evaluate` runs arbitrary JavaScript in the controlled Playwright browser context. This is a **High-risk / Destructive** primitive — it can read DOM, click invisible elements, exfiltrate state, and bypass UI HITL. | Disable `tl_evaluate` from the MCP host's tool allowlist for any agent that does not strictly require it. Never expose it to a remote/multi-user MCP deployment. |
@@ -2675,7 +2882,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
Swaps are **Remote Write** and execute against a public DEX router, so they are exposed to **price slippage** and **front-running / MEV** (e.g. sandwich attacks): the realized output can be worse than quoted if the pool moves between quote and execution.
-- **Always bound the trade with a minimum-output / slippage limit.** Inspect the `tl_chain_swap_v3` input schema via `list_tools` (the `SwapV3Params` shape) for the exact slippage / minimum-output field names — do **not** rely on an unstated default, and treat a missing or zero minimum-output as unsafe.
+- **Always set `slippage` explicitly.** `tl_chain_swap_v3` has no minimum-output input; the server derives the minimum output from `slippage` (a percentage, default 0.5). Do **not** rely on the default; confirm the tolerance with the user and check the field in the `list_tools` schema.
- **Quote immediately before executing.** Get a fresh quote/route (e.g. Skills `tron-swap` `swap-quote` / `swap-route`), pick a tolerance you accept, and pass it explicitly.
- **Check the router.** Set `TL_SUNSWAP_ROUTER` / `TL_SUNSWAP_V3_ROUTER` to the Routers listed for your network in SunSwap's official contract addresses (see Environment Variables); a stale or wrong router can route funds unexpectedly.
- **No auto-retry.** A failed/uncertain swap is a Remote Write — confirm on-chain before re-issuing (`TL_CHAIN_SWAP_FAILED` is not retryable).
@@ -2728,9 +2935,9 @@ Verify after restart with `list_tools` — `tl_evaluate` should not appear. The
The Direct-API path signs with a local encrypted wallet managed by `@bankofai/agent-wallet`. Two paths exist for unlocking it; pick deliberately.
-**Path A — Manual (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. The password lives only in process memory; nothing is written by this server.
+**Manual creation (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. This path reads the supplied password from the environment.
-**Path B — Auto-create (convenience for local dev).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
+**Automatic creation (local development).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
1. Generates a random password.
2. Writes it in plaintext to `~/.agent-wallet/runtime_secrets.json` so a restart can reuse the wallet.
@@ -2739,7 +2946,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
| Aspect | Behavior |
|---|---|
| **File** | `~/.agent-wallet/runtime_secrets.json` (plaintext JSON containing the password) |
-| **Recommended permissions** | `chmod 600` — the file is created under the user's `$HOME`, but no umask hardening is enforced. Verify after first run. |
+| **Recommended permissions** | Version 0.1.1 requests mode `0600` when creating the file. Verify the permissions after startup. |
| **Git safety** | `~/.agent-wallet/` is outside any repo by default. If you point `AGENT_WALLET_DIR` inside a repo, add it to `.gitignore` explicitly. |
| **Knowledge Store redaction** | The Knowledge Store auto-redacts `password`, `mnemonic`, `private_key`, `seed` fields in tool inputs / outputs. It does **not** read or sanitize `runtime_secrets.json`. The file is independent of the Knowledge Store. |
| **Logs / stderr** | The auto-generated password is not logged. The file path may appear in startup output. |
@@ -2747,11 +2954,11 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
**Production guidance.**
-- Prefer Path A. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (Claude Desktop env, vault, etc.).
-- If you must use Path B (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
+- Prefer manual creation. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (for example, a vault).
+- If you must use automatic creation (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
- For any tool that moves real funds, prefer `mcp-tronlink-signer` (browser approval, no on-disk password) over Direct-API.
-**How to enforce Path A (doc-side, today).**
+**How to enforce manual creation (doc-side, today).**
1. Provision the wallet **before** the server boots. From a separate shell:
@@ -2760,7 +2967,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
# take note of the password you supply here — it is the only copy
```
-2. Inject the password via the MCP host's secret manager so it lands in the server's `env` at launch:
+2. For Claude Code, export the password from your secret manager into the client’s environment and reference it in the server configuration:
```jsonc
// .mcp.json — secret comes from host env, not from this file
@@ -2777,7 +2984,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
3. **Do not let the agent call `tl_wallet_create`.** Disable it the same way as `tl_evaluate` above (Claude Code `permissions.deny`, Claude Desktop `disabledTools`, or client-side `list_tools` filtering on the name `tl_wallet_create`).
-4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms Path B did not run.
+4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms automatic creation did not run.
**Tracking issue (code-side).** A `--no-auto-create` / `AGENT_WALLET_DISABLE_AUTOCREATE=1` flag that makes the server fail-loud at startup when no wallet exists is the proper long-term fix; until that ships upstream, the doc-side enforcement above is the defense in depth.
@@ -2805,8 +3012,8 @@ npm install && npm run build
# TL_TRONGRID_URL=https://nile.trongrid.io
#
# 3. If no wallet exists, choose one path:
-# Option A: call tl_wallet_create after startup
-# Option B: create one locally, then set AGENT_WALLET_PASSWORD
+# Automatic creation (local development): call tl_wallet_create after startup
+# Manual creation (recommended for production): create one locally, then set AGENT_WALLET_PASSWORD
# 4. Use with Claude Code
# "Check my TRX balance"
@@ -2822,19 +3029,17 @@ npm install && npm run build
### Compatibility & migration policy
-- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, `error.code` values, or `meta.schemaVersion` semantics. Post-1.0: standard semver — major-only breaking changes.
+- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, or `error.code` values. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- Tool names (`tl_chain_send`, `tl_chain_swap_v3`, `tl_multisig_*`, `tl_gasfree_*`, `tl_evaluate`, etc.)
- `error.code` enum (SSOT: [TronLink MCP Core — Error Codes](tronlink-mcp-core.md#error-codes))
- - `error.retryable` semantics
- - `meta.schemaVersion` major component
- Required env var names (`TL_TRONGRID_URL`, `TL_MULTISIG_SECRET_KEY`, `AGENT_WALLET_PASSWORD`, …)
- **Volatile contracts** (may change at any time):
- Prose `message` text, log line formats, stderr output
- Internal Knowledge Store keys (consumers should not parse them)
- Pre-check error detail strings (branch on `code`, not on `details.reason`)
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag exposed via `list_tools`; removal lands no earlier than the cycle after that.
-- **Verifying after upgrade.** Re-call `list_tools` and confirm the tool names + `inputSchema` you depend on are still present before resuming the workflow. Compare `meta.schemaVersion` against the value cached at session start.
+- **Deprecations.** [@tronlink/mcp-server-tronlink 0.1.1](https://www.npmjs.com/package/@tronlink/mcp-server-tronlink/v/0.1.1) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Verifying after upgrade.** Record the installed server and Core versions. Recheck tool names and `inputSchema` with `tools/list`, then verify your client handles both `ok: true` and `ok: false` for a read-only tool.
---
@@ -3199,7 +3404,7 @@ All tools use the `tl_` prefix. Organized into 13 categories:
## Standardized Response Format
-All tools return a consistent structure:
+In [Core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0), inspect `ok` to select `result` or `error`. On failure, read `error.code` and `error.message`. `error.details` is optional. Response metadata contains `timestamp`, `sessionId`, and `durationMs`.
```typescript
// Success
@@ -3208,7 +3413,7 @@ All tools return a consistent structure:
result: { /* tool-specific data */ },
meta: {
timestamp: "2026-03-09T10:15:23.456Z",
- sessionId: "tl-1741504523",
+ sessionId: "tl-1773051323",
durationMs: 234
}
}
@@ -3219,17 +3424,15 @@ All tools return a consistent structure:
error: {
code: "TL_CLICK_FAILED", // stable code — see table below
message: "Element not found",
- retryable: false, // explicit hint for agents
- hint: "Re-snapshot the page and retry with a fresh a11yRef.",
details: { /* optional */ }
},
- meta: { timestamp, sessionId, durationMs, schemaVersion: "1.0" }
+ meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1773051323", durationMs: 234 }
}
```
### Error Codes
-This is the single source of truth (SSOT) for error codes returned by every tool in this framework. Downstream servers built on this framework (`mcp-server-tronlink`) inherit these codes and may extend them; `mcp-tronlink-signer` is a separate server and does not use them. `retryable` reflects framework-level safety; an agent **must** still apply the side-effect classification of the calling tool — never auto-retry a Remote Write whose outcome is unknown, regardless of `retryable`.
+This table is the single source of truth for Core error codes and their retry semantics. Look up `error.code` in the table below for retry guidance and recovery steps. **Retryable** and **Hint** are documentation columns. Core 0.1.0 omits `error.retryable`, `error.hint`, and `meta.schemaVersion` from the response. For a Remote Write with an unknown outcome, verify the transaction before considering another attempt. Downstream servers such as `mcp-server-tronlink` can extend this table. The independent `mcp-tronlink-signer` server uses its own errors.
| Code | Retryable | Hint | Typical trigger |
|------|:---:|------|-----------------|
@@ -3245,8 +3448,8 @@ This is the single source of truth (SSOT) for error codes returned by every tool
| `TL_WAIT_TIMEOUT` | true | Increase the timeout or wait on a different selector. | `tl_wait_for`, `tl_wait_for_notification` |
| `TL_SCREENSHOT_FAILED` | true | Transient; retry. | `tl_screenshot`, `tl_describe_screen` |
| `TL_CAPABILITY_NOT_AVAILABLE` | false | The session was launched without this capability; reconfigure and relaunch. | Any tool that requires an optional capability |
-| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. | `tl_chain_get_*` |
-| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake`, `tl_chain_resource` |
+| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. **Exception:** `tl_chain_resource` also returns this code when a delegate/undelegate write fails, so treat it as `TL_CHAIN_SEND_FAILED` and check the transaction before re-issuing. | `tl_chain_get_*`, `tl_chain_resource` |
+| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake` |
| `TL_CHAIN_SWAP_FAILED` | false | Same as send — confirm the previous tx did not land before retrying. | `tl_chain_swap`, `tl_chain_swap_v3` |
| `TL_GASFREE_QUERY_FAILED` | true | Transient; retry. | `tl_gasfree_get_account`, `tl_gasfree_get_transactions` |
| `TL_GASFREE_SEND_FAILED` | false | Do **not** auto-retry; query the GasFree service for the latest status. | `tl_gasfree_send` |
@@ -3258,7 +3461,7 @@ This is the single source of truth (SSOT) for error codes returned by every tool
Custom codes added by downstream servers must follow these rules:
- Never reuse a code listed above with a different meaning.
-- `retryable` is required for every new code.
+- Document the retry policy and recovery step for each new code.
- Meaning is stable within a major version.
- New codes are documented in the consuming server's docs, not silently introduced.
@@ -3482,19 +3685,19 @@ npm run clean # Remove dist/
### Compatibility & migration policy
-This package is **the SSOT** for tool schemas, error codes, and `meta.schemaVersion` consumed by `mcp-server-tronlink` and any downstream MCP server built on this core. The compatibility surface is therefore wider than a typical library:
+This package defines the tool schemas, error codes, and response envelope used by `mcp-server-tronlink` and other servers built on Core.
- **Semver.** Pre-1.0: a **minor** bump may change the `ISessionManager` interface, capability shapes, or `Tool[]` registration order; a **patch** will not. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- - The `error.code` enum (the SSOT exported as `ERROR_CODES`) — adding a new code is non-breaking; renaming or removing one is breaking.
- - The `{ ok, result/error, meta }` response envelope and `meta.schemaVersion` major component.
+ - The `error.code` enum (the SSOT exported as `ErrorCodes`) — adding a new code is non-breaking; renaming or removing one is breaking.
+ - The `{ ok, result/error, meta }` response envelope.
- Tool names and the **shape** of each tool's `inputSchema` (adding optional fields is non-breaking; renaming or making a field required is breaking).
- The 9 capability interfaces (`OnChainCapability`, `MultiSigCapability`, …) — adding an optional method is non-breaking.
- **Volatile contracts** (may change at any time):
- Internal helper exports under `src/internal/*`, `Knowledge Store` keys, recipe-runner internals.
- Pre-check error `details` strings (branch on `code`, not `details.reason`).
-- **Deprecation window.** A deprecated tool / field / capability method stays present for at least one minor cycle alongside its replacement, marked with `meta.deprecated` in `list_tools` output; removal lands no earlier than the cycle after.
-- **Adopting downstream.** Bump the `@tronlink/tronlink-mcp-core` peer / dependency only after re-running your downstream's `list_tools` snapshot test against the new core; assert `meta.schemaVersion` major matches the version your harness was written for.
+- **Deprecations.** [@tronlink/tronlink-mcp-core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Upgrading Core.** Record the installed package version. Compare `tools/list` against the tool names and input schemas your client uses, then check that the client handles a successful result and an error from a read-only tool.
---
@@ -3506,13 +3709,13 @@ This package is **the SSOT** for tool schemas, error codes, and `meta.schemaVers
**GitHub**: [https://github.com/TronLink/tronlink-skills](https://github.com/TronLink/tronlink-skills)
-> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `7d2d58cb`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.1**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
+> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `b12b5868`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.3**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
**TronLink Wallet Skills** is an AI Agent skill set that provides complete TRON blockchain wallet and DeFi functionality through natural language. Designed for Claude Code, Cursor, OpenCode, Codex CLI, and other AI agents.
**Key Highlights:**
- **6 skills, 33 commands** covering wallet, token research, market data, swaps, resources, and staking
-- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.1 — see [Dependencies](#dependencies)), no `npm install` needed
+- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.3 — see [Dependencies](#dependencies)), no `npm install` needed
- **TRON-specific domain knowledge** — dedicated handling of Energy + Bandwidth resource model
- **Multi-platform support** — Claude Code, Cursor, OpenCode, Codex CLI, LangChain/CrewAI
- **Read-only & safe** — all commands are query-only, no private keys or signing involved
@@ -3543,7 +3746,7 @@ Natural Language Input
AI Agent (Claude Code / Cursor / OpenCode / Custom)
|
v
-tron_api.mjs (Node.js 24.22.1, native fetch, zero dependencies)
+tron_api.mjs (Node.js 24.22.3, native fetch, zero dependencies)
├── Zero npm dependencies
├── TronGrid HTTP API (public or with API key)
└── Tronscan API for token metadata
@@ -3571,7 +3774,7 @@ Wallet queries and account information.
**Features:** Handles both Base58Check (T...) and hex address formats, supports known token symbols, auto-converts decimals.
-**When NOT to use:** Sending TRX/tokens — these are read-only; use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md). For deep token-level analytics (rug-pull / liquidity locks), prefer `tron-token`.
+**When NOT to use:** To transfer TRX or TRC-20 tokens with browser approval, use [Signer SDK](tronlink-signer.en.md) `sendTrx` or `sendTrc20`. For a local agent wallet, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_send`. Use `tron-token` for token risk and liquidity analysis.
### 2. tron-token (7 commands)
@@ -3622,7 +3825,7 @@ DEX swap quotes and route optimization.
**Features:** Aggregates liquidity from multiple sources, estimates Energy cost, handles multi-hop routes.
-**When NOT to use:** Executing the swap — quotes are read-only; the swap itself goes through [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_swap_v3`) or the signer SDK. Historical trade data — `tron-market`.
+**When NOT to use:** To execute a swap, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and a user-approved `slippage`. Use `tron-market` for historical trade data.
### 5. tron-resource (6 commands)
@@ -3639,7 +3842,7 @@ Energy & Bandwidth management — TRON-specific.
**Features:** Decision tree logic for cost optimization, tracks daily free bandwidth, calculates TRX burn equivalent.
-**When NOT to use:** Actually freezing TRX to acquire Energy/Bandwidth — that's a Remote Write; use the signer SDK / MCP Server. SR voting strategy after freezing — see `tron-staking`.
+**When NOT to use:** To freeze TRX for Energy or Bandwidth, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` with `action="freeze"`. Use `tron-staking` to research SRs before voting.
### 6. tron-staking (3 commands)
@@ -3653,13 +3856,13 @@ Stake 2.0 queries and SR information.
**Features:** Stake 2.0 status queries, APY calculation, SR commission tracking.
-**When NOT to use:** Performing the freeze/vote/unfreeze actions — those are Remote Writes; route through the signer SDK / MCP Server. Calculating Energy cost per operation — `tron-resource`.
+**When NOT to use:** Cast votes with [TronLink CLI](tronlink-cli.en.md) `tronlink vote` and claim voting rewards with `tronlink reward`. To freeze or unfreeze TRX, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake`. Use `tron-resource` for energy estimates.
---
## Skill ↔ MCP Tool Map
-`scripts/mcp_server.mjs` (the wrapper from [Method 2](#method-2-mcp-server)) exposes **25 of the 33 commands** as MCP tools — every signature, every input field, every output shape is generated from the same `tron_api.mjs` implementation, so the CLI and the MCP tool are guaranteed equivalent. The 8 CLI-only commands stay reachable through Method 1 (skill prompt) and Method 3 (direct CLI). Use this table when an agent needs to route a user request to a specific tool or when you're inspecting `tools/list` output.
+In the v1.0.x command set, `scripts/mcp_server.mjs` exposes **25 of 33 CLI commands** as MCP tools. At the default-branch commit `b12b5868`, it exposes 39 of 40 commands; only `swap-route` is CLI-only, so the “CLI-only” markers below apply to v1.0.x. The wrapper runs the corresponding CLI command and returns text in an MCP tool result. The remaining eight commands are available through the Skills or the CLI.
| Skill | CLI command | MCP tool name | Side effect | Retryable |
|---|---|---|---|:---:|
@@ -3697,7 +3900,7 @@ Stake 2.0 queries and SR information.
| `tron-staking` | `staking-info` | `tron_staking_info` | Network Read | Yes |
| `tron-staking` | `staking-apy` | `tron_staking_apy` | Network Read | Yes |
-**Totals.** 33 CLI commands · 25 MCP tools · 8 CLI-only commands. Every command is read-only — no signing, no broadcast, no fund movement. To execute a transaction, route to [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_*`) or [signer SDK](tronlink-signer.md) (`sendTrx`, `sendTrc20`, `sign*`).
+The v1.0.x table covers 33 read-only CLI commands, including 25 available over MCP. Use the routing examples below for transactions.
### Intent → Skill → Tool Routing
@@ -3731,16 +3934,16 @@ If the request implies **changing on-chain state** (transfer, swap execution, fr
### ❌ When NOT to route here (negative examples)
-Skills are **read-only**. If the user intent implies a signed / Remote Write action, do **not** dispatch to a skill — the underlying command will succeed but only as a query/estimate, and the user's actual goal will go unfulfilled. Route to the signer SDK or `mcp-server-tronlink` instead:
+Use Skills for queries and estimates. For actions that sign or broadcast, choose the route below. The [TronLink CLI](tronlink-cli.en.md) and signer SDK use browser approval. MCP Server direct chain tools sign with the local agent wallet, so the host must obtain confirmation before the call.
| User says (intent) | ❌ Wrong route (looks plausible, but read-only) | ✅ Correct route |
|---|---|---|
-| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.md) `tl_chain_send` |
-| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | `mcp-server-tronlink` `tl_chain_stake` (Remote Write, HITL) |
-| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | `mcp-server-tronlink` `tl_chain_stake` / signer SDK `signTransaction` |
-| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [signer SDK](tronlink-signer.md) `signTransaction` or `mcp-server-tronlink` `tl_chain_send` |
-| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | `mcp-server-tronlink` `tl_chain_swap_v3` (Remote Write, HITL, set `minOut`) |
-| "Claim my staking rewards" | `tron-staking staking-info` — only shows the pending balance. | `mcp-server-tronlink` `tl_chain_stake` (withdraw / claim) or signer SDK |
+| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.en.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.en.md) `tl_chain_send` |
+| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` (`action="freeze"`, `amount_trx=1000`, `resource="ENERGY"`) |
+| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | [TronLink CLI](tronlink-cli.en.md) `tronlink vote --votes :5000`. A vote replaces all of the account’s current votes; to keep votes for other SRs, list them in the same command. |
+| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [TronLink CLI](tronlink-cli.en.md) `tronlink trigger --contract --method 'approve(address,uint256)' --args '["","1000000"]'`. Use the token and router on the selected network. The router is the spender. For 6-decimal USDT, `1000000` authorizes 1 USDT. |
+| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and an explicitly approved `slippage` (%) |
+| "Claim my voting rewards" | `tron-staking staking-info` — only shows the pending balance. | [TronLink CLI](tronlink-cli.en.md) `tronlink reward` |
**Heuristic.** If the user's verb is *send / freeze / unfreeze / vote / unvote / approve / swap (execute) / claim / sign / broadcast*, the answer never starts in this Skills set. Skills can still **precede** the write (quote, estimate cost, validate address, check balance) — just don't claim a Skills call finished the user's request.
@@ -3794,8 +3997,8 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
- Freeze TRX → Get Energy or Bandwidth → Vote for SR → Earn rewards
- Unfreezing has **14-day wait** before withdrawal
- Votes reset if you unfreeze; must re-vote after re-freezing
-- 1 frozen TRX ≈ 4.5 Energy/day — **dynamic**: depends on total network stake; use `tron-resource estimate-energy` for the live value. Effective figure as of 2026-05.
-- Voting rewards claimable every 6 hours
+- Energy obtained by staking depends on the network’s current stake. Estimate the quota per TRX from `TotalEnergyLimit / TotalEnergyWeight` on the target network. `estimate-energy` estimates a contract call’s consumption. [GetAccountResource](https://developers.tron.network/reference/getaccountresource)
+- Voting rewards can be claimed once every 24 hours
---
@@ -3805,8 +4008,11 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
```bash
# Clone and use directly
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
claude # Auto-discovers SKILL.md files
```
@@ -3818,8 +4024,8 @@ No `npm install` needed for read-only operations.
# Register as MCP server
claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
-# Provides 25 MCP tools callable by Claude Desktop / Claude Code
-# (see "Skill ↔ MCP Tool Map" above for the per-command mapping; 8 commands are CLI-only)
+# Provides 39 MCP tools at b12b5868 (25 in v1.0.x), callable by Claude Desktop / Claude Code
+# (only swap-route is CLI-only at b12b5868; see "Skill ↔ MCP Tool Map" above for the v1.0.x mapping)
```
### Method 3: Manual CLI
@@ -3827,10 +4033,16 @@ claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
```bash
# Direct command execution
node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs swap-quote --from TRX --to USDT --amount 100
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs swap-quote --from-token TRX --to-token USDT --amount 100
```
+#### Handling Skills CLI and MCP errors
+
+In Skills v1.1.0 (`b12b5868`), an unknown CLI command or a missing required option exits with `1` and writes a diagnostic to stderr. A command can also exit with `0` and return an error in stdout. For example, `staking-apy --amount 0` returns JSON with `error`, `status: 400`, and `parameter: "amount"`. For a data query, check the exit status first, then parse stdout and check for `error` before using the result. [Skills CLI implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/tron_api.mjs)
+
+For MCP `tools/call`, check for a JSON-RPC error first (an unknown tool returns `-32602`). For a recognized tool, parse the JSON in `result.content[0].text` and check its `error` field. The wrapper can return command failures in this text with no `isError` flag. [Skills MCP implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/mcp_server.mjs)
+
### Method 4: Other AI Platforms
| Platform | Integration |
@@ -3887,7 +4099,10 @@ def tron_call(cmd: str) -> dict:
["node", "scripts/tron_api.mjs", *cmd.split()],
cwd="/absolute/path/to/tronlink-skills",
)
- return json.loads(out)
+ result = json.loads(out)
+ if isinstance(result, dict) and "error" in result:
+ raise RuntimeError(result["error"])
+ return result
tron_wallet_balance = Tool.from_function(
func=lambda addr: tron_call(f"wallet-balance --address {addr}"),
@@ -3985,7 +4200,7 @@ tronlink-skills/
| Dependency | Required? | Purpose |
|------------|-----------|---------|
-| Node.js 24.22.1 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.1 && nvm use 24.22.1` before installing. |
+| Node.js 24.22.3 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.3 && nvm use 24.22.3` before installing. |
| npm install | Not needed | All operations work without any npm dependencies |
---
@@ -3998,7 +4213,7 @@ tronlink-skills/
| Side effects | Every command is **Network Read**: it calls public APIs but changes no state. All commands are safe to retry; no human-in-the-loop confirmation is needed |
| No secrets required | Only optional TRONGRID_API_KEY for higher rate limits |
| Rate limits | Public TronGrid API; use TRONGRID_API_KEY for higher limits |
-| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). To execute a transaction (transfer, swap, stake), use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md) — these skills never sign or broadcast |
+| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). |
---
@@ -4029,28 +4244,31 @@ Both formats are supported and auto-normalized across all commands:
```bash
# 1. Clone
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
# 2. Use with Claude Code (no install needed for reads)
claude
-> "What's the TRX balance of TAddress...?"
-> "Show me the top trending tokens on TRON"
-> "How much Energy do I need to send USDT?"
-> "What's the best way to get Energy — freeze, rent, or burn?"
+# "What's the TRX balance of TAddress...?"
+# "Show me the top trending tokens on TRON"
+# "How much Energy do I need to send USDT?"
+# "What's the best way to get Energy — freeze, rent, or burn?"
-# 3. Or use directly
-node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs optimize-cost --address TAddress...
+# 3. Alternatively, run these in the shell. Set ACCOUNT to the address to query.
+node scripts/tron_api.mjs wallet-balance --address "${ACCOUNT:?set ACCOUNT}"
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs optimize-cost --address "${ACCOUNT:?set ACCOUNT}"
```
## Version & License
- **Package:** `tronlink-skills` v1.0.1 — the version the command tables on this page describe.
-- **Default branch:** v1.1.0 (commit `7d2d58cb`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
- - 7 additional read-only commands, also exposed as `tron_` MCP tools: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
- - Node.js is pinned to exactly 24.22.1 (`.nvmrc`, `engines`); `install.sh` exits on any other version.
+- **Default branch:** v1.1.0 (commit `b12b5868`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
+ - 7 additional read-only commands, also exposed as `tron_` MCP tools. At this commit `mcp_server.mjs` exposes 39 of the 40 commands; only `swap-route` is CLI-only. The new commands: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
+ - For this commit, [`.nvmrc`](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/.nvmrc) specifies Node.js 24.22.3. To reproduce [commit `7d2d58cb`](https://github.com/TronLink/tronlink-skills/blob/7d2d58cb/.nvmrc), use Node.js 24.22.1. Run `nvm install && nvm use` in the checked-out repository to select its pinned version.
- **License:** MIT — `SPDX-License-Identifier: MIT`
- **Changelog / releases:** [https://github.com/TronLink/tronlink-skills/releases](https://github.com/TronLink/tronlink-skills/releases) — no GitHub-tagged releases yet for v1.0.x; track changes by commit until the first tag.
@@ -4061,13 +4279,12 @@ Skills are at **v1.0.x**, so standard semver applies — only **major** bumps ma
- **Stable contracts** (won't change in a minor or patch):
- The 33 CLI command names and their required / optional flags (`tron_api.mjs [...]`).
- The 25 MCP tool names listed in [Skill ↔ MCP Tool Map](#skill-mcp-tool-map) (`tron_*` form) and their `inputSchema` keys.
- - Exit codes: `0` success, `1` query error / invalid input, `2` unsupported / unknown command.
- The `Network Read` side-effect classification — no command will ever become a Remote Write without a major bump.
- **Volatile contracts** (may change in a minor):
- The exact field layout of JSON `stdout` payloads — new fields can be added in any minor; renames or removals are major. Use a tolerant parser.
- Built-in token-symbol shortcut list (`USDT`, `USDC`, `WTRX`, …) — symbols may be added in any minor; existing mappings won't be repointed in a minor.
- Heuristics and thresholds (`whale-transfers` default cutoff, `optimize-cost` decision tree weights, etc.).
-- **Subset relationship.** The MCP tool subset (currently 25 of 33) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
+- **Subset relationship.** The MCP tool subset (25 of 33 in v1.0.x; 39 of 40 at `b12b5868`) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
- **Deprecation window.** A command / tool marked deprecated continues to work for at least one minor cycle. Removal lands no earlier than the next major.
- **Verifying after upgrade.** Re-run `tron_api.mjs --help` and (if using MCP) `tools/list` to confirm the names you depend on are still present. The MCP `serverInfo.version` exposed during `initialize` should match the bumped `package.json` version.
@@ -4224,7 +4441,7 @@ In v0.1.4, errors are returned as an MCP tool result with `isError: true` and a
|---|---|---|
| **Prompt injection** | Tool inputs are consumed verbatim as call arguments; the server does not re-prompt an LLM with them. The TronLink approval page renders parsed transaction fields, not the agent's free-text. | Treat any on-chain string returned (memos, revert reasons) as untrusted; branch on `txId` / `status`, not on prose. |
| **Local HTTP listener** | The local approval server **binds to `127.0.0.1` only** (port `TRON_HTTP_PORT`, default 3386, auto-increments on conflict). It never accepts off-host connections. Each server session has a unique ID; old browser tabs from previous sessions are invalidated automatically. | Do not port-forward 3386 over a network. Do not run two copies of this server with the same `TRON_HTTP_PORT` on a shared box. |
-| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [Networks](#environment-variables) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
+| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [network endpoints](../reference/networks.md#networks) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
| **API key handling (token passthrough)** | `TRON_API_KEY` is read from env at startup and used only on the outbound leg to TronGrid. It is **not** returned in any tool response, error `details`, or MCP resource. The server does not accept Authorization headers from MCP clients and forward them upstream. | Store the key in the MCP host's secret manager, not in plain `mcpServers` config committed to git. |
| **HITL is mandatory for signing** | Every signing tool (`send_trx`, `send_trc20`, `sign_message`, `sign_typed_data`, `sign_transaction`) opens the TronLink approval page. **There is no programmatic bypass.** Private keys never leave TronLink. | Operators do not need to enforce HITL — it is structural. Do not attempt to harden by removing the browser layer. |
| **Browser tab hijacking** | The approval page authenticates each request against the server session ID and ignores stale tabs. Heartbeat detection closes the session on browser disconnect. | If the same user runs multiple agents, ensure each spawns its own signer instance; cross-instance request mixing is prevented by session ID, but UI confusion is not. |
@@ -4278,7 +4495,7 @@ Co-released with `tronlink-signer@0.1.2`. **Major UX overhaul** on the approval
### Compatibility & migration policy
- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change MCP tool names or input schemas. Post-1.0: standard semver — major-only breaking changes.
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag in the schema; removal lands no earlier than the cycle after that.
+- **Deprecations.** [mcp-tronlink-signer 0.1.4](https://www.npmjs.com/package/mcp-tronlink-signer/v/0.1.4) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
- **Stable contracts.** Tool names and `status` values (`success` / `pending` / `failed`) are part of the public surface — they don't change in a patch.
- **Volatile contracts.** Error `message` text (match the known values under [Errors](#errors) and treat others as unknown), log line formats, and the layout of the browser approval page are **not** part of the public surface and may change at any time.
- **Verifying after upgrade.** Re-call `list_tools` and confirm the names + schemas you depend on are still present before resuming a workflow.
@@ -4301,18 +4518,26 @@ npm install tronlink-signer
## Quick Start
+On Nile, select a funded test account and set the Node.js environment variable `RECIPIENT` to your test recipient’s address. This example requests approval to send 1 test TRX.
+
```ts
import { TronSigner } from "tronlink-signer";
+const recipient = process.env.RECIPIENT;
+if (!recipient) throw new Error("Set RECIPIENT to the Nile recipient address");
const signer = new TronSigner();
await signer.start();
-const { address, network } = await signer.connectWallet();
-const { txId, status } = await signer.sendTrx("TXxx...", 1); // status: "success" | "pending" | "failed"
-const { txId: txId2, status: s2 } = await signer.signTransaction(tx, "nile", true); // broadcast + auto-confirm
-const { balance } = await signer.getBalance("TXxx...");
-
-await signer.stop();
+try {
+ const { address } = await signer.connectWallet("nile");
+ const { balance } = await signer.getBalance(address, "nile");
+ console.log(address, balance);
+ // Signer takes TRX, so this sends 1 TRX.
+ const { txId, status } = await signer.sendTrx(recipient, 1, "nile");
+ console.log(txId, status);
+} finally {
+ await signer.stop();
+}
```
## API
@@ -4391,25 +4616,51 @@ Signs a raw transaction. When `broadcast` is `true`, the signed transaction is b
| `broadcast` | `boolean` | Whether to broadcast after signing (default: `false`) |
| `options` | `SignerOptions` | Optional — cancellation, confirmation control, broadcast callback |
-```ts
+To build an unsigned Nile transfer in Node.js, install `tronlink-signer` and `tronweb@6`. Select the funded Nile payer in TronLink and set `RECIPIENT` to the intended Nile recipient address. Run this setup followed by one calling pattern in the same ES module.
+
+```js
+import { TronSigner } from "tronlink-signer";
+import { TronWeb } from "tronweb";
+
+const signer = new TronSigner();
+const tronWeb = new TronWeb({ fullHost: "https://nile.trongrid.io" });
+const recipient = process.env.RECIPIENT;
+if (!TronWeb.isAddress(recipient)) throw new Error("Set RECIPIENT to a TRON address");
+await signer.start();
+const { address } = await signer.connectWallet("nile");
+// The builder takes SUN, so this creates a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronWeb.transactionBuilder.sendTrx(recipient, 10, address);
+```
+
+Choose one of the following calling patterns.
+
+```js
// Sign only
-const { signedTransaction } = await signer.signTransaction(tx);
+const { signedTransaction } = await signer.signTransaction(tx, "nile");
+```
+```js
// Sign, broadcast, and wait for confirmation (default)
const { signedTransaction, txId, status, error } = await signer.signTransaction(tx, "nile", true);
// status === "success" — confirmed on-chain
// status === "pending" — broadcast succeeded but not confirmed within timeout
// status === "failed" — on-chain execution failed; `error` carries the reason
+```
+```js
// Broadcast without waiting for confirmation
const result = await signer.signTransaction(tx, "nile", true, { confirm: false });
+```
+```js
// Get notified as soon as the tx enters the mempool
const result = await signer.signTransaction(tx, "nile", true, {
onBroadcasted: ({ txId }) => console.log("Broadcast:", txId),
});
```
+Wrap connection, construction and the selected call in `try / finally`, and call `await signer.stop()` in `finally` as in Quick Start. If a broadcast outcome is unknown, look up the transaction ID before taking further action.
+
### Broadcast Result
Broadcasting methods (`sendTrx`, `sendTrc20`, and `signTransaction` with `broadcast: true`) return a `BroadcastResult`:
@@ -4944,7 +5195,10 @@ In `--json` mode, v1.0.1 writes failures to **stderr** and exits with `1`:
2. For read operations with `--address`: queries TronGrid directly
3. For write/read without `--address`: connects to the TronLink browser extension for wallet info
4. Builds unsigned transaction using local TronWeb `transactionBuilder`
-5. Pre-flight check: runs on all write commands (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+5. Pre-flight check: depends on the command (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+
+ In v1.0.1, `withdraw` queries the payer’s `unfrozenV2` entries and errors before signing if no matured TRX is available. `reward` calls `getReward(address)` and returns without signing if the amount is zero or less (JSON status `No Rewards`). A failed lookup stops either command before signing.
+
6. Sends transaction to TronLink for signing (browser approval page)
7. Broadcasts: signer broadcasts by default, or CLI broadcasts locally with `--local-broadcast`. In both modes the CLI polls `getUnconfirmedTransactionInfo` until the tx is packed into a block (~3s), and surfaces OUT_OF_ENERGY / REVERT / FAILED as errors
8. Outputs result
@@ -5048,11 +5302,15 @@ tronlink reward --json
### Example: AI Transfer Flow
```bash
-# 1. Check balance first
-tronlink balance --address TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL --network mainnet --json
+# Set PAYER to the address selected in TronLink and RECIPIENT to the destination.
+# If the wallet account or network changes, cancel and check the new balance first.
+NETWORK=mainnet
+
+# 1. Check the payer's balance
+tronlink balance --address "${PAYER:?set PAYER}" --network "$NETWORK" --json
# 2. Send 10 TRX (opens browser for signing, wait for return)
-tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network mainnet --json
+tronlink transfer --type trx --toAddress "${RECIPIENT:?set RECIPIENT}" --amount 10 --network "$NETWORK" --json
# 3. Verify result — output includes txId and explorer URL
# { "Status": "Success", "TxID": "abc...", "Explorer": "https://tronscan.org/#/transaction/abc..." }
@@ -5162,48 +5420,124 @@ For this section, you may refer to [General Transfer](transfer.en.md)
## Query active permissions
-`multiSign` requires a valid `permissionId` for an **active** permission on the signing account. Active permissions are returned by `tronWeb.trx.getAccount(address)` under the `active_permission[]` field; each entry exposes `id`, `permission_name`, `threshold`, and the `keys[]` array (address + weight). Owner permissions have a fixed `id` of `0` and are exposed under `owner_permission` separately.
+Choose the account that holds the funds. If the connected signer owns the funds, use its address. For a co-signer, enter the controlled account’s address. Read that owner’s permissions on the transaction network and select an entry whose keys include the signer and whose operations allow TRX transfers. Use its actual `id`.
```javascript
const tronweb = window.tron.tronWeb;
-const account = await tronweb.trx.getAccount(tronweb.defaultAddress.base58);
-// account.active_permission is the array — pick the id whose keys[] includes
-// the address you intend to sign with, and whose weight + threshold allow the tx.
-const activePermissions = account.active_permission ?? [];
-console.log(activePermissions.map(p => ({ id: p.id, name: p.permission_name, threshold: p.threshold })));
+const owner = "REPLACE_WITH_OWNER_ADDRESS";
+const account = await tronweb.trx.getAccount(owner);
+console.table(account.active_permission);
```
-Use the resulting `id` as `permissionId` below.
-
## Specification
-### Example
+### Sign and check the weight
+
+Use these helpers with the authorized TronWeb instance on the transaction network. Before broadcasting, the node checks the signatures against the transaction owner’s current permission. [GetSignWeight](https://developers.tron.network/reference/getsignweight)
```javascript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TRKb2nAnCBfwxnLxgoKJro6VbyA6QmsuXq";
-// fromAddress = the account whose active permission controls the funds (the tx owner).
-// It is not necessarily the connected signer: if the connected account is only a
-// co-signer listed in that permission's keys[], set fromAddress to the controlled account.
-const fromAddress = tronweb.defaultAddress.base58;
-const activePermissionId = 2; // obtained via tronWeb.trx.getAccount(fromAddress).active_permission
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId }
-); // Step 1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // Step 2
- const res = await tronweb.trx.sendRawTransaction(signedTx); // Step 3
- if (!res.result) {
- // Node rejections are returned, not thrown — see Errors below.
- console.error(res.code, res.message && tronweb.toUtf8(res.message));
+function validateSignWeight(check, permissionId) {
+ const { permission, result, current_weight: weight } = check ?? {};
+ if (result?.code === "PERMISSION_ERROR") throw new Error("Recheck owner and permission");
+ if (!result || typeof result !== "object" || Array.isArray(result) ||
+ !permission || !Number.isSafeInteger(permission.threshold) ||
+ permission.threshold <= 0 || !Number.isSafeInteger(weight) || weight < 0 ||
+ !/^[0-9a-f]{64}$/i.test(permission.operations)) {
+ throw new Error("Permission or weight unavailable");
+ }
+ // TransferContract is operation 1 in the active permission bitmap.
+ const allowsTransfer = (parseInt(permission.operations.slice(0, 2), 16) & 2) !== 0;
+ if (permission.type !== "Active" || permission.id !== permissionId || !allowsTransfer) {
+ throw new Error("Recheck owner and permission");
+ }
+ return { code: result.code, weight, threshold: permission.threshold };
+}
+
+async function checkAndBroadcast(tronweb, signedTx, permissionId) {
+ const check = await tronweb.trx.getSignWeight(signedTx);
+ const { code, weight, threshold } = validateSignWeight(check, permissionId);
+ if (code === "NOT_ENOUGH_PERMISSION" && weight < threshold) {
+ return { status: "collect", signedTx };
+ }
+
+ // The node may omit the default ENOUGH_PERMISSION code.
+ if ((code !== undefined && code !== "ENOUGH_PERMISSION") || weight < threshold) {
+ throw new Error("Signature weight check failed");
+ }
+
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ throw new Error([receipt.code, message].filter(Boolean).join(" ") || "Broadcast rejected");
+ }
+ return { status: "submitted", txID: signedTx.txID };
+}
+
+async function signAndCheck(tronweb, tx) {
+ const permissionId = tx.raw_data.contract[0].Permission_id;
+ if (!Number.isSafeInteger(permissionId) || permissionId < 2) {
+ throw new Error("An active permission ID is required");
}
-} catch (e) {}
+
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.multiSign(tx, undefined, permissionId);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return { status: "declined" };
+ throw error;
+ }
+
+ return checkAndBroadcast(tronweb, signedTx, permissionId);
+}
+```
+
+### First signer
+
+Replace the recipient address and use the permission ID selected from the owner’s active permissions above.
+
+```javascript
+const recipient = "REPLACE_WITH_RECIPIENT_ADDRESS";
+const permissionId = 2; // Replace with the selected permission ID.
+if (!account.active_permission?.some(p => p.id === permissionId)) {
+ throw new Error("Select an active permission of the transaction owner");
+}
+
+// Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronweb.transactionBuilder.sendTrx(recipient, 10, owner, { permissionId });
+const outcome = await signAndCheck(tronweb, tx);
```
-If the user chooses “Reject” in the pop-up window, an exception will be thrown, which the developer can catch for further processing. If the user chooses “Sign” in the pop-up window, the DApp receives and broadcasts the signed transaction.
+### Additional co-signers
-Note that the broadcast only collects one signature in this call — a fully signed multi-sig tx requires the threshold to be met across multiple `multiSign` calls (one per co-signer). Track the partially-signed transaction off-chain (or via the MCP `tl_multisig_*` tools) until the threshold is reached, then broadcast.
+When the outcome has status `collect`, pass its `signedTx` to the next authorized co-signer using your DApp’s handoff flow. Each co-signer connects their wallet on the same network. Before signing, check that the transaction data matches its `txID`, show the co-signer the decoded owner, recipient, amount and expiration, and continue only after they confirm. Pass `coSignTransfer` the received transaction object and a `confirmTransfer` callback that resolves to `true` once the co-signer approves. `signAndCheck` calls `multiSign` on that object so the existing signatures and transaction ID carry forward.
+
+```javascript
+function describeTransfer(tronweb, tx) {
+ // The signature covers txID, so confirm raw_data hashes to it before showing details.
+ const txCheck = tronweb.utils?.transaction?.txCheck;
+ if (!txCheck || !txCheck(tx)) throw new Error("Transaction data does not match its txID");
+ const contract = tx.raw_data.contract[0];
+ if (contract.type !== "TransferContract") throw new Error("Not a TRX transfer");
+ const { owner_address, to_address, amount } = contract.parameter.value;
+ return {
+ owner: tronweb.address.fromHex(owner_address),
+ recipient: tronweb.address.fromHex(to_address),
+ amount: `${tronweb.fromSun(amount)} TRX`,
+ permissionId: contract.Permission_id,
+ expires: new Date(tx.raw_data.expiration).toISOString(),
+ };
+}
+
+async function coSignTransfer(partiallySignedTx, confirmTransfer) {
+ const tronweb = window.tron.tronWeb;
+ const details = describeTransfer(tronweb, partiallySignedTx);
+ // Show the details in your UI; sign only after the co-signer confirms them.
+ if (!(await confirmTransfer(details))) return { status: "declined" };
+ return signAndCheck(tronweb, partiallySignedTx);
+}
+```
+
+Repeat the handoff on `collect`. On `declined`, stop the current signing attempt. If the weight lookup fails or required fields are missing, pause and run the full weight check again after recovery. If the permission was revoked or no longer allows this operation, verify the owner and permission ID, rebuild the transaction and collect fresh signatures. If broadcast times out, look up the transaction ID before another submission.
## Errors
@@ -5212,7 +5546,7 @@ Note that the broadcast only collects one signature in this call — a fully sig
| Code | Meaning | Where it comes from | Retryable? |
| :---: | --- | --- | :---: |
| `'Confirmation declined by user'` (string) | User clicked **Reject** in the signing popup | `tronWeb.trx.multiSign(...)` | No — user declined |
-| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `fromAddress` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(fromAddress).active_permission` and rebuild the transaction |
+| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `owner` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(owner).active_permission` and rebuild the transaction |
| `code: 'SIGERROR'`, other `Validate signature error: …` messages | Signatures do not satisfy the permission — e.g. total weight below `threshold`, or a signer that is not in its `keys[]` | Return value of `sendRawTransaction(...)` (not thrown) | No — collect the missing signatures (one `multiSign` call per co-signer) |
| `REVERT` / `OUT_OF_ENERGY` / `FAILED` | Broadcast succeeded but execution failed on-chain | `getTransactionInfo(txid)` | **No — the tx is final; never auto-retry** |
@@ -5244,7 +5578,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
### Parameters
@@ -5264,12 +5604,7 @@ If the user chooses to sign in the pop-up window, the DApp will get the signed h
0xb0e0b150b9b10dc348f25c7f38fc87f16e18c0d230d23946aac519a5ad9e45937f656012d33c09e9d9dec00b03fbb304e797f8991bb823dce676ac91e03a55991b
```
-If an error occurs, the following information will be returned:
-
-```text
-
- Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
## Interaction
@@ -5433,7 +5768,7 @@ Definitions of terms, standards, and identifiers used across this documentation.
- **ABI** — Application Binary Interface: the JSON description of a contract's callable methods and events. If a token contract's ABI lacks a recognized method (e.g. `transfer`, `approve`), TronLink may not be able to offer that action.
- **`chainId`** — the network identifier. TronLink uses the hex form (e.g. `0x2b6653dc`) for `wallet_switchEthereumChain` and `chainChanged`, and the decimal EVM form (e.g. `728126428`) for EIP-712 `domain.chainId`. See [Networks & Addresses](networks.md).
- **`ProviderRpcError`** — the EIP-1193 error object emitted on `disconnect`, shaped `{ code: number; message: string; data?: unknown }`.
-- **permission id** — the active permission index used for multi-signature transactions (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
+- **permission id** — the value of the selected active permission’s `id` field on the transaction owner’s account (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
- **base58 / hex address** — the two TRON address encodings (`T...` vs `41...`). See [Networks & Addresses](networks.md#address-formats).
## AI tooling
@@ -5453,7 +5788,7 @@ TronLink agents traverse three or four error-code dialects when a single user re
**Error shape:** On the TronLink-injected `tronWeb` (extension 4.0.0 and later), when the user rejects `trx.sign`, `trx.multiSign`, or `trx.signMessageV2`, the promise rejects with the **plain string** `'Confirmation declined by user'` — not an `Error` object, and without a numeric `code`. The `{ code: 4001, message: 'User rejected the request.' }` object is returned only by `window.tron.request(...)` methods such as `eth_requestAccounts`. Other failures (locked wallet, invalid payload, watch-only account) use other values — see [Handling rejections](#handling-rejections). Do not automatically retry signing.
-| Business meaning | DApp provider ([EIP-1474][provider]) | DeepLink ([5-digit][deeplink]) | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
+| Business meaning | DApp provider ([EIP-1474][provider]) | [DeepLink callback code][deeplink] | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
| --- | :---: | :---: | :---: | :---: | :---: |
| **User rejected** the signing or connection prompt | `4001` from `window.tron.request(...)`; the string `'Confirmation declined by user'` from `tronWeb.trx.sign` / `multiSign` / `signMessageV2` | `300` (Transaction canceled) | — (HITL — re-prompt only on a fresh tool call) | `1` | **No** |
| **Invalid input** / malformed params | thrown by `tronWeb` builder | `10001`–`10020`, `10024`, `10025` | `TL_INVALID_INPUT` | `1` | **No** — fix the payload |
diff --git a/docs/llms-full.txt b/docs/llms-full.txt
index c93053b..d1bb85b 100644
--- a/docs/llms-full.txt
+++ b/docs/llms-full.txt
@@ -2,11 +2,11 @@
> Concatenation of all English documentation pages for single-fetch LLM ingestion. Generated by scripts/gen_llms_full.py. See ./llms.txt for the curated index.
-- Generated: 2026-11-04T10:12:58Z
-- Commit: 56f294d79923
+- Generated: 2026-11-26T12:11:13Z
+- Commit: 7d9fecacf230
- Language: en
-- Pages: 24
-- Token estimate: ~61,555 (chars / 4)
+- Pages: 27
+- Token estimate: ~67,446 (chars / 4)
---
@@ -143,27 +143,39 @@ The following self-contained HTML example detects TronLink via TIP-6963, request
async function connect() {
if (!tronProvider) return alert("TronLink not found!");
try {
- const accounts = await tronProvider.request({
- method: "eth_requestAccounts",
- });
- console.log("Connected:", accounts[0]);
-
- const tronweb = tronProvider.tronWeb;
- const from = tronweb.defaultAddress.base58;
- const to = "TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP"; // replace with the actual recipient address
+ await tronProvider.request({ method: "eth_requestAccounts" });
+ } catch (error) {
+ if (error?.code === 4001) return console.info("Connection declined");
+ return console.error("Authorization failed", error);
+ }
- // Build a 10 SUN TRX transfer (amount unit is SUN: 1 TRX = 1_000_000 SUN)
- const tx = await tronweb.transactionBuilder.sendTrx(to, 10, from);
+ const tronweb = tronProvider.tronWeb;
+ let tx;
+ try {
+ const to = "REPLACE_WITH_RECIPIENT_ADDRESS";
+ // Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+ tx = await tronweb.transactionBuilder.sendTrx(to, 10, tronweb.defaultAddress.base58);
+ } catch (error) {
+ return console.error("Could not build transfer", error);
+ }
- // Pops up the TronLink confirmation window
- const signedTx = await tronweb.trx.sign(tx);
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return console.info("Signing declined");
+ return console.error("Signing failed", error);
+ }
- // Broadcast to the network
- const broadcastTx = await tronweb.trx.sendRawTransaction(signedTx);
- console.log(broadcastTx);
+ try {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ return console.error(receipt.code, message);
+ }
+ console.log("Check on-chain confirmation for", signedTx.txID);
} catch (error) {
- // { code: 4001, message: "User rejected the request." } when the user declines
- console.error(error);
+ console.error("Broadcast outcome unknown. Check transaction before retrying", signedTx.txID, error);
}
}
@@ -277,7 +289,14 @@ img {
}
-For every action below, the `param` value of `tronlinkoutside://pull.activity?param={}` is the protocol data in JSON format. Note: the JSON string must be URL-encoded before being placed in the link.
+The `param` query parameter contains URL-encoded JSON. Each sample link encodes the request shown below it. For your integration, replace the sample values and generate a new URL.
+
+```javascript
+const buildDeepLink = (request) =>
+ "tronlinkoutside://pull.activity?param=" + encodeURIComponent(JSON.stringify(request));
+```
+
+For login, transfer and signing, use your DApp URL and callback, the target chain ID, and a fresh action ID. For transaction signing, set `data` to the JSON string of a newly built transaction. The sample transaction contains an expired timestamp.
## Open Wallet
@@ -286,7 +305,7 @@ For every action below, the `param` value of `tronlinkoutside://pull.activity?pa
Available since TronLink v4.10.0.
```html
-Open Tronlink
+Open Tronlink
```
`param` (request):
@@ -306,7 +325,7 @@ Available since TronLink v4.10.0.
Available since TronLink v4.10.0.
```html
-Open DApp
+Open DApp
```
`param` (request) — `url` is the target DApp:
@@ -325,14 +344,14 @@ Available since TronLink v4.10.0.
Available since TronLink v4.11.0.
```html
-Login/Request Address
+Login/Request Address
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -361,14 +380,14 @@ Callback:
Available since TronLink v4.11.0.
```html
-Transfer
+Transfer
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -404,14 +423,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign transaction
+Sign transaction
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -445,14 +464,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign message
+Sign message
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -481,40 +500,38 @@ Callback:
## Result Code
-> Note: `tokenId` and `contract` are mutually exclusive in a transfer request — supplying both returns code `10025`.
-
-| Code | Message |
-|:-------|:-------|
-| 0 | success |
-| 10001 | Incorrect JSON format |
-| 10002 | Missing Action |
-| 10003 | Unknown Action |
-| 10004 | Missing ActionId |
-| 10005 | Incorrect DApp URL format |
-| 10006 | Incorrect CallbackUrl format |
-| 10007 | Empty DApp name |
-| 10008 | Version number not supported |
-| 10009 | Current network not supported |
-| 10010 | The URL is not supported to open TronLink |
-| 10011 | Unknown SignType |
-| 10012 | Incorrect Transaction format |
-| 10013 | Incorrect Method format |
-| 10014 | Incorrect Message format |
-| 10015 | Incorrect toAddress |
-| 10016 | No wallet created in TronLink |
-| 10017 | Incorrect fromAddress |
-| 10018 | Incorrect contractAddress |
-| 10019 | Incorrect chainId |
-| 10020 | Incorrect amount |
-| 10021 | The initiating address does not match the current wallet |
-| 10022 | Incorrect loginAddress |
-| 10023 | System contract not support |
-| 10024 | Incorrect tokenId |
-| 10025 | TokenId & Contract address should not exist together |
-| 300 | Transaction canceled |
-| 301 | Transaction executed in TronLink |
-| 302 | Broadcast failure - returned with incorrect info |
-| -1 | Unknown reason |
+| Code | Message | Notes |
+|:-------|:-------|:-------|
+| 0 | success | |
+| 10001 | Incorrect JSON format | |
+| 10002 | Missing Action | |
+| 10003 | Unknown Action | |
+| 10004 | Missing ActionId | |
+| 10005 | Incorrect DApp URL format | |
+| 10006 | Incorrect CallbackUrl format | |
+| 10007 | Empty DApp name | |
+| 10008 | Version number not supported | |
+| 10009 | Current network not supported | |
+| 10010 | The URL is not supported to open TronLink | |
+| 10011 | Unknown SignType | |
+| 10012 | Incorrect Transaction format | |
+| 10013 | Incorrect Method format | |
+| 10014 | Incorrect Message format | |
+| 10015 | Incorrect toAddress | |
+| 10016 | No wallet created in TronLink | |
+| 10017 | Incorrect fromAddress | |
+| 10018 | Incorrect contractAddress | |
+| 10019 | Incorrect chainId | |
+| 10020 | Incorrect amount | |
+| 10021 | The initiating address does not match the current wallet | |
+| 10022 | Incorrect loginAddress | |
+| 10023 | System contract not support | |
+| 10024 | Incorrect tokenId | |
+| 10025 | TokenId & Contract address should not exist together | Conflicting asset identifiers in a transfer request. |
+| 300 | Transaction canceled | |
+| 301 | Transaction executed in TronLink | |
+| 302 | Broadcast failure - returned with incorrect info | |
+| -1 | Unknown reason | |
## JSON Schema Reference
@@ -609,7 +626,13 @@ Every `param` shares this prefix:
}
```
-**Transfer** request — `tokenId` (TRX / TRC10) and `contract` (TRC20) are **mutually exclusive**; supplying both returns `10025`. Set the unused one to `""` (empty string):
+**Transfer** uses the field values below. Send the unused field as an empty string, following the transfer sample and the DeepLink demo request format. Omitting the unused key produces a request that differs from these samples; this page does not define how the App treats an omitted key, so keep both keys present.
+
+| Asset | `tokenId` | `contract` |
+|---|---|---|
+| TRX | `"0"` | `""` |
+| TRC10 | Decimal token ID as a string | `""` |
+| TRC20 | `""` | Token contract address |
```json
{
@@ -623,8 +646,8 @@ Every `param` shares this prefix:
"from": { "type": "string", "description": "Sender TRON address (base58)" },
"to": { "type": "string", "description": "Recipient TRON address (base58)" },
"loginAddress": { "type": "string", "description": "Address that authorized this session — must match the current wallet (otherwise code 10021)" },
- "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX; pass '' when sending TRC20" },
- "contract": { "type": "string", "description": "TRC20 contract address; pass '' when sending TRX / TRC10" },
+ "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX" },
+ "contract": { "type": "string", "description": "TRC20 contract address" },
"amount": { "type": "string", "description": "Decimal string in human units (e.g. '1.5'); the app handles decimals" },
"memo": { "type": "string", "description": "Optional transaction memo" },
"dappName": { "type": "string" },
@@ -728,9 +751,11 @@ The full set of values is in the [Result Code](#result-code) table above. Branch
## TronLink Integration
-TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with TronLink DApps and the TRON network.
+TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with the TronLink App and the TRON network.
+
+Once the in-app browser has supplied an authorized TronWeb instance, the transaction-building steps in [Start Developing](../dapp/getting-started.md) apply. That guide demonstrates provider discovery (TIP-6963), authorization (`eth_requestAccounts`) and events for the browser extension. Check support for each of those interfaces on the target App version.
-Details: [Go to DApp](../../dapp/getting-started)
+From an external mobile browser, use [DeepLink](deeplink.md) to open TronLink.
## DApp Explorer
@@ -754,6 +779,112 @@ Tron DApp running in the DApp Explorer injects iTron objects automatically to of
---
+
+
+# Android Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-android-core](https://github.com/TronLink/tronlink-android-core)
+
+Integrate the wallet functions used by TronLink Android to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+The library requires Android API level 21 or later; the Java version is set in the upstream [build configuration](https://github.com/TronLink/tronlink-android-core/blob/main/core/build.gradle). Add JitPack to the repositories Gradle uses to resolve dependencies (Groovy DSL).
+
+```groovy
+repositories {
+ maven { url "https://jitpack.io" }
+}
+```
+
+Add the AAR to the app module’s dependencies. Replace `` with a tag from the [releases](https://github.com/TronLink/tronlink-android-core/releases), normally the latest.
+
+```groovy
+dependencies {
+ implementation 'com.github.TronLink:tronlink-android-core:@aar'
+}
+```
+
+## Create a wallet
+
+Create a wallet in your app and read its TRON address.
+
+```java
+import org.tron.walletserver.Wallet;
+
+// Inside an application method
+Wallet wallet = new Wallet(true);
+String address = wallet.getAddress();
+```
+
+The wallet tests also show how to restore an address from a mnemonic or private key. For transaction signing, see the transaction tests. The tests include no message-signing example; the library implements it in `org.tron.common.bip32.Sign` (`signPrefixedMessage`, `signPrefixedMessageV2`). [Wallet examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/WalletCoreUnitTest.java) · [Transaction signing examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/TransactionCoreUnitTest.java) · [`Sign.java`](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/main/java/org/tron/common/bip32/Sign.java)
+
+## Verify the AAR
+
+Verification requires the exact AAR signed by TronLink and its matching detached `.asc` signature. JitPack and the GitHub releases do not provide signature files, so obtain the signed AAR and matching signature from the maintainers. See the [upstream verification instructions](https://github.com/TronLink/tronlink-android-core#integrity-check).
+
+Download the [public key](https://keys.openpgp.org/vks/v1/by-fingerprint/7B910EA80207596075E6D7BA5D34F7A6550473BA) as `tronlink-build.asc`. Check the signing subkey fingerprint against the one in the upstream instructions, `7B910EA80207596075E6D7BA5D34F7A6550473BA`. Once it matches, import the key and verify the two files supplied by the maintainers, substituting their filenames below.
+
+```bash
+gpg --show-keys --with-subkey-fingerprint tronlink-build.asc
+gpg --import tronlink-build.asc
+gpg --verify release.aar.asc release.aar
+```
+
+## Privacy
+
+Embedding the library does not start usage reporting. The reporting code in `org.tron.metrics` records and uploads data only after the host app wires up its repositories and calls `DataUploader.init(...)` and `upload(...)`. Read the upstream [privacy policy](https://github.com/TronLink/tronlink-android-core/blob/main/PRIVACY-POLICY.md) before enabling it.
+
+## Version & License
+
+The examples and links on this page follow the upstream `main` branch. When you pin an older tag, check that its APIs match. [Apache License 2.0](https://github.com/TronLink/tronlink-android-core/blob/main/LICENSE)
+
+---
+
+
+
+# iOS Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-iOS-core](https://github.com/TronLink/tronlink-iOS-core)
+
+Use TronLink’s native iOS wallet module to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+Add the dependency to your app target in the Podfile. The minimum iOS version and the Swift version are declared in the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec).
+
+```ruby
+pod 'tronlink-iOS-core'
+```
+
+Run `pod install`, open the generated `.xcworkspace` in Xcode, and import the module in Swift.
+
+```swift
+import TLCore
+```
+
+## Run the example project
+
+To explore the wallet APIs in the upstream Xcode project, install its pods from the example directory.
+
+```bash
+git clone https://github.com/TronLink/tronlink-iOS-core.git
+cd tronlink-iOS-core/Example
+pod install
+```
+
+Open the workspace in `Example/`. The Swift tests show wallet creation, transaction and message signing, and how to export a private key or mnemonic. [Swift wallet examples](https://github.com/TronLink/tronlink-iOS-core/blob/main/Example/Tests/Tests.swift)
+
+## Privacy
+
+Installing the pod or creating a wallet does not start a statistics upload. The host app must invoke the reporter and implement the upload callback in `TRXMetricsDataSource`. To enable uploads, the app must also identify its environment as production or pre-release. The same check applies to Debug and Release builds. In TronLink iOS, Basic Mode suppresses reporting, as do watch-only wallets and Shasta activity. [iOS privacy policy](https://github.com/TronLink/tronlink-iOS-core/blob/main/PRIVACY-POLICY.md)
+
+## Version & License
+
+For the current version, see the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec). [Apache License 2.0](https://github.com/TronLink/tronlink-iOS-core/blob/main/LICENSE)
+
+---
+
# Proactively Request TronLink Plugin Features
@@ -773,7 +904,10 @@ This method follows the Ethereum **EIP-1102** protocol.
```javascript
try {
await window.tron.request({method: 'eth_requestAccounts'});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Connection declined");
+ else console.error("Authorization failed", error);
+}
```
#### Return Value
@@ -898,10 +1032,17 @@ const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+} catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+}
+if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+}
```
When executing `await tronweb.trx.sign(tx);`, TronLink displays a confirmation popup.
@@ -926,24 +1067,7 @@ Refer to **Normal Transfer** above.
#### Code Example
-```typescript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
-const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
-const activePermissionId = 2;
-
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
-);
-
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
-```
-
-Rejecting triggers an exception; signing returns the signed transaction for broadcasting.
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting.
> **Legacy (not recommended):** [Legacy: multiSign via window.tronLink](#legacy-multisign-via-windowtronlink)
@@ -969,7 +1093,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
#### Parameter
@@ -990,11 +1120,7 @@ If signed successfully:
0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c
```
-If an error occurs:
-
-```typescript
-Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
### Interaction Flow
@@ -1139,7 +1265,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
#### Parameters
@@ -1366,12 +1495,27 @@ Retained for back-compat; new integrations should use `eth_requestAccounts`.
```json
{
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": { "type": "integer", "enum": [200, 4000, 4001] },
- "message": { "type": "string" }
- }
+ "oneOf": [
+ {
+ "const": ""
+ },
+ {
+ "type": "object",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [200, 4000, 4001]
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ ]
}
```
@@ -1397,15 +1541,22 @@ Therefore, the DApp must perform the **Connect Website** request first and wait
#### Code Example
```typescript
-const res = await tronWeb.request(
+const res: RequestAccountsResponse = await window.tronLink.request(
{
method: 'tron_requestAccounts',
params: {
websiteIcon: '',
websiteName: '',
- } as RequestAccountParams,
+ } as RequestAccountsParams,
}
);
+if (res === "") {
+ console.info("Unlock TronLink");
+} else if (res.code === 200) {
+ console.info("Connected");
+} else {
+ console.info(res.code, res.message);
+}
```
#### Parameters
@@ -1418,14 +1569,14 @@ interface RequestAccountsParams {
```
- **method:** fixed string `tron_requestAccounts`
-- **params:** `RequestAccountParams` type:
+- **params:** `RequestAccountsParams` type:
- `websiteIcon`: DApp website icon URI (displayed in connected site list)
- `websiteName`: DApp website name
#### Return Value
```typescript
-interface ReqestAccountsResponse {
+type RequestAccountsResponse = "" | {
code: 200 | 4000 | 4001,
message: string
}
@@ -1449,34 +1600,24 @@ if (window.tronLink.ready) {
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+ let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+ }
+ if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+ }
}
```
## Legacy: multiSign via window.tronLink
-```typescript
-if (window.tronLink.ready) {
- const tronweb = tronLink.tronWeb;
- const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
- const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
- const activePermissionId = 2;
-
- const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
- );
-
- try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
-}
-```
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting. For the legacy provider, obtain `tronweb` from `window.tronLink.tronWeb` once `window.tronLink.ready` is true.
## Legacy: signMessageV2 via window.tronLink
@@ -1488,7 +1629,13 @@ if (window.tronLink.ready) {
try {
const message = "Sign in to Example DApp\nNonce: 8f3a2c"; // plain UTF-8 text
const signedString = await tronweb.trx.signMessageV2(message);
- } catch (e) {}
+ } catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+ }
}
```
@@ -1500,42 +1647,48 @@ if (window.tronLink.ready) {
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc10',
options: { address: '1002000' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC20
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc20',
options: { address: 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC721
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc721',
options: { address: 'TVtaUnsgKXhTfqSFRnHCsSXzPiXmm53nZt' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
```
@@ -1548,7 +1701,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
---
@@ -1811,7 +1967,7 @@ window.tron.on('disconnect', (providerRpcError) => {
})
```
-> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message) or [rejectWeb (postMessage)](#user-rejected-connection-message)
+> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message)
---
@@ -2086,6 +2242,56 @@ Modified hash:
---
+
+
+# Extension Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-extension-core](https://github.com/TronLink/tronlink-extension-core)
+
+`@tronlink/core` is the JavaScript and TypeScript wallet library used by the TronLink extension. Embed it in a wallet application to derive TRON and EVM accounts and sign locally. For a DApp that asks the user’s installed extension to connect or sign, use the [extension provider](active-requests.en.md).
+
+## Installation
+
+Install the npm package. It includes CommonJS and ES module entry points and TypeScript declarations.
+
+```bash
+npm install @tronlink/core
+```
+
+See the upstream prerequisites for the required Node.js, pnpm (development) and TypeScript versions. Browser builds need polyfills for Node modules such as `buffer`, `crypto`, and `stream`. [Prerequisites](https://github.com/TronLink/tronlink-extension-core/blob/main/README.md#prerequisites) · [Upstream webpack configuration](https://github.com/TronLink/tronlink-extension-core/blob/main/webpack.config.js)
+
+## Derive a TRON address
+
+Generate a mnemonic, derive the first account’s first address path, then use the derived private key to obtain the address.
+
+```ts
+import { BaseWallet, TronWallet } from '@tronlink/core';
+
+const wallet = new TronWallet();
+const mnemonic = BaseWallet.generateRandomMnemonic();
+const path = wallet.derivePath({ accountIndex: 0, addressIndex: 0 });
+const privateKey = wallet.derivePrivateKey({ mnemonic, path });
+const address = wallet.getAddressBy({ privateKey });
+```
+
+For an EVM address, use `EvmWallet` and call its `derivePath` before deriving the key. [TRON and EVM account example](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/create_account.ts)
+
+## Signing
+
+Both wallet classes support transaction, message, and typed-data signing. For TRON, pass a prepared transaction to `wallet.signTransaction({ privateKey, data: rawTransaction })`. For an EVM transaction, supply the chain configuration and unsigned transaction in `data`. Signing returns the result locally. Broadcasting is a separate step. [TRON signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/tron_signature.ts) · [EVM signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/evm_signature.ts)
+
+## Ledger and usage statistics
+
+Ledger signing requires a browser that exposes `navigator.hid`. Use `LedgerTrxSigner` with the device’s TRX app and `LedgerEvmSigner` with its ETH app.
+
+Importing the package, deriving an address, or signing locally does not start a statistics upload. To send a report, the host calls `checkAndReportXY(deps)` and supplies the upload callback. The optional `userStatistics` module groups mainnet activity by day and amount range, using UUIDs assigned to addresses on the device. [Privacy and reporting details](https://github.com/TronLink/tronlink-extension-core/blob/main/PRIVACY.md)
+
+## Version & License
+
+For the current version, see the [package manifest](https://github.com/TronLink/tronlink-extension-core/blob/main/package.json). [Apache License 2.0](https://github.com/TronLink/tronlink-extension-core/blob/main/LICENSE)
+
+---
+
# MCP Server TronLink
@@ -2098,7 +2304,7 @@ Modified hash:
**Key Highlights:**
- Dual-mode architecture: **Playwright** (browser automation) + **Direct API** (on-chain operations)
-- 32 built-in Flow Recipes with pre-checks and dependency resolution
+- 24 built-in Flow Recipes with pre-checks and dependency resolution
- Non-custodial local transaction signing via encrypted `agent-wallet`
- Multi-signature management with real-time WebSocket monitoring
- Gas-free TRC20 transfers via GasFree service integration
@@ -2117,7 +2323,7 @@ flowchart TD
Multi["TronLinkMultiSigCapability (5 tools)"]
GasFree["TronLinkGasFreeCapability (3 tools)"]
Util["Utility Capabilities
Build · StateSnapshot · TRON Crypto"]
- Flow["Flow Recipes
(32 built-in, pre-checked)"]
+ Flow["Flow Recipes
(24 built-in, pre-checked)"]
Ext["TronGrid API / Multi-Sig Service / GasFree Service"]
Chain["TRON Blockchain"]
Agent -- "MCP Protocol — stdio / JSON-RPC 2.0" --> Server
@@ -2264,11 +2470,13 @@ Uses `@noble/curves` (secp256k1 ECDSA) and `@noble/hashes` (Keccak-256, SHA256).
---
-## Flow Recipes (32 Built-In)
+## Flow Recipes (24 Built-In)
Pre-configured multi-step workflows with dependency checks and parameter templates.
-### Playwright Flows
+Call `tl_list_flows` for the registry in the running server.
+
+### Playwright Flows (4)
| Flow | Description |
|------|-------------|
| `switchNetworkFlow` | Switch to Mainnet/Nile/Shasta |
@@ -2338,7 +2546,7 @@ Pre-configured multi-step workflows with dependency checks and parameter templat
| Variable | Description |
|----------|-------------|
-| `AGENT_WALLET_PASSWORD` | Encryption password (optional if using `tl_wallet_create`; required for manual or existing wallets) |
+| `AGENT_WALLET_PASSWORD` | Encryption password (supply for manually provisioned wallets; local auto-created wallets reuse their saved password) |
| `AGENT_WALLET_DIR` | Custom wallet storage directory |
| `TL_OWNER_WALLET_ID` | Owner wallet ID for multisig signing |
| `TL_COSIGNER_WALLET_ID` | Co-signer wallet ID for multisig |
@@ -2380,12 +2588,13 @@ Auto-detected by Claude Code:
}
```
-If no wallet exists yet, startup shows two paths:
+**Manual creation (recommended for production).** For a new wallet, run `agent-wallet start local_secure --generate --wallet-id main`. For this or an existing wallet, load its password into the launch environment of Claude Code (tested with 2.1.141) as `AGENT_WALLET_PASSWORD` using your secret manager. Add the following entry to the server’s `env` object. Claude Code expands the reference when starting the server. [Claude Code MCP](https://code.claude.com/docs/en/mcp#environment-variable-expansion-in-mcp-json)
-- Auto-create in the running MCP session: call `tl_wallet_create`
-- Manual setup: create the wallet locally with `agent-wallet start local_secure --generate --wallet-id main`, then set `AGENT_WALLET_PASSWORD` and restart
+```json
+{ "AGENT_WALLET_PASSWORD": "${AGENT_WALLET_PASSWORD}" }
+```
-If you choose auto-create, the server generates a random password, saves it to `~/.agent-wallet/runtime_secrets.json`, creates an encrypted `main` wallet, and continues with the current session.
+**Automatic creation (local development).** Leave the password entry out. With no wallet present, call `tl_wallet_create`. The server generates a random password and stores it in plaintext in `~/.agent-wallet/runtime_secrets.json` for reuse after restart. Restrict the file to its owner (`chmod 600`) and protect backups.
The following is a fuller Nile configuration. The router addresses are SunSwap's official Nile Routers ([V2](https://docs.sun.io/protocols/sunswap-v2/reference/contract/), [V3](https://docs.sun.io/protocols/sunswap-v3/reference/contract/)); do not copy Mainnet router addresses into a Nile configuration. `tl_chain_swap` (V2) executes the token path of the quote API's best route through the V2 router, so it fails when the route includes non-V2 pools (for example TRX→USDT on Nile). A Shasta URL selects the Mainnet defaults, so swaps do not work on Shasta:
@@ -2401,7 +2610,6 @@ The following is a fuller Nile configuration. The router addresses are SunSwap's
"TL_MODE": "prod",
"TL_HEADLESS": "false",
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2428,7 +2636,6 @@ If you only need direct API tools and do not need browser automation, you can ke
"cwd": ".",
"env": {
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2486,7 +2693,7 @@ mcp-server-tronlink/
│ │ ├── state-snapshot.ts # UI state extraction
│ │ └── tron-crypto.ts # Address derivation, signing, Base58
│ └── flows/
-│ ├── index.ts # Flow registry (32 recipes)
+│ ├── index.ts # Flow registry (24 recipes)
│ ├── switch-network.ts # Network switching flows
│ ├── transfer-trx.ts # Transfer flows
│ ├── multisig.ts # 6 multi-sig flows
@@ -2504,7 +2711,7 @@ mcp-server-tronlink/
## Dependencies
-Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
+Ranges from the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bumping major versions of the wallet, MCP, or crypto libraries.
| Package | Version | Purpose |
|---------|---------|---------|
@@ -2512,14 +2719,14 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
| `@noble/hashes` | ^2.0.1 | Keccak-256, SHA256 |
| `@tronlink/tronlink-mcp-core` | ^0.1.0 | Core MCP server framework |
| `playwright` | ^1.49.0 | Browser automation |
-| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`) — pinned, not `latest`, to keep wallet behavior reproducible |
+| `@bankofai/agent-wallet` | ^2.3.0 | Encrypted local wallet management (`local_secure`). The range allows versions from 2.3.0 up to, excluding, 3.0.0. Check the installed version with `npm ls @bankofai/agent-wallet`. |
| `ws` | ^8.18.0 | WebSocket (multi-sig monitoring) |
---
## Tool Contract & Side Effects
-**Input/output schemas and error contract.** Each tool's input/output schema and the structured error envelope are defined by the underlying framework — see [TronLink MCP Core](tronlink-mcp-core.md#error-codes) for the SSOT error code table (`code` / `retryable` / `hint` / triggered_by). Every response carries `meta.schemaVersion`; field meanings are stable within a major version. Agents should branch on `error.code` and `error.retryable`, never on the human-readable `message`.
+**Tool results and errors.** When the server uses Core 0.1.0, inspect `ok` in the Core response. On failure, use `error.code` to look up retry guidance in the [Core error-code table](tronlink-mcp-core.en.md#error-codes). The response includes `error.message` and may include `error.details`. For writes with an unknown outcome, check the transaction status before retrying.
**Per-tool input schemas are discoverable at runtime.** Every tool's parameters are Zod-validated in core and exposed as a JSON `inputSchema` via the MCP `list_tools` method, so a client can enumerate names, types, and required fields without reading this page. The tables below summarize tools by capability; `list_tools` is the authoritative, machine-readable source.
@@ -2536,7 +2743,7 @@ Pinned to the `package.json` of `mcp-server-tronlink@0.1.1`. Re-verify when bump
### Selected tool schemas (inline mirror)
-These are **docs-side mirrors** of the most critical tool inputs — useful when an agent is writing a tool-call call site without an MCP session open. Runtime `list_tools` remains the authoritative source: the schemas there carry full Zod metadata (descriptions, `default`, etc.) plus `meta.schemaVersion`. Fields below are derived from `@tronlink/tronlink-mcp-core` `src/mcp-server/schemas.ts` and follow JSON Schema Draft 7. The full set of 52 tool schemas is **not** reproduced here — see core for the SSOT.
+The following tables summarize selected tool inputs. Call `tools/list` on the installed server to read each tool’s `inputSchema`, including its parameter descriptions and defaults. The examples below use JSON Schema Draft 7.
> Docs CI checks the field names and required flags of every block below against upstream `schemas.ts`; if they ever disagree, `list_tools` wins.
@@ -2663,7 +2870,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
| Boundary | Guarantee | Agent / operator obligation |
|---|---|---|
-| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `code`, `retryable`) for branching. |
+| **Prompt injection** | Tool inputs are consumed verbatim as call arguments. The server never concatenates tool inputs into a prompt re-sent to an LLM. Strings retrieved from chain or third-party APIs (account memos, contract revert reasons, transaction notes) **may contain attacker-controlled text** — treat them as untrusted. | Do not let the agent auto-route Remote Write tools off prose returned from a read. Always require structured fields (`txId`, `error.code`) for branching. |
| **Outbound host allowlist (SSRF)** | The server only originates HTTPS to the three configured endpoints — `TL_TRONGRID_URL` (TronGrid; SunSwap router contracts are also called through its `triggersmartcontract` endpoint), `TL_MULTISIG_BASE_URL`, `TL_GASFREE_BASE_URL` — plus the built-in SunSwap quote API (`rot.endjgfsv.link` on Mainnet, `tnrouter.endjgfsv.link` on Nile; not configurable). Tools never accept user-supplied URLs that get fetched verbatim. | Pin these env vars to known hosts in production, and include the quote API host in any egress allowlist; do not let LLM input populate any `*_BASE_URL`. |
| **API key handling (token passthrough)** | `TL_TRONGRID_API_KEY`, `TL_MULTISIG_SECRET_KEY`, `TL_GASFREE_API_SECRET` are read from env at startup and used only on the outbound leg. They are **not** returned in any tool response, error `details`, or Knowledge Store record. The server does not accept Authorization headers from MCP clients and forward them upstream. | Audit env capture in your MCP host config (some hosts log env); store secrets in the host's secret manager, not in `.mcp.json` committed to git. |
| **Browser JS execution** | `tl_evaluate` runs arbitrary JavaScript in the controlled Playwright browser context. This is a **High-risk / Destructive** primitive — it can read DOM, click invisible elements, exfiltrate state, and bypass UI HITL. | Disable `tl_evaluate` from the MCP host's tool allowlist for any agent that does not strictly require it. Never expose it to a remote/multi-user MCP deployment. |
@@ -2675,7 +2882,7 @@ Reminder: `tl_evaluate` runs arbitrary JS in the controlled Playwright browser.
Swaps are **Remote Write** and execute against a public DEX router, so they are exposed to **price slippage** and **front-running / MEV** (e.g. sandwich attacks): the realized output can be worse than quoted if the pool moves between quote and execution.
-- **Always bound the trade with a minimum-output / slippage limit.** Inspect the `tl_chain_swap_v3` input schema via `list_tools` (the `SwapV3Params` shape) for the exact slippage / minimum-output field names — do **not** rely on an unstated default, and treat a missing or zero minimum-output as unsafe.
+- **Always set `slippage` explicitly.** `tl_chain_swap_v3` has no minimum-output input; the server derives the minimum output from `slippage` (a percentage, default 0.5). Do **not** rely on the default; confirm the tolerance with the user and check the field in the `list_tools` schema.
- **Quote immediately before executing.** Get a fresh quote/route (e.g. Skills `tron-swap` `swap-quote` / `swap-route`), pick a tolerance you accept, and pass it explicitly.
- **Check the router.** Set `TL_SUNSWAP_ROUTER` / `TL_SUNSWAP_V3_ROUTER` to the Routers listed for your network in SunSwap's official contract addresses (see Environment Variables); a stale or wrong router can route funds unexpectedly.
- **No auto-retry.** A failed/uncertain swap is a Remote Write — confirm on-chain before re-issuing (`TL_CHAIN_SWAP_FAILED` is not retryable).
@@ -2728,9 +2935,9 @@ Verify after restart with `list_tools` — `tl_evaluate` should not appear. The
The Direct-API path signs with a local encrypted wallet managed by `@bankofai/agent-wallet`. Two paths exist for unlocking it; pick deliberately.
-**Path A — Manual (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. The password lives only in process memory; nothing is written by this server.
+**Manual creation (recommended for production).** Create the wallet out-of-band, set `AGENT_WALLET_PASSWORD` via the MCP host's secret manager, and start the server. This path reads the supplied password from the environment.
-**Path B — Auto-create (convenience for local dev).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
+**Automatic creation (local development).** If no wallet exists at startup and the agent calls `tl_wallet_create`, the server:
1. Generates a random password.
2. Writes it in plaintext to `~/.agent-wallet/runtime_secrets.json` so a restart can reuse the wallet.
@@ -2739,7 +2946,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
| Aspect | Behavior |
|---|---|
| **File** | `~/.agent-wallet/runtime_secrets.json` (plaintext JSON containing the password) |
-| **Recommended permissions** | `chmod 600` — the file is created under the user's `$HOME`, but no umask hardening is enforced. Verify after first run. |
+| **Recommended permissions** | Version 0.1.1 requests mode `0600` when creating the file. Verify the permissions after startup. |
| **Git safety** | `~/.agent-wallet/` is outside any repo by default. If you point `AGENT_WALLET_DIR` inside a repo, add it to `.gitignore` explicitly. |
| **Knowledge Store redaction** | The Knowledge Store auto-redacts `password`, `mnemonic`, `private_key`, `seed` fields in tool inputs / outputs. It does **not** read or sanitize `runtime_secrets.json`. The file is independent of the Knowledge Store. |
| **Logs / stderr** | The auto-generated password is not logged. The file path may appear in startup output. |
@@ -2747,11 +2954,11 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
**Production guidance.**
-- Prefer Path A. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (Claude Desktop env, vault, etc.).
-- If you must use Path B (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
+- Prefer manual creation. Source `AGENT_WALLET_PASSWORD` from the host's secret manager (for example, a vault).
+- If you must use automatic creation (e.g., ephemeral CI), set `AGENT_WALLET_DIR` to a tmpfs path that is destroyed at job end.
- For any tool that moves real funds, prefer `mcp-tronlink-signer` (browser approval, no on-disk password) over Direct-API.
-**How to enforce Path A (doc-side, today).**
+**How to enforce manual creation (doc-side, today).**
1. Provision the wallet **before** the server boots. From a separate shell:
@@ -2760,7 +2967,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
# take note of the password you supply here — it is the only copy
```
-2. Inject the password via the MCP host's secret manager so it lands in the server's `env` at launch:
+2. For Claude Code, export the password from your secret manager into the client’s environment and reference it in the server configuration:
```jsonc
// .mcp.json — secret comes from host env, not from this file
@@ -2777,7 +2984,7 @@ The Direct-API path signs with a local encrypted wallet managed by `@bankofai/ag
3. **Do not let the agent call `tl_wallet_create`.** Disable it the same way as `tl_evaluate` above (Claude Code `permissions.deny`, Claude Desktop `disabledTools`, or client-side `list_tools` filtering on the name `tl_wallet_create`).
-4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms Path B did not run.
+4. Verify on first launch: `list_tools` should not include `tl_wallet_create`, and the absence of `~/.agent-wallet/runtime_secrets.json` confirms automatic creation did not run.
**Tracking issue (code-side).** A `--no-auto-create` / `AGENT_WALLET_DISABLE_AUTOCREATE=1` flag that makes the server fail-loud at startup when no wallet exists is the proper long-term fix; until that ships upstream, the doc-side enforcement above is the defense in depth.
@@ -2805,8 +3012,8 @@ npm install && npm run build
# TL_TRONGRID_URL=https://nile.trongrid.io
#
# 3. If no wallet exists, choose one path:
-# Option A: call tl_wallet_create after startup
-# Option B: create one locally, then set AGENT_WALLET_PASSWORD
+# Automatic creation (local development): call tl_wallet_create after startup
+# Manual creation (recommended for production): create one locally, then set AGENT_WALLET_PASSWORD
# 4. Use with Claude Code
# "Check my TRX balance"
@@ -2822,19 +3029,17 @@ npm install && npm run build
### Compatibility & migration policy
-- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, `error.code` values, or `meta.schemaVersion` semantics. Post-1.0: standard semver — major-only breaking changes.
+- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change tool names, input schemas, or `error.code` values. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- Tool names (`tl_chain_send`, `tl_chain_swap_v3`, `tl_multisig_*`, `tl_gasfree_*`, `tl_evaluate`, etc.)
- `error.code` enum (SSOT: [TronLink MCP Core — Error Codes](tronlink-mcp-core.md#error-codes))
- - `error.retryable` semantics
- - `meta.schemaVersion` major component
- Required env var names (`TL_TRONGRID_URL`, `TL_MULTISIG_SECRET_KEY`, `AGENT_WALLET_PASSWORD`, …)
- **Volatile contracts** (may change at any time):
- Prose `message` text, log line formats, stderr output
- Internal Knowledge Store keys (consumers should not parse them)
- Pre-check error detail strings (branch on `code`, not on `details.reason`)
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag exposed via `list_tools`; removal lands no earlier than the cycle after that.
-- **Verifying after upgrade.** Re-call `list_tools` and confirm the tool names + `inputSchema` you depend on are still present before resuming the workflow. Compare `meta.schemaVersion` against the value cached at session start.
+- **Deprecations.** [@tronlink/mcp-server-tronlink 0.1.1](https://www.npmjs.com/package/@tronlink/mcp-server-tronlink/v/0.1.1) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Verifying after upgrade.** Record the installed server and Core versions. Recheck tool names and `inputSchema` with `tools/list`, then verify your client handles both `ok: true` and `ok: false` for a read-only tool.
---
@@ -3199,7 +3404,7 @@ All tools use the `tl_` prefix. Organized into 13 categories:
## Standardized Response Format
-All tools return a consistent structure:
+In [Core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0), inspect `ok` to select `result` or `error`. On failure, read `error.code` and `error.message`. `error.details` is optional. Response metadata contains `timestamp`, `sessionId`, and `durationMs`.
```typescript
// Success
@@ -3208,7 +3413,7 @@ All tools return a consistent structure:
result: { /* tool-specific data */ },
meta: {
timestamp: "2026-03-09T10:15:23.456Z",
- sessionId: "tl-1741504523",
+ sessionId: "tl-1773051323",
durationMs: 234
}
}
@@ -3219,17 +3424,15 @@ All tools return a consistent structure:
error: {
code: "TL_CLICK_FAILED", // stable code — see table below
message: "Element not found",
- retryable: false, // explicit hint for agents
- hint: "Re-snapshot the page and retry with a fresh a11yRef.",
details: { /* optional */ }
},
- meta: { timestamp, sessionId, durationMs, schemaVersion: "1.0" }
+ meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1773051323", durationMs: 234 }
}
```
### Error Codes
-This is the single source of truth (SSOT) for error codes returned by every tool in this framework. Downstream servers built on this framework (`mcp-server-tronlink`) inherit these codes and may extend them; `mcp-tronlink-signer` is a separate server and does not use them. `retryable` reflects framework-level safety; an agent **must** still apply the side-effect classification of the calling tool — never auto-retry a Remote Write whose outcome is unknown, regardless of `retryable`.
+This table is the single source of truth for Core error codes and their retry semantics. Look up `error.code` in the table below for retry guidance and recovery steps. **Retryable** and **Hint** are documentation columns. Core 0.1.0 omits `error.retryable`, `error.hint`, and `meta.schemaVersion` from the response. For a Remote Write with an unknown outcome, verify the transaction before considering another attempt. Downstream servers such as `mcp-server-tronlink` can extend this table. The independent `mcp-tronlink-signer` server uses its own errors.
| Code | Retryable | Hint | Typical trigger |
|------|:---:|------|-----------------|
@@ -3245,8 +3448,8 @@ This is the single source of truth (SSOT) for error codes returned by every tool
| `TL_WAIT_TIMEOUT` | true | Increase the timeout or wait on a different selector. | `tl_wait_for`, `tl_wait_for_notification` |
| `TL_SCREENSHOT_FAILED` | true | Transient; retry. | `tl_screenshot`, `tl_describe_screen` |
| `TL_CAPABILITY_NOT_AVAILABLE` | false | The session was launched without this capability; reconfigure and relaunch. | Any tool that requires an optional capability |
-| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. | `tl_chain_get_*` |
-| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake`, `tl_chain_resource` |
+| `TL_CHAIN_QUERY_FAILED` | true | TronGrid transient or rate-limited; back off and retry. **Exception:** `tl_chain_resource` also returns this code when a delegate/undelegate write fails, so treat it as `TL_CHAIN_SEND_FAILED` and check the transaction before re-issuing. | `tl_chain_get_*`, `tl_chain_resource` |
+| `TL_CHAIN_SEND_FAILED` | false | Do **not** auto-retry. Verify on-chain state with `tl_chain_get_tx` before re-issuing. | `tl_chain_send`, `tl_chain_stake` |
| `TL_CHAIN_SWAP_FAILED` | false | Same as send — confirm the previous tx did not land before retrying. | `tl_chain_swap`, `tl_chain_swap_v3` |
| `TL_GASFREE_QUERY_FAILED` | true | Transient; retry. | `tl_gasfree_get_account`, `tl_gasfree_get_transactions` |
| `TL_GASFREE_SEND_FAILED` | false | Do **not** auto-retry; query the GasFree service for the latest status. | `tl_gasfree_send` |
@@ -3258,7 +3461,7 @@ This is the single source of truth (SSOT) for error codes returned by every tool
Custom codes added by downstream servers must follow these rules:
- Never reuse a code listed above with a different meaning.
-- `retryable` is required for every new code.
+- Document the retry policy and recovery step for each new code.
- Meaning is stable within a major version.
- New codes are documented in the consuming server's docs, not silently introduced.
@@ -3482,19 +3685,19 @@ npm run clean # Remove dist/
### Compatibility & migration policy
-This package is **the SSOT** for tool schemas, error codes, and `meta.schemaVersion` consumed by `mcp-server-tronlink` and any downstream MCP server built on this core. The compatibility surface is therefore wider than a typical library:
+This package defines the tool schemas, error codes, and response envelope used by `mcp-server-tronlink` and other servers built on Core.
- **Semver.** Pre-1.0: a **minor** bump may change the `ISessionManager` interface, capability shapes, or `Tool[]` registration order; a **patch** will not. Post-1.0: standard semver — major-only breaking changes.
- **Stable contracts** (won't change in a patch):
- - The `error.code` enum (the SSOT exported as `ERROR_CODES`) — adding a new code is non-breaking; renaming or removing one is breaking.
- - The `{ ok, result/error, meta }` response envelope and `meta.schemaVersion` major component.
+ - The `error.code` enum (the SSOT exported as `ErrorCodes`) — adding a new code is non-breaking; renaming or removing one is breaking.
+ - The `{ ok, result/error, meta }` response envelope.
- Tool names and the **shape** of each tool's `inputSchema` (adding optional fields is non-breaking; renaming or making a field required is breaking).
- The 9 capability interfaces (`OnChainCapability`, `MultiSigCapability`, …) — adding an optional method is non-breaking.
- **Volatile contracts** (may change at any time):
- Internal helper exports under `src/internal/*`, `Knowledge Store` keys, recipe-runner internals.
- Pre-check error `details` strings (branch on `code`, not `details.reason`).
-- **Deprecation window.** A deprecated tool / field / capability method stays present for at least one minor cycle alongside its replacement, marked with `meta.deprecated` in `list_tools` output; removal lands no earlier than the cycle after.
-- **Adopting downstream.** Bump the `@tronlink/tronlink-mcp-core` peer / dependency only after re-running your downstream's `list_tools` snapshot test against the new core; assert `meta.schemaVersion` major matches the version your harness was written for.
+- **Deprecations.** [@tronlink/tronlink-mcp-core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
+- **Upgrading Core.** Record the installed package version. Compare `tools/list` against the tool names and input schemas your client uses, then check that the client handles a successful result and an error from a read-only tool.
---
@@ -3506,13 +3709,13 @@ This package is **the SSOT** for tool schemas, error codes, and `meta.schemaVers
**GitHub**: [https://github.com/TronLink/tronlink-skills](https://github.com/TronLink/tronlink-skills)
-> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `7d2d58cb`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.1**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
+> **Version scope.** The command reference on this page (6 skills, 33 commands) was written for **v1.0.x**. The default branch — what `git clone` and `install.sh` install — is now **v1.1.0** (commit `b12b5868`): it adds 7 read-only commands (40 in total) and requires exactly **Node.js 24.22.3**. See [Version & License](#version-license); treat `tron_api.mjs --help` / MCP `tools/list` from your installed copy as authoritative.
**TronLink Wallet Skills** is an AI Agent skill set that provides complete TRON blockchain wallet and DeFi functionality through natural language. Designed for Claude Code, Cursor, OpenCode, Codex CLI, and other AI agents.
**Key Highlights:**
- **6 skills, 33 commands** covering wallet, token research, market data, swaps, resources, and staking
-- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.1 — see [Dependencies](#dependencies)), no `npm install` needed
+- **Zero npm dependencies** — uses native Node.js `fetch` and `crypto` (requires exactly Node.js 24.22.3 — see [Dependencies](#dependencies)), no `npm install` needed
- **TRON-specific domain knowledge** — dedicated handling of Energy + Bandwidth resource model
- **Multi-platform support** — Claude Code, Cursor, OpenCode, Codex CLI, LangChain/CrewAI
- **Read-only & safe** — all commands are query-only, no private keys or signing involved
@@ -3543,7 +3746,7 @@ Natural Language Input
AI Agent (Claude Code / Cursor / OpenCode / Custom)
|
v
-tron_api.mjs (Node.js 24.22.1, native fetch, zero dependencies)
+tron_api.mjs (Node.js 24.22.3, native fetch, zero dependencies)
├── Zero npm dependencies
├── TronGrid HTTP API (public or with API key)
└── Tronscan API for token metadata
@@ -3571,7 +3774,7 @@ Wallet queries and account information.
**Features:** Handles both Base58Check (T...) and hex address formats, supports known token symbols, auto-converts decimals.
-**When NOT to use:** Sending TRX/tokens — these are read-only; use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md). For deep token-level analytics (rug-pull / liquidity locks), prefer `tron-token`.
+**When NOT to use:** To transfer TRX or TRC-20 tokens with browser approval, use [Signer SDK](tronlink-signer.en.md) `sendTrx` or `sendTrc20`. For a local agent wallet, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_send`. Use `tron-token` for token risk and liquidity analysis.
### 2. tron-token (7 commands)
@@ -3622,7 +3825,7 @@ DEX swap quotes and route optimization.
**Features:** Aggregates liquidity from multiple sources, estimates Energy cost, handles multi-hop routes.
-**When NOT to use:** Executing the swap — quotes are read-only; the swap itself goes through [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_swap_v3`) or the signer SDK. Historical trade data — `tron-market`.
+**When NOT to use:** To execute a swap, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and a user-approved `slippage`. Use `tron-market` for historical trade data.
### 5. tron-resource (6 commands)
@@ -3639,7 +3842,7 @@ Energy & Bandwidth management — TRON-specific.
**Features:** Decision tree logic for cost optimization, tracks daily free bandwidth, calculates TRX burn equivalent.
-**When NOT to use:** Actually freezing TRX to acquire Energy/Bandwidth — that's a Remote Write; use the signer SDK / MCP Server. SR voting strategy after freezing — see `tron-staking`.
+**When NOT to use:** To freeze TRX for Energy or Bandwidth, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` with `action="freeze"`. Use `tron-staking` to research SRs before voting.
### 6. tron-staking (3 commands)
@@ -3653,13 +3856,13 @@ Stake 2.0 queries and SR information.
**Features:** Stake 2.0 status queries, APY calculation, SR commission tracking.
-**When NOT to use:** Performing the freeze/vote/unfreeze actions — those are Remote Writes; route through the signer SDK / MCP Server. Calculating Energy cost per operation — `tron-resource`.
+**When NOT to use:** Cast votes with [TronLink CLI](tronlink-cli.en.md) `tronlink vote` and claim voting rewards with `tronlink reward`. To freeze or unfreeze TRX, use [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake`. Use `tron-resource` for energy estimates.
---
## Skill ↔ MCP Tool Map
-`scripts/mcp_server.mjs` (the wrapper from [Method 2](#method-2-mcp-server)) exposes **25 of the 33 commands** as MCP tools — every signature, every input field, every output shape is generated from the same `tron_api.mjs` implementation, so the CLI and the MCP tool are guaranteed equivalent. The 8 CLI-only commands stay reachable through Method 1 (skill prompt) and Method 3 (direct CLI). Use this table when an agent needs to route a user request to a specific tool or when you're inspecting `tools/list` output.
+In the v1.0.x command set, `scripts/mcp_server.mjs` exposes **25 of 33 CLI commands** as MCP tools. At the default-branch commit `b12b5868`, it exposes 39 of 40 commands; only `swap-route` is CLI-only, so the “CLI-only” markers below apply to v1.0.x. The wrapper runs the corresponding CLI command and returns text in an MCP tool result. The remaining eight commands are available through the Skills or the CLI.
| Skill | CLI command | MCP tool name | Side effect | Retryable |
|---|---|---|---|:---:|
@@ -3697,7 +3900,7 @@ Stake 2.0 queries and SR information.
| `tron-staking` | `staking-info` | `tron_staking_info` | Network Read | Yes |
| `tron-staking` | `staking-apy` | `tron_staking_apy` | Network Read | Yes |
-**Totals.** 33 CLI commands · 25 MCP tools · 8 CLI-only commands. Every command is read-only — no signing, no broadcast, no fund movement. To execute a transaction, route to [MCP Server TronLink](mcp-server-tronlink.md) (`tl_chain_*`) or [signer SDK](tronlink-signer.md) (`sendTrx`, `sendTrc20`, `sign*`).
+The v1.0.x table covers 33 read-only CLI commands, including 25 available over MCP. Use the routing examples below for transactions.
### Intent → Skill → Tool Routing
@@ -3731,16 +3934,16 @@ If the request implies **changing on-chain state** (transfer, swap execution, fr
### ❌ When NOT to route here (negative examples)
-Skills are **read-only**. If the user intent implies a signed / Remote Write action, do **not** dispatch to a skill — the underlying command will succeed but only as a query/estimate, and the user's actual goal will go unfulfilled. Route to the signer SDK or `mcp-server-tronlink` instead:
+Use Skills for queries and estimates. For actions that sign or broadcast, choose the route below. The [TronLink CLI](tronlink-cli.en.md) and signer SDK use browser approval. MCP Server direct chain tools sign with the local agent wallet, so the host must obtain confirmation before the call.
| User says (intent) | ❌ Wrong route (looks plausible, but read-only) | ✅ Correct route |
|---|---|---|
-| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.md) `tl_chain_send` |
-| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | `mcp-server-tronlink` `tl_chain_stake` (Remote Write, HITL) |
-| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | `mcp-server-tronlink` `tl_chain_stake` / signer SDK `signTransaction` |
-| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [signer SDK](tronlink-signer.md) `signTransaction` or `mcp-server-tronlink` `tl_chain_send` |
-| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | `mcp-server-tronlink` `tl_chain_swap_v3` (Remote Write, HITL, set `minOut`) |
-| "Claim my staking rewards" | `tron-staking staking-info` — only shows the pending balance. | `mcp-server-tronlink` `tl_chain_stake` (withdraw / claim) or signer SDK |
+| "Send 100 TRX to `T…`" | `tron-wallet wallet-balance` then stop — this only checks the balance, never sends. | [signer SDK](tronlink-signer.en.md) `sendTrx` (HITL) or [`mcp-server-tronlink`](mcp-server-tronlink.en.md) `tl_chain_send` |
+| "Freeze 1000 TRX to get Energy" | `tron-resource optimize-cost` — this only computes the recommendation. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_stake` (`action="freeze"`, `amount_trx=1000`, `resource="ENERGY"`) |
+| "Vote 5000 votes for SR `T…`" | `tron-staking sr-list` — only reads the SR list, no vote is cast. | [TronLink CLI](tronlink-cli.en.md) `tronlink vote --votes :5000`. A vote replaces all of the account’s current votes; to keep votes for other SRs, list them in the same command. |
+| "Approve USDT spending for the SunSwap router" | `tron-token token-info` / `contract-info` — pure metadata, no approval is broadcast. | [TronLink CLI](tronlink-cli.en.md) `tronlink trigger --contract --method 'approve(address,uint256)' --args '["","1000000"]'`. Use the token and router on the selected network. The router is the spender. For 6-decimal USDT, `1000000` authorizes 1 USDT. |
+| "Swap 100 TRX for USDT now" | `tron-swap swap-quote` — only quotes price, never executes. | [mcp-server-tronlink](mcp-server-tronlink.en.md) `tl_chain_swap_v3` with `action="execute"` and an explicitly approved `slippage` (%) |
+| "Claim my voting rewards" | `tron-staking staking-info` — only shows the pending balance. | [TronLink CLI](tronlink-cli.en.md) `tronlink reward` |
**Heuristic.** If the user's verb is *send / freeze / unfreeze / vote / unvote / approve / swap (execute) / claim / sign / broadcast*, the answer never starts in this Skills set. Skills can still **precede** the write (quote, estimate cost, validate address, check balance) — just don't claim a Skills call finished the user's request.
@@ -3794,8 +3997,8 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
- Freeze TRX → Get Energy or Bandwidth → Vote for SR → Earn rewards
- Unfreezing has **14-day wait** before withdrawal
- Votes reset if you unfreeze; must re-vote after re-freezing
-- 1 frozen TRX ≈ 4.5 Energy/day — **dynamic**: depends on total network stake; use `tron-resource estimate-energy` for the live value. Effective figure as of 2026-05.
-- Voting rewards claimable every 6 hours
+- Energy obtained by staking depends on the network’s current stake. Estimate the quota per TRX from `TotalEnergyLimit / TotalEnergyWeight` on the target network. `estimate-energy` estimates a contract call’s consumption. [GetAccountResource](https://developers.tron.network/reference/getaccountresource)
+- Voting rewards can be claimed once every 24 hours
---
@@ -3805,8 +4008,11 @@ tron-resource (check status) → tron-resource (estimate cost) → tron-resource
```bash
# Clone and use directly
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
claude # Auto-discovers SKILL.md files
```
@@ -3818,8 +4024,8 @@ No `npm install` needed for read-only operations.
# Register as MCP server
claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
-# Provides 25 MCP tools callable by Claude Desktop / Claude Code
-# (see "Skill ↔ MCP Tool Map" above for the per-command mapping; 8 commands are CLI-only)
+# Provides 39 MCP tools at b12b5868 (25 in v1.0.x), callable by Claude Desktop / Claude Code
+# (only swap-route is CLI-only at b12b5868; see "Skill ↔ MCP Tool Map" above for the v1.0.x mapping)
```
### Method 3: Manual CLI
@@ -3827,10 +4033,16 @@ claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
```bash
# Direct command execution
node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs swap-quote --from TRX --to USDT --amount 100
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs swap-quote --from-token TRX --to-token USDT --amount 100
```
+#### Handling Skills CLI and MCP errors
+
+In Skills v1.1.0 (`b12b5868`), an unknown CLI command or a missing required option exits with `1` and writes a diagnostic to stderr. A command can also exit with `0` and return an error in stdout. For example, `staking-apy --amount 0` returns JSON with `error`, `status: 400`, and `parameter: "amount"`. For a data query, check the exit status first, then parse stdout and check for `error` before using the result. [Skills CLI implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/tron_api.mjs)
+
+For MCP `tools/call`, check for a JSON-RPC error first (an unknown tool returns `-32602`). For a recognized tool, parse the JSON in `result.content[0].text` and check its `error` field. The wrapper can return command failures in this text with no `isError` flag. [Skills MCP implementation](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/mcp_server.mjs)
+
### Method 4: Other AI Platforms
| Platform | Integration |
@@ -3887,7 +4099,10 @@ def tron_call(cmd: str) -> dict:
["node", "scripts/tron_api.mjs", *cmd.split()],
cwd="/absolute/path/to/tronlink-skills",
)
- return json.loads(out)
+ result = json.loads(out)
+ if isinstance(result, dict) and "error" in result:
+ raise RuntimeError(result["error"])
+ return result
tron_wallet_balance = Tool.from_function(
func=lambda addr: tron_call(f"wallet-balance --address {addr}"),
@@ -3985,7 +4200,7 @@ tronlink-skills/
| Dependency | Required? | Purpose |
|------------|-----------|---------|
-| Node.js 24.22.1 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.1 && nvm use 24.22.1` before installing. |
+| Node.js 24.22.3 (exact; default branch v1.1.0) | Yes | Runtime (native fetch, crypto). Pinned by `.nvmrc` and `package.json` `engines` on the default branch; `install.sh` exits with an error on any other version. Run `nvm install 24.22.3 && nvm use 24.22.3` before installing. |
| npm install | Not needed | All operations work without any npm dependencies |
---
@@ -3998,7 +4213,7 @@ tronlink-skills/
| Side effects | Every command is **Network Read**: it calls public APIs but changes no state. All commands are safe to retry; no human-in-the-loop confirmation is needed |
| No secrets required | Only optional TRONGRID_API_KEY for higher rate limits |
| Rate limits | Public TronGrid API; use TRONGRID_API_KEY for higher limits |
-| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). To execute a transaction (transfer, swap, stake), use the [signer SDK](tronlink-signer.md) or [MCP Server TronLink](mcp-server-tronlink.md) — these skills never sign or broadcast |
+| Error handling | Failures are query errors: rate limit (retryable, back off), network errors (retryable), invalid address/parameters (not retryable — fix the input). |
---
@@ -4029,28 +4244,31 @@ Both formats are supported and auto-normalized across all commands:
```bash
# 1. Clone
-git clone
+# v1.1.0 requires Git, nvm, Node.js 24.22.3 and (for the interactive steps) Claude Code.
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
# 2. Use with Claude Code (no install needed for reads)
claude
-> "What's the TRX balance of TAddress...?"
-> "Show me the top trending tokens on TRON"
-> "How much Energy do I need to send USDT?"
-> "What's the best way to get Energy — freeze, rent, or burn?"
+# "What's the TRX balance of TAddress...?"
+# "Show me the top trending tokens on TRON"
+# "How much Energy do I need to send USDT?"
+# "What's the best way to get Energy — freeze, rent, or burn?"
-# 3. Or use directly
-node scripts/tron_api.mjs wallet-balance --address TAddress...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs optimize-cost --address TAddress...
+# 3. Alternatively, run these in the shell. Set ACCOUNT to the address to query.
+node scripts/tron_api.mjs wallet-balance --address "${ACCOUNT:?set ACCOUNT}"
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs optimize-cost --address "${ACCOUNT:?set ACCOUNT}"
```
## Version & License
- **Package:** `tronlink-skills` v1.0.1 — the version the command tables on this page describe.
-- **Default branch:** v1.1.0 (commit `7d2d58cb`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
- - 7 additional read-only commands, also exposed as `tron_` MCP tools: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
- - Node.js is pinned to exactly 24.22.1 (`.nvmrc`, `engines`); `install.sh` exits on any other version.
+- **Default branch:** v1.1.0 (commit `b12b5868`, `package.json` `version: 1.1.0`), installed by `git clone` / `install.sh`. Differences from v1.0.1 that affect agents:
+ - 7 additional read-only commands, also exposed as `tron_` MCP tools. At this commit `mcp_server.mjs` exposes 39 of the 40 commands; only `swap-route` is CLI-only. The new commands: `wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`. 40 commands in total; all remain Network Read.
+ - For this commit, [`.nvmrc`](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/.nvmrc) specifies Node.js 24.22.3. To reproduce [commit `7d2d58cb`](https://github.com/TronLink/tronlink-skills/blob/7d2d58cb/.nvmrc), use Node.js 24.22.1. Run `nvm install && nvm use` in the checked-out repository to select its pinned version.
- **License:** MIT — `SPDX-License-Identifier: MIT`
- **Changelog / releases:** [https://github.com/TronLink/tronlink-skills/releases](https://github.com/TronLink/tronlink-skills/releases) — no GitHub-tagged releases yet for v1.0.x; track changes by commit until the first tag.
@@ -4061,13 +4279,12 @@ Skills are at **v1.0.x**, so standard semver applies — only **major** bumps ma
- **Stable contracts** (won't change in a minor or patch):
- The 33 CLI command names and their required / optional flags (`tron_api.mjs [...]`).
- The 25 MCP tool names listed in [Skill ↔ MCP Tool Map](#skill-mcp-tool-map) (`tron_*` form) and their `inputSchema` keys.
- - Exit codes: `0` success, `1` query error / invalid input, `2` unsupported / unknown command.
- The `Network Read` side-effect classification — no command will ever become a Remote Write without a major bump.
- **Volatile contracts** (may change in a minor):
- The exact field layout of JSON `stdout` payloads — new fields can be added in any minor; renames or removals are major. Use a tolerant parser.
- Built-in token-symbol shortcut list (`USDT`, `USDC`, `WTRX`, …) — symbols may be added in any minor; existing mappings won't be repointed in a minor.
- Heuristics and thresholds (`whale-transfers` default cutoff, `optimize-cost` decision tree weights, etc.).
-- **Subset relationship.** The MCP tool subset (currently 25 of 33) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
+- **Subset relationship.** The MCP tool subset (25 of 33 in v1.0.x; 39 of 40 at `b12b5868`) may **grow** in a minor (a previously CLI-only command exposed as an MCP tool); it will not **shrink** in a minor.
- **Deprecation window.** A command / tool marked deprecated continues to work for at least one minor cycle. Removal lands no earlier than the next major.
- **Verifying after upgrade.** Re-run `tron_api.mjs --help` and (if using MCP) `tools/list` to confirm the names you depend on are still present. The MCP `serverInfo.version` exposed during `initialize` should match the bumped `package.json` version.
@@ -4224,7 +4441,7 @@ In v0.1.4, errors are returned as an MCP tool result with `isError: true` and a
|---|---|---|
| **Prompt injection** | Tool inputs are consumed verbatim as call arguments; the server does not re-prompt an LLM with them. The TronLink approval page renders parsed transaction fields, not the agent's free-text. | Treat any on-chain string returned (memos, revert reasons) as untrusted; branch on `txId` / `status`, not on prose. |
| **Local HTTP listener** | The local approval server **binds to `127.0.0.1` only** (port `TRON_HTTP_PORT`, default 3386, auto-increments on conflict). It never accepts off-host connections. Each server session has a unique ID; old browser tabs from previous sessions are invalidated automatically. | Do not port-forward 3386 over a network. Do not run two copies of this server with the same `TRON_HTTP_PORT` on a shared box. |
-| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [Networks](#environment-variables) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
+| **Outbound host allowlist (SSRF)** | The signer only talks to TronGrid endpoints listed in [network endpoints](../reference/networks.md#networks) and to the local browser. Tools do not accept user-supplied URLs that get fetched. | Pin `TRON_NETWORK` and (optionally) `TRON_API_KEY` to known values in production. |
| **API key handling (token passthrough)** | `TRON_API_KEY` is read from env at startup and used only on the outbound leg to TronGrid. It is **not** returned in any tool response, error `details`, or MCP resource. The server does not accept Authorization headers from MCP clients and forward them upstream. | Store the key in the MCP host's secret manager, not in plain `mcpServers` config committed to git. |
| **HITL is mandatory for signing** | Every signing tool (`send_trx`, `send_trc20`, `sign_message`, `sign_typed_data`, `sign_transaction`) opens the TronLink approval page. **There is no programmatic bypass.** Private keys never leave TronLink. | Operators do not need to enforce HITL — it is structural. Do not attempt to harden by removing the browser layer. |
| **Browser tab hijacking** | The approval page authenticates each request against the server session ID and ignores stale tabs. Heartbeat detection closes the session on browser disconnect. | If the same user runs multiple agents, ensure each spawns its own signer instance; cross-instance request mixing is prevented by session ID, but UI confusion is not. |
@@ -4278,7 +4495,7 @@ Co-released with `tronlink-signer@0.1.2`. **Major UX overhaul** on the approval
### Compatibility & migration policy
- **Semver.** Pre-1.0: a **minor** bump (0.x → 0.y) may introduce breaking changes; a **patch** bump (0.1.x → 0.1.y) will not change MCP tool names or input schemas. Post-1.0: standard semver — major-only breaking changes.
-- **Deprecation window.** When a tool or input field is deprecated, the next minor release retains the old form alongside the new one for at least one minor cycle, with a `meta.deprecated` flag in the schema; removal lands no earlier than the cycle after that.
+- **Deprecations.** [mcp-tronlink-signer 0.1.4](https://www.npmjs.com/package/mcp-tronlink-signer/v/0.1.4) exposes no deprecation flag for its registered tools. Before upgrading, review the target release notes and compare the tool names and input fields returned by `tools/list`.
- **Stable contracts.** Tool names and `status` values (`success` / `pending` / `failed`) are part of the public surface — they don't change in a patch.
- **Volatile contracts.** Error `message` text (match the known values under [Errors](#errors) and treat others as unknown), log line formats, and the layout of the browser approval page are **not** part of the public surface and may change at any time.
- **Verifying after upgrade.** Re-call `list_tools` and confirm the names + schemas you depend on are still present before resuming a workflow.
@@ -4301,18 +4518,26 @@ npm install tronlink-signer
## Quick Start
+On Nile, select a funded test account and set the Node.js environment variable `RECIPIENT` to your test recipient’s address. This example requests approval to send 1 test TRX.
+
```ts
import { TronSigner } from "tronlink-signer";
+const recipient = process.env.RECIPIENT;
+if (!recipient) throw new Error("Set RECIPIENT to the Nile recipient address");
const signer = new TronSigner();
await signer.start();
-const { address, network } = await signer.connectWallet();
-const { txId, status } = await signer.sendTrx("TXxx...", 1); // status: "success" | "pending" | "failed"
-const { txId: txId2, status: s2 } = await signer.signTransaction(tx, "nile", true); // broadcast + auto-confirm
-const { balance } = await signer.getBalance("TXxx...");
-
-await signer.stop();
+try {
+ const { address } = await signer.connectWallet("nile");
+ const { balance } = await signer.getBalance(address, "nile");
+ console.log(address, balance);
+ // Signer takes TRX, so this sends 1 TRX.
+ const { txId, status } = await signer.sendTrx(recipient, 1, "nile");
+ console.log(txId, status);
+} finally {
+ await signer.stop();
+}
```
## API
@@ -4391,25 +4616,51 @@ Signs a raw transaction. When `broadcast` is `true`, the signed transaction is b
| `broadcast` | `boolean` | Whether to broadcast after signing (default: `false`) |
| `options` | `SignerOptions` | Optional — cancellation, confirmation control, broadcast callback |
-```ts
+To build an unsigned Nile transfer in Node.js, install `tronlink-signer` and `tronweb@6`. Select the funded Nile payer in TronLink and set `RECIPIENT` to the intended Nile recipient address. Run this setup followed by one calling pattern in the same ES module.
+
+```js
+import { TronSigner } from "tronlink-signer";
+import { TronWeb } from "tronweb";
+
+const signer = new TronSigner();
+const tronWeb = new TronWeb({ fullHost: "https://nile.trongrid.io" });
+const recipient = process.env.RECIPIENT;
+if (!TronWeb.isAddress(recipient)) throw new Error("Set RECIPIENT to a TRON address");
+await signer.start();
+const { address } = await signer.connectWallet("nile");
+// The builder takes SUN, so this creates a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronWeb.transactionBuilder.sendTrx(recipient, 10, address);
+```
+
+Choose one of the following calling patterns.
+
+```js
// Sign only
-const { signedTransaction } = await signer.signTransaction(tx);
+const { signedTransaction } = await signer.signTransaction(tx, "nile");
+```
+```js
// Sign, broadcast, and wait for confirmation (default)
const { signedTransaction, txId, status, error } = await signer.signTransaction(tx, "nile", true);
// status === "success" — confirmed on-chain
// status === "pending" — broadcast succeeded but not confirmed within timeout
// status === "failed" — on-chain execution failed; `error` carries the reason
+```
+```js
// Broadcast without waiting for confirmation
const result = await signer.signTransaction(tx, "nile", true, { confirm: false });
+```
+```js
// Get notified as soon as the tx enters the mempool
const result = await signer.signTransaction(tx, "nile", true, {
onBroadcasted: ({ txId }) => console.log("Broadcast:", txId),
});
```
+Wrap connection, construction and the selected call in `try / finally`, and call `await signer.stop()` in `finally` as in Quick Start. If a broadcast outcome is unknown, look up the transaction ID before taking further action.
+
### Broadcast Result
Broadcasting methods (`sendTrx`, `sendTrc20`, and `signTransaction` with `broadcast: true`) return a `BroadcastResult`:
@@ -4944,7 +5195,10 @@ In `--json` mode, v1.0.1 writes failures to **stderr** and exits with `1`:
2. For read operations with `--address`: queries TronGrid directly
3. For write/read without `--address`: connects to the TronLink browser extension for wallet info
4. Builds unsigned transaction using local TronWeb `transactionBuilder`
-5. Pre-flight check: runs on all write commands (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+5. Pre-flight check: depends on the command (transfer, stake, unstake, delegate, reclaim, vote, trigger). Verifies TRX / token / staked / delegated balances, simulates contract calls to catch reverts, estimates energy & bandwidth burn, validates SR addresses (vote), NFT ownership (TRC721), and delegation unlock times (reclaim) before signing
+
+ In v1.0.1, `withdraw` queries the payer’s `unfrozenV2` entries and errors before signing if no matured TRX is available. `reward` calls `getReward(address)` and returns without signing if the amount is zero or less (JSON status `No Rewards`). A failed lookup stops either command before signing.
+
6. Sends transaction to TronLink for signing (browser approval page)
7. Broadcasts: signer broadcasts by default, or CLI broadcasts locally with `--local-broadcast`. In both modes the CLI polls `getUnconfirmedTransactionInfo` until the tx is packed into a block (~3s), and surfaces OUT_OF_ENERGY / REVERT / FAILED as errors
8. Outputs result
@@ -5048,11 +5302,15 @@ tronlink reward --json
### Example: AI Transfer Flow
```bash
-# 1. Check balance first
-tronlink balance --address TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL --network mainnet --json
+# Set PAYER to the address selected in TronLink and RECIPIENT to the destination.
+# If the wallet account or network changes, cancel and check the new balance first.
+NETWORK=mainnet
+
+# 1. Check the payer's balance
+tronlink balance --address "${PAYER:?set PAYER}" --network "$NETWORK" --json
# 2. Send 10 TRX (opens browser for signing, wait for return)
-tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network mainnet --json
+tronlink transfer --type trx --toAddress "${RECIPIENT:?set RECIPIENT}" --amount 10 --network "$NETWORK" --json
# 3. Verify result — output includes txId and explorer URL
# { "Status": "Success", "TxID": "abc...", "Explorer": "https://tronscan.org/#/transaction/abc..." }
@@ -5162,48 +5420,124 @@ For this section, you may refer to [General Transfer](transfer.en.md)
## Query active permissions
-`multiSign` requires a valid `permissionId` for an **active** permission on the signing account. Active permissions are returned by `tronWeb.trx.getAccount(address)` under the `active_permission[]` field; each entry exposes `id`, `permission_name`, `threshold`, and the `keys[]` array (address + weight). Owner permissions have a fixed `id` of `0` and are exposed under `owner_permission` separately.
+Choose the account that holds the funds. If the connected signer owns the funds, use its address. For a co-signer, enter the controlled account’s address. Read that owner’s permissions on the transaction network and select an entry whose keys include the signer and whose operations allow TRX transfers. Use its actual `id`.
```javascript
const tronweb = window.tron.tronWeb;
-const account = await tronweb.trx.getAccount(tronweb.defaultAddress.base58);
-// account.active_permission is the array — pick the id whose keys[] includes
-// the address you intend to sign with, and whose weight + threshold allow the tx.
-const activePermissions = account.active_permission ?? [];
-console.log(activePermissions.map(p => ({ id: p.id, name: p.permission_name, threshold: p.threshold })));
+const owner = "REPLACE_WITH_OWNER_ADDRESS";
+const account = await tronweb.trx.getAccount(owner);
+console.table(account.active_permission);
```
-Use the resulting `id` as `permissionId` below.
-
## Specification
-### Example
+### Sign and check the weight
+
+Use these helpers with the authorized TronWeb instance on the transaction network. Before broadcasting, the node checks the signatures against the transaction owner’s current permission. [GetSignWeight](https://developers.tron.network/reference/getsignweight)
```javascript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TRKb2nAnCBfwxnLxgoKJro6VbyA6QmsuXq";
-// fromAddress = the account whose active permission controls the funds (the tx owner).
-// It is not necessarily the connected signer: if the connected account is only a
-// co-signer listed in that permission's keys[], set fromAddress to the controlled account.
-const fromAddress = tronweb.defaultAddress.base58;
-const activePermissionId = 2; // obtained via tronWeb.trx.getAccount(fromAddress).active_permission
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId }
-); // Step 1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // Step 2
- const res = await tronweb.trx.sendRawTransaction(signedTx); // Step 3
- if (!res.result) {
- // Node rejections are returned, not thrown — see Errors below.
- console.error(res.code, res.message && tronweb.toUtf8(res.message));
+function validateSignWeight(check, permissionId) {
+ const { permission, result, current_weight: weight } = check ?? {};
+ if (result?.code === "PERMISSION_ERROR") throw new Error("Recheck owner and permission");
+ if (!result || typeof result !== "object" || Array.isArray(result) ||
+ !permission || !Number.isSafeInteger(permission.threshold) ||
+ permission.threshold <= 0 || !Number.isSafeInteger(weight) || weight < 0 ||
+ !/^[0-9a-f]{64}$/i.test(permission.operations)) {
+ throw new Error("Permission or weight unavailable");
+ }
+ // TransferContract is operation 1 in the active permission bitmap.
+ const allowsTransfer = (parseInt(permission.operations.slice(0, 2), 16) & 2) !== 0;
+ if (permission.type !== "Active" || permission.id !== permissionId || !allowsTransfer) {
+ throw new Error("Recheck owner and permission");
+ }
+ return { code: result.code, weight, threshold: permission.threshold };
+}
+
+async function checkAndBroadcast(tronweb, signedTx, permissionId) {
+ const check = await tronweb.trx.getSignWeight(signedTx);
+ const { code, weight, threshold } = validateSignWeight(check, permissionId);
+ if (code === "NOT_ENOUGH_PERMISSION" && weight < threshold) {
+ return { status: "collect", signedTx };
+ }
+
+ // The node may omit the default ENOUGH_PERMISSION code.
+ if ((code !== undefined && code !== "ENOUGH_PERMISSION") || weight < threshold) {
+ throw new Error("Signature weight check failed");
+ }
+
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ throw new Error([receipt.code, message].filter(Boolean).join(" ") || "Broadcast rejected");
+ }
+ return { status: "submitted", txID: signedTx.txID };
+}
+
+async function signAndCheck(tronweb, tx) {
+ const permissionId = tx.raw_data.contract[0].Permission_id;
+ if (!Number.isSafeInteger(permissionId) || permissionId < 2) {
+ throw new Error("An active permission ID is required");
}
-} catch (e) {}
+
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.multiSign(tx, undefined, permissionId);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return { status: "declined" };
+ throw error;
+ }
+
+ return checkAndBroadcast(tronweb, signedTx, permissionId);
+}
+```
+
+### First signer
+
+Replace the recipient address and use the permission ID selected from the owner’s active permissions above.
+
+```javascript
+const recipient = "REPLACE_WITH_RECIPIENT_ADDRESS";
+const permissionId = 2; // Replace with the selected permission ID.
+if (!account.active_permission?.some(p => p.id === permissionId)) {
+ throw new Error("Select an active permission of the transaction owner");
+}
+
+// Build a 10 SUN transfer (1 TRX = 1_000_000 SUN).
+const tx = await tronweb.transactionBuilder.sendTrx(recipient, 10, owner, { permissionId });
+const outcome = await signAndCheck(tronweb, tx);
```
-If the user chooses “Reject” in the pop-up window, an exception will be thrown, which the developer can catch for further processing. If the user chooses “Sign” in the pop-up window, the DApp receives and broadcasts the signed transaction.
+### Additional co-signers
-Note that the broadcast only collects one signature in this call — a fully signed multi-sig tx requires the threshold to be met across multiple `multiSign` calls (one per co-signer). Track the partially-signed transaction off-chain (or via the MCP `tl_multisig_*` tools) until the threshold is reached, then broadcast.
+When the outcome has status `collect`, pass its `signedTx` to the next authorized co-signer using your DApp’s handoff flow. Each co-signer connects their wallet on the same network. Before signing, check that the transaction data matches its `txID`, show the co-signer the decoded owner, recipient, amount and expiration, and continue only after they confirm. Pass `coSignTransfer` the received transaction object and a `confirmTransfer` callback that resolves to `true` once the co-signer approves. `signAndCheck` calls `multiSign` on that object so the existing signatures and transaction ID carry forward.
+
+```javascript
+function describeTransfer(tronweb, tx) {
+ // The signature covers txID, so confirm raw_data hashes to it before showing details.
+ const txCheck = tronweb.utils?.transaction?.txCheck;
+ if (!txCheck || !txCheck(tx)) throw new Error("Transaction data does not match its txID");
+ const contract = tx.raw_data.contract[0];
+ if (contract.type !== "TransferContract") throw new Error("Not a TRX transfer");
+ const { owner_address, to_address, amount } = contract.parameter.value;
+ return {
+ owner: tronweb.address.fromHex(owner_address),
+ recipient: tronweb.address.fromHex(to_address),
+ amount: `${tronweb.fromSun(amount)} TRX`,
+ permissionId: contract.Permission_id,
+ expires: new Date(tx.raw_data.expiration).toISOString(),
+ };
+}
+
+async function coSignTransfer(partiallySignedTx, confirmTransfer) {
+ const tronweb = window.tron.tronWeb;
+ const details = describeTransfer(tronweb, partiallySignedTx);
+ // Show the details in your UI; sign only after the co-signer confirms them.
+ if (!(await confirmTransfer(details))) return { status: "declined" };
+ return signAndCheck(tronweb, partiallySignedTx);
+}
+```
+
+Repeat the handoff on `collect`. On `declined`, stop the current signing attempt. If the weight lookup fails or required fields are missing, pause and run the full weight check again after recovery. If the permission was revoked or no longer allows this operation, verify the owner and permission ID, rebuild the transaction and collect fresh signatures. If broadcast times out, look up the transaction ID before another submission.
## Errors
@@ -5212,7 +5546,7 @@ Note that the broadcast only collects one signature in this call — a fully sig
| Code | Meaning | Where it comes from | Retryable? |
| :---: | --- | --- | :---: |
| `'Confirmation declined by user'` (string) | User clicked **Reject** in the signing popup | `tronWeb.trx.multiSign(...)` | No — user declined |
-| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `fromAddress` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(fromAddress).active_permission` and rebuild the transaction |
+| `code: 'SIGERROR'`, `message` decodes to `Validate signature error: permission isn't exit` | `permissionId` does not exist on `owner` (wrong or revoked). `sendTrx` does **not** validate the permission — the node rejects at broadcast | Return value of `sendRawTransaction(...)` (not thrown) | No — re-query `getAccount(owner).active_permission` and rebuild the transaction |
| `code: 'SIGERROR'`, other `Validate signature error: …` messages | Signatures do not satisfy the permission — e.g. total weight below `threshold`, or a signer that is not in its `keys[]` | Return value of `sendRawTransaction(...)` (not thrown) | No — collect the missing signatures (one `multiSign` call per co-signer) |
| `REVERT` / `OUT_OF_ENERGY` / `FAILED` | Broadcast succeeded but execution failed on-chain | `getTransactionInfo(txid)` | **No — the tx is final; never auto-retry** |
@@ -5244,7 +5578,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
### Parameters
@@ -5264,12 +5604,7 @@ If the user chooses to sign in the pop-up window, the DApp will get the signed h
0xb0e0b150b9b10dc348f25c7f38fc87f16e18c0d230d23946aac519a5ad9e45937f656012d33c09e9d9dec00b03fbb304e797f8991bb823dce676ac91e03a55991b
```
-If an error occurs, the following information will be returned:
-
-```text
-
- Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
## Interaction
@@ -5433,7 +5768,7 @@ Definitions of terms, standards, and identifiers used across this documentation.
- **ABI** — Application Binary Interface: the JSON description of a contract's callable methods and events. If a token contract's ABI lacks a recognized method (e.g. `transfer`, `approve`), TronLink may not be able to offer that action.
- **`chainId`** — the network identifier. TronLink uses the hex form (e.g. `0x2b6653dc`) for `wallet_switchEthereumChain` and `chainChanged`, and the decimal EVM form (e.g. `728126428`) for EIP-712 `domain.chainId`. See [Networks & Addresses](networks.md).
- **`ProviderRpcError`** — the EIP-1193 error object emitted on `disconnect`, shaped `{ code: number; message: string; data?: unknown }`.
-- **permission id** — the active permission index used for multi-signature transactions (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
+- **permission id** — the value of the selected active permission’s `id` field on the transaction owner’s account (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
- **base58 / hex address** — the two TRON address encodings (`T...` vs `41...`). See [Networks & Addresses](networks.md#address-formats).
## AI tooling
@@ -5453,7 +5788,7 @@ TronLink agents traverse three or four error-code dialects when a single user re
**Error shape:** On the TronLink-injected `tronWeb` (extension 4.0.0 and later), when the user rejects `trx.sign`, `trx.multiSign`, or `trx.signMessageV2`, the promise rejects with the **plain string** `'Confirmation declined by user'` — not an `Error` object, and without a numeric `code`. The `{ code: 4001, message: 'User rejected the request.' }` object is returned only by `window.tron.request(...)` methods such as `eth_requestAccounts`. Other failures (locked wallet, invalid payload, watch-only account) use other values — see [Handling rejections](#handling-rejections). Do not automatically retry signing.
-| Business meaning | DApp provider ([EIP-1474][provider]) | DeepLink ([5-digit][deeplink]) | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
+| Business meaning | DApp provider ([EIP-1474][provider]) | [DeepLink callback code][deeplink] | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
| --- | :---: | :---: | :---: | :---: | :---: |
| **User rejected** the signing or connection prompt | `4001` from `window.tron.request(...)`; the string `'Confirmation declined by user'` from `tronWeb.trx.sign` / `multiSign` / `signMessageV2` | `300` (Transaction canceled) | — (HITL — re-prompt only on a fresh tool call) | `1` | **No** |
| **Invalid input** / malformed params | thrown by `tronWeb` builder | `10001`–`10020`, `10024`, `10025` | `TL_INVALID_INPUT` | `1` | **No** — fix the payload |
diff --git a/docs/llms-full.zh.txt b/docs/llms-full.zh.txt
index a52d0df..6266ff6 100644
--- a/docs/llms-full.zh.txt
+++ b/docs/llms-full.zh.txt
@@ -2,11 +2,11 @@
> 中文文档全文拼接,适合 LLM 一次性 ingest。由 scripts/gen_llms_full.py 生成。索引见 ../llms.txt 的 Localized 段。
-- Generated: 2026-11-04T10:12:58Z
-- Commit: 56f294d79923
+- Generated: 2026-11-26T12:11:13Z
+- Commit: 7d9fecacf230
- Language: zh
-- Pages: 24
-- Token estimate: ~42,359 (chars / 4)
+- Pages: 27
+- Token estimate: ~46,735 (chars / 4)
---
@@ -141,27 +141,39 @@ async function getTronWeb() {
async function connect() {
if (!tronProvider) return alert("未检测到 TronLink!");
try {
- const accounts = await tronProvider.request({
- method: "eth_requestAccounts",
- });
- console.log("已连接:", accounts[0]);
-
- const tronweb = tronProvider.tronWeb;
- const from = tronweb.defaultAddress.base58;
- const to = "TN9RRaXkCFtTXRso2GdTZxSxxwufzxLQPP"; // 请替换为真实的收款地址
+ await tronProvider.request({ method: "eth_requestAccounts" });
+ } catch (error) {
+ if (error?.code === 4001) return console.info("连接请求被拒绝");
+ return console.error("授权失败", error);
+ }
- // 构建一笔 10 SUN 的 TRX 转账(金额单位为 SUN:1 TRX = 1_000_000 SUN)
- const tx = await tronweb.transactionBuilder.sendTrx(to, 10, from);
+ const tronweb = tronProvider.tronWeb;
+ let tx;
+ try {
+ const to = "替换为实际收款地址";
+ // 构建一笔 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+ tx = await tronweb.transactionBuilder.sendTrx(to, 10, tronweb.defaultAddress.base58);
+ } catch (error) {
+ return console.error("构建转账失败", error);
+ }
- // 弹出 TronLink 确认窗口
- const signedTx = await tronweb.trx.sign(tx);
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return console.info("用户拒绝签名");
+ return console.error("签名失败", error);
+ }
- // 广播到网络
- const broadcastTx = await tronweb.trx.sendRawTransaction(signedTx);
- console.log(broadcastTx);
+ try {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ return console.error(receipt.code, message);
+ }
+ console.log("请查询该交易的链上确认状态", signedTx.txID);
} catch (error) {
- // 用户拒绝时为 { code: 4001, message: "User rejected the request." }
- console.error(error);
+ console.error("广播结果未知,重试前先按交易 ID 查询", signedTx.txID, error);
}
}
@@ -278,14 +290,21 @@ img {
}
-下文每个操作中,`tronlinkoutside://pull.activity?param={}` 的 `param` 参数都是 JSON 格式的协议数据。注意:JSON 字符串放入链接前需要进行 urlencode 编码。
+`param` 查询参数包含 URL 编码后的 JSON。每个示例链接都由其下方的请求对象编码而成。接入时请替换示例值,并重新生成链接。
+
+```javascript
+const buildDeepLink = (request) =>
+ "tronlinkoutside://pull.activity?param=" + encodeURIComponent(JSON.stringify(request));
+```
+
+登录、转账和签名时,请使用自己的 DApp 地址、回调地址、目标 chainId 和新生成的 actionId。交易签名时,将 `data` 设为新构建交易的 JSON 字符串。示例交易的有效期已过。
## 打开钱包
使用 DeepLink 方式唤起钱包。可用版本:TronLink v4.10.0 起。
```html
-Open Tronlink
+Open Tronlink
```
`param`(请求):
@@ -303,7 +322,7 @@ img {
使用 DeepLink 方式唤起钱包,并在 DApp 浏览器中打开 DApp。可用版本:TronLink v4.10.0 起。
```html
-Open DApp
+Open DApp
```
`param`(请求),`url` 为目标 DApp:
@@ -322,14 +341,14 @@ img {
使用 DeepLink 方式唤起钱包,并在钱包中选择获取钱包地址。可用版本:TronLink v4.11.0 起。
```html
-Login/Request Address
+Login/Request Address
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -358,14 +377,14 @@ img {
使用 DeepLink 方式唤起 TronLink,并发送转账数据,在钱包中转账并广播。可用版本:TronLink v4.11.0 起。
```html
-Transfer
+Transfer
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -401,14 +420,14 @@ img {
可用版本:TronLink v4.11.0 起。
```html
-Sign transaction
+Sign transaction
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -442,14 +461,14 @@ img {
可用版本:TronLink v4.11.0 起。
```html
-Sign message
+Sign message
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -476,12 +495,8 @@ img {
}
```
-
-
## 回传消息码
-> 注意:转账请求中 `tokenId` 与 `contract` 互斥,两者同时传入会返回消息码 `10025`。
-
| 消息码 | 消息 | 备注 |
|:-------|:-------|:-------|
| 0 | success | |
@@ -509,7 +524,7 @@ img {
| 10022 | Incorrect loginAddress | |
| 10023 | System contract not support | |
| 10024 | Incorrect tokenId | |
-| 10025 | TokenId & Contract address should not exist together | |
+| 10025 | TokenId & Contract address should not exist together | 转账请求中的资产标识冲突。 |
| 300 | Transaction canceled | |
| 301 | Transaction executed in TronLink | |
| 302 | Broadcast failure - returned with incorrect info | |
@@ -608,7 +623,13 @@ img {
}
```
-**转账** 请求——`tokenId`(TRX / TRC10)与 `contract`(TRC20)**互斥**;同时传入会返回 `10025`。不用的那个传 `""`(空字符串):
+**转账**字段按下表填写。沿用转账示例和 DeepLink Demo 的请求格式,将未使用的字段设为空字符串。省略未使用的字段会得到与示例不同的请求,本页未定义 App 对省略字段的处理方式,因此请保留两个字段。
+
+| 资产 | `tokenId` | `contract` |
+|---|---|---|
+| TRX | `"0"` | `""` |
+| TRC10 | 十进制字符串形式的代币 ID | `""` |
+| TRC20 | `""` | 代币合约地址 |
```json
{
@@ -622,8 +643,8 @@ img {
"from": { "type": "string", "description": "发起方 TRON 地址(base58)" },
"to": { "type": "string", "description": "收款方 TRON 地址(base58)" },
"loginAddress": { "type": "string", "description": "本次会话的授权地址——必须与当前钱包一致,否则返回 10021" },
- "tokenId": { "type": "string", "description": "TRC10 token id,或 '0' 表示 TRX;发送 TRC20 时传 ''" },
- "contract": { "type": "string", "description": "TRC20 合约地址;发送 TRX / TRC10 时传 ''" },
+ "tokenId": { "type": "string", "description": "TRC10 token id,或 '0' 表示 TRX" },
+ "contract": { "type": "string", "description": "TRC20 合约地址" },
"amount": { "type": "string", "description": "人类单位的十进制字符串(如 '1.5'),App 内部处理 decimals" },
"memo": { "type": "string", "description": "可选交易备注" },
"dappName": { "type": "string" },
@@ -732,7 +753,9 @@ img {
TronLink App 内置 DApp 浏览器,对于在其上运行的 TRON DApp,TronLink 会自动将 tronWeb 及 tronLink 对象注入到该 DApp。从而允许 DApp 与 TronLink App,以及TRON 网络交互。
-详情:参考[DApp章节](../../dapp/getting-started)
+在 App 内置浏览器中取得已授权的 TronWeb 实例后,可参考[开始开发](../dapp/getting-started.md)中的交易构建步骤。该指南中的 Provider 发现(TIP-6963)、授权(`eth_requestAccounts`)和事件示例面向浏览器插件,请在目标 App 版本上逐项确认接口支持情况。
+
+从外部移动浏览器唤起 TronLink 请参考 [DeepLink](deeplink.md)。
## Dapp 浏览器
@@ -754,6 +777,112 @@ DApp 浏览器支持运行 TRON DApp,并自动注入 tronWeb 及 tronLink 对
---
+
+
+# Android 开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-android-core](https://github.com/TronLink/tronlink-android-core)
+
+在 Android 应用中集成 TronLink 的钱包功能,可以创建 TRON 钱包、读取地址,并对交易或消息签名。
+
+## 安装
+
+环境要求为 Android API 21 及以上;Java 版本见上游[构建配置](https://github.com/TronLink/tronlink-android-core/blob/main/core/build.gradle)。在 Gradle 解析依赖的仓库列表中加入 JitPack。以下示例使用 Groovy DSL。
+
+```groovy
+repositories {
+ maven { url "https://jitpack.io" }
+}
+```
+
+在应用模块中声明 AAR 依赖。将 `` 替换为[发布页](https://github.com/TronLink/tronlink-android-core/releases)中的标签,通常使用最新版本。
+
+```groovy
+dependencies {
+ implementation 'com.github.TronLink:tronlink-android-core:@aar'
+}
+```
+
+## 创建钱包
+
+在应用中创建钱包并读取 TRON 地址。
+
+```java
+import org.tron.walletserver.Wallet;
+
+// 在应用的方法中执行
+Wallet wallet = new Wallet(true);
+String address = wallet.getAddress();
+```
+
+钱包测试还演示了如何通过助记词或私钥恢复地址。交易签名的用法见交易测试。测试中没有消息签名示例,库中的实现位于 `org.tron.common.bip32.Sign`(`signPrefixedMessage`、`signPrefixedMessageV2`)。[钱包示例](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/WalletCoreUnitTest.java) · [交易签名示例](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/TransactionCoreUnitTest.java) · [`Sign.java`](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/main/java/org/tron/common/bip32/Sign.java)
+
+## 验证 AAR 签名
+
+验签需要 TronLink 签署的 AAR 原件及配套的独立签名文件 `.asc`。JitPack 和 GitHub 发布页不提供签名文件,如需验签,请向维护者索取签署的 AAR 和配套签名。参见[上游验签说明](https://github.com/TronLink/tronlink-android-core#integrity-check)。
+
+下载[发布公钥](https://keys.openpgp.org/vks/v1/by-fingerprint/7B910EA80207596075E6D7BA5D34F7A6550473BA),保存为 `tronlink-build.asc`。先查看签名子密钥的指纹,与上游公布的 `7B910EA80207596075E6D7BA5D34F7A6550473BA` 核对。一致后导入公钥,再用维护者提供的两个文件验签;请替换下例中的文件名。
+
+```bash
+gpg --show-keys --with-subkey-fingerprint tronlink-build.asc
+gpg --import tronlink-build.asc
+gpg --verify release.aar.asc release.aar
+```
+
+## 隐私
+
+集成本库不会自动开始使用统计上报。`org.tron.metrics` 中的上报代码只有在宿主应用接入相应的数据仓库,并调用 `DataUploader.init(...)` 和 `upload(...)` 后,才会记录和上传数据。启用前请参阅上游的[隐私说明](https://github.com/TronLink/tronlink-android-core/blob/main/PRIVACY-POLICY.md)。
+
+## 版本与许可证
+
+本页示例和链接以上游 `main` 分支为准。固定使用较旧的标签时,请核对其接口是否一致。[Apache License 2.0](https://github.com/TronLink/tronlink-android-core/blob/main/LICENSE)
+
+---
+
+
+
+# iOS 开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-iOS-core](https://github.com/TronLink/tronlink-iOS-core)
+
+在 iOS 应用中使用 TronLink 的原生钱包模块,可以创建 TRON 钱包、读取地址,并对交易或消息签名。
+
+## 安装
+
+在 Podfile 中为应用 target 添加依赖。支持的最低 iOS 版本和 Swift 版本见 [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec)。
+
+```ruby
+pod 'tronlink-iOS-core'
+```
+
+运行 `pod install`,用 Xcode 打开生成的 `.xcworkspace`,然后在 Swift 文件中导入模块。
+
+```swift
+import TLCore
+```
+
+## 运行示例工程
+
+要在上游 Xcode 示例工程中查看钱包 API 的用法,请先进入示例目录安装依赖。
+
+```bash
+git clone https://github.com/TronLink/tronlink-iOS-core.git
+cd tronlink-iOS-core/Example
+pod install
+```
+
+在 Xcode 中打开 `Example/` 下的工作区。Swift 测试展示了创建钱包、签署交易和消息,以及导出私钥或助记词的用法。[Swift 钱包示例](https://github.com/TronLink/tronlink-iOS-core/blob/main/Example/Tests/Tests.swift)
+
+## 隐私
+
+安装 Pod 或创建钱包不会自动上传统计数据。要启用上传,集成方需要主动调用上报方法,实现 `TRXMetricsDataSource` 的上传回调,并将应用当前连接的环境标记为生产或预发布。Debug 和 Release 构建都遵循这项检查。TronLink iOS 还会在基础模式、观察钱包和 Shasta 测试网下停用上报。[iOS 隐私说明](https://github.com/TronLink/tronlink-iOS-core/blob/main/PRIVACY-POLICY.md)
+
+## 版本与许可证
+
+当前版本见 [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec)。[Apache License 2.0](https://github.com/TronLink/tronlink-iOS-core/blob/main/LICENSE)
+
+---
+
# 主动请求TronLink插件功能
@@ -769,7 +898,10 @@ TronLink 可用于管理钱包私钥,DApp 在进行一些需签名的操作前
```javascript
try {
await window.tron.request({method: 'eth_requestAccounts'});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("连接请求被拒绝");
+ else console.error("授权失败", error);
+}
```
#### 返回值
@@ -798,8 +930,6 @@ try {
> **旧版用法(不推荐):** [兼容用法:tron_requestAccounts](#tron_requestaccounts)
-
-
## 获取TronLink的provider TIP-6963
### 简介
@@ -884,10 +1014,17 @@ const tronweb = window.tron.tronWeb;
const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress); // 步骤1
+let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
-} catch (e) {}
+ signedTx = await tronweb.trx.sign(tx); // 步骤2
+} catch (error) {
+ if (error === "Confirmation declined by user") console.info("用户拒绝签名");
+ else console.error("签名失败", error);
+}
+if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+}
```
当代码执行到 `await tronweb.trx.sign(tx);` 时,TronLink 钱包会提示弹窗,需要用户进行确认,如下图:
@@ -910,24 +1047,7 @@ try {
### 技术规范
#### 代码示例
-```typescript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
-const fromAddress = tronweb.defaultAddress.base58; // 交易 owner:由该 active 权限控制的账户;若当前账户只是共同签名人,请显式填写被控制账户
-const activePermissionId = 2;
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
-); // 步骤1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
-} catch (e) {}
-```
-
-如果用户在弹窗中选择【拒绝】,则会抛出异常,开发者可捕获此异常进行业务处理。
-
-如果用户在弹窗中选择【签名】,DApp 可以拿到签名后的交易,继续进行广播。
+按[多签转账示例](../dapp/multi-sign-transfer.md)查询交易 owner 的权限、收集签名并核对累计权重,满足阈值后再广播。
> **旧版用法(不推荐):** [兼容用法:multiSign(window.tronLink)](#multisignwindowtronlink)
@@ -949,7 +1069,13 @@ try {
// 用同一个字符串验签,返回签名者的 base58 地址
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+}
```
#### 参数
消息须为非空**字符串**。TronLink 对该字符串的 UTF-8 字节签名,并加上 TIP-191 前缀 `"\x19TRON Signed Message:\n" + <字节长度>`。外观类似 hex 的字符串**不会**被解码:`"0x1234"` 按六个文本字符(字节为 `30 78 31 32 33 34`)签名,而不是两个原始字节 `12 34`。
@@ -965,10 +1091,7 @@ try {
```text
0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c
```
-如果报错,则会返回如下信息:
-```typescript
-Uncaught (in promise) Invalid transaction provided
-```
+消息为空或钱包签名失败时可能返回 `Invalid transaction provided`。用户拒签时返回 `Confirmation declined by user`。其他失败请查看具体错误原因。
### 交互流程
@@ -1113,7 +1236,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("用户拒绝切换网络");
+ else console.error("切换网络失败", error);
+}
```
#### 参数
params 接受一个只有单一元素的数组,单一元素为 `SwitchTronChainParameter` 类型:
@@ -1148,7 +1274,7 @@ interface SwitchTronChainParameter {

-解锁后,或者 TronLink 已经提前解锁,会打开连接确认的弹窗:
+解锁后,或者 TronLink 已经提前解锁,会打开网络切换确认弹窗:

@@ -1339,12 +1465,27 @@ interface SwitchTronChainParameter {
```json
{
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": { "type": "integer", "enum": [200, 4000, 4001] },
- "message": { "type": "string" }
- }
+ "oneOf": [
+ {
+ "const": ""
+ },
+ {
+ "type": "object",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [200, 4000, 4001]
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ ]
}
```
@@ -1365,15 +1506,22 @@ TronLink 提供外部发起 TRX 转账、合约签名、授权等功能。基于
### 技术规范
#### 代码示例
```typescript
-const res = await tronWeb.request(
+const res: RequestAccountsResponse = await window.tronLink.request(
{
method: 'tron_requestAccounts',
params: {
websiteIcon: '',
websiteName: '',
- } as RequestAccountParams,
+ } as RequestAccountsParams,
}
);
+if (res === "") {
+ console.info("请解锁 TronLink");
+} else if (res.code === 200) {
+ console.info("已连接");
+} else {
+ console.info(res.code, res.message);
+}
```
#### 参数
@@ -1384,7 +1532,7 @@ interface RequestAccountsParams {
}
```
* method: `tron_requestAccounts` 固定的字符串
-* params: `RequestAccountParams` 类型,具体参数如下
+* params: `RequestAccountsParams` 类型,具体参数如下
* websiteIcon: DApp 网站的 Icon 的 URI,具体会展示在用户已连接网站列表中
* websiteName: DApp 网站名称
@@ -1392,7 +1540,7 @@ interface RequestAccountsParams {
#### 返回值
类型说明:
```typescript
-interface ReqestAccountsResponse {
+type RequestAccountsResponse = "" | {
code: 200 | 4000 | 4001,
message: string
}
@@ -1415,32 +1563,24 @@ if (window.tronLink.ready) {
const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress); // 步骤1
+ let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- } catch (e) {}
+ signedTx = await tronweb.trx.sign(tx); // 步骤2
+ } catch (error) {
+ if (error === "Confirmation declined by user") console.info("用户拒绝签名");
+ else console.error("签名失败", error);
+ }
+ if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+ }
}
```
## 兼容用法:multiSign(window.tronLink)
-```typescript
-if (window.tronLink.ready) {
- const tronweb = tronLink.tronWeb;
- const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
- const fromAddress = tronweb.defaultAddress.base58; // 交易 owner:由该 active 权限控制的账户;若当前账户只是共同签名人,请显式填写被控制账户
- const activePermissionId = 2;
- const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
- ); // 步骤1
- try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- } catch (e) {}
-}
-```
+按[多签转账示例](../dapp/multi-sign-transfer.md)查询交易 owner 的权限、收集签名并核对累计权重,满足阈值后再广播。使用旧版 provider 时,等待 `window.tronLink.ready` 为真,再从 `window.tronLink.tronWeb` 取得示例中的 `tronweb`。
## 兼容用法:signMessageV2(window.tronLink)
@@ -1451,7 +1591,13 @@ if (window.tronLink.ready) {
try {
const message = "Sign in to Example DApp\nNonce: 8f3a2c"; // 普通 UTF-8 文本
const signedString = await tronweb.trx.signMessageV2(message);
- } catch (e) {}
+ } catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+ }
}
```
@@ -1463,42 +1609,48 @@ if (window.tronLink.ready) {
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc10',
options: { address: '1002000' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
// 添加 TRC20
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc20',
options: { address: 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
// 添加 TRC721
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc721',
options: { address: 'TVtaUnsgKXhTfqSFRnHCsSXzPiXmm53nZt' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
```
@@ -1511,7 +1663,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("用户拒绝切换网络");
+ else console.error("切换网络失败", error);
+}
```
---
@@ -1742,7 +1897,7 @@ window.tron.on('disconnect', (providerRpcError) => {
})
```
-> **旧版用法(不推荐):** [disconnectWeb(postMessage)](#disconnectweb) 或 [rejectWeb(postMessage)](#rejectweb)
+> **旧版用法(不推荐):** [disconnectWeb(postMessage)](#disconnectweb)
## 历史遗留问题
@@ -2014,6 +2169,56 @@ ledger返回的实际签名hash:
---
+
+
+# 插件开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-extension-core](https://github.com/TronLink/tronlink-extension-core)
+
+`@tronlink/core` 是 TronLink 插件使用的 JavaScript / TypeScript 钱包库。钱包应用可以用它派生 TRON 和 EVM 账户,并在本地签名。DApp 如需连接用户已安装的 TronLink 插件并请求签名,请使用[插件提供的接口](active-requests.zh.md)。
+
+## 安装
+
+通过 npm 安装。该包提供 CommonJS、ES 模块入口以及 TypeScript 类型声明。
+
+```bash
+npm install @tronlink/core
+```
+
+所需的 Node.js、pnpm(开发用)和 TypeScript 版本见上游环境要求。面向浏览器打包时,需要为 `buffer`、`crypto`、`stream` 等 Node 模块配置 polyfill。[环境要求](https://github.com/TronLink/tronlink-extension-core/blob/main/README.md#prerequisites) · [上游 webpack 配置](https://github.com/TronLink/tronlink-extension-core/blob/main/webpack.config.js)
+
+## 派生 TRON 地址
+
+生成助记词,获取第一个账户下第一个地址的派生路径,再用该路径派生私钥并计算地址。
+
+```ts
+import { BaseWallet, TronWallet } from '@tronlink/core';
+
+const wallet = new TronWallet();
+const mnemonic = BaseWallet.generateRandomMnemonic();
+const path = wallet.derivePath({ accountIndex: 0, addressIndex: 0 });
+const privateKey = wallet.derivePrivateKey({ mnemonic, path });
+const address = wallet.getAddressBy({ privateKey });
+```
+
+派生 EVM 地址时,使用 `EvmWallet` 的 `derivePath` 获取对应路径,再派生私钥。[TRON 与 EVM 账户示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/create_account.ts)
+
+## 签名
+
+两个钱包类都支持交易、消息和结构化数据签名。对 TRON 交易签名时,将已构建的交易传入 `wallet.signTransaction({ privateKey, data: rawTransaction })`。对 EVM 交易签名时,在 `data` 中提供链配置和未签名交易。签名结果在本地返回,广播需另行执行。[TRON 签名示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/tron_signature.ts) · [EVM 签名示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/evm_signature.ts)
+
+## Ledger 与使用统计
+
+Ledger 签名要求浏览器提供 `navigator.hid`。使用设备上的 TRX 应用时选择 `LedgerTrxSigner`,使用 ETH 应用时选择 `LedgerEvmSigner`。
+
+导入包、派生地址或在本地签名都不会自动上传统计数据。启用上报需要宿主调用 `checkAndReportXY(deps)` 并提供上传回调。可选的 `userStatistics` 模块使用设备上为地址分配的 UUID,按日期和金额区间汇总主网活动。[隐私与上报说明](https://github.com/TronLink/tronlink-extension-core/blob/main/PRIVACY.md)
+
+## 版本与许可证
+
+当前版本见[包配置](https://github.com/TronLink/tronlink-extension-core/blob/main/package.json)。[Apache License 2.0](https://github.com/TronLink/tronlink-extension-core/blob/main/LICENSE)
+
+---
+
# MCP Server TronLink
@@ -2026,7 +2231,7 @@ ledger返回的实际签名hash:
**核心亮点:**
- 双模架构:**Playwright**(浏览器自动化)+ **Direct API**(链上操作)
-- 32 个内置 Flow Recipe,带预检查和依赖解析
+- 24 个内置 Flow Recipe,带预检查和依赖解析
- 基于加密 `agent-wallet` 的非托管本地交易签名
- 多签管理,支持实时 WebSocket 监控
- 通过 GasFree 服务集成实现零 Gas TRC20 转账
@@ -2045,7 +2250,7 @@ flowchart TD
Multi["TronLinkMultiSigCapability (5 个工具)"]
GasFree["TronLinkGasFreeCapability (3 个工具)"]
Util["实用能力
Build · StateSnapshot · TRON Crypto"]
- Flow["Flow Recipes
(32 个内置流程配方)"]
+ Flow["Flow Recipes
(24 个内置流程配方)"]
Ext["TronGrid API / 多签服务 / GasFree 服务"]
Chain["TRON 区块链"]
Agent -- "MCP 协议 — stdio / JSON-RPC 2.0" --> Server
@@ -2192,11 +2397,13 @@ hexToAddress() 0x41... → T 地址
---
-## Flow Recipes(32 个内置流程)
+## Flow Recipes(24 个内置流程)
预配置的多步骤工作流,带依赖检查和参数模板。
-### Playwright 流程
+调用 `tl_list_flows` 可查看运行中服务的注册清单。
+
+### Playwright 流程(4 个)
| 流程 | 说明 |
|------|------|
| `switchNetworkFlow` | 切换到主网/Nile/Shasta |
@@ -2266,7 +2473,7 @@ hexToAddress() 0x41... → T 地址
| 变量 | 说明 |
|------|------|
-| `AGENT_WALLET_PASSWORD` | 钱包加密密码(自动创建时可省略;手动或已有钱包时需要) |
+| `AGENT_WALLET_PASSWORD` | 钱包加密密码(手动创建的钱包需提供;本地自动创建的钱包可复用已保存的随机密码) |
| `AGENT_WALLET_DIR` | 自定义钱包目录 |
| `TL_OWNER_WALLET_ID` | 多签 owner 使用的钱包 ID |
| `TL_COSIGNER_WALLET_ID` | 多签 cosigner 使用的钱包 ID |
@@ -2308,15 +2515,13 @@ Claude Code 自动检测:
}
```
-如果本地还没有钱包,服务启动后会提示两条路径:
+**手动创建(生产推荐)**。新建钱包时运行 `agent-wallet start local_secure --generate --wallet-id main`。对于该钱包或已有钱包,通过凭据管理器将其密码导出到启动 Claude Code(已核对 2.1.141)的环境变量 `AGENT_WALLET_PASSWORD`。在服务的 `env` 对象中添加下列配置,Claude Code 在启动服务时展开变量。 [Claude Code MCP](https://code.claude.com/docs/en/mcp#environment-variable-expansion-in-mcp-json)
-1. 自动创建:调用 `tl_wallet_create`
-2. 手动创建:
- 1. 运行 `agent-wallet start local_secure --generate --wallet-id main`
- 2. 把 `AGENT_WALLET_PASSWORD` 写进 `.mcp.json`
- 3. 重启 MCP 服务
+```json
+{ "AGENT_WALLET_PASSWORD": "${AGENT_WALLET_PASSWORD}" }
+```
-如果选择自动创建,服务会生成随机密码,把密码保存到 `~/.agent-wallet/runtime_secrets.json`,创建一个加密的 `main` 钱包,并继续当前会话。
+**自动创建(本地开发)**。省略上述密码配置项。在尚无钱包时调用 `tl_wallet_create`,服务会生成随机密码,明文保存到 `~/.agent-wallet/runtime_secrets.json` 以便重启后复用。将文件权限限制为仅所有者可读写(`chmod 600`),并保护备份。
下面是更完整的 Nile 配置。其中的路由地址是 SunSwap 官方的 Nile Router([V2](https://docs.sun.io/protocols/sunswap-v2/reference/contract/)、[V3](https://docs.sun.io/protocols/sunswap-v3/reference/contract/));请勿把主网路由地址填进 Nile 配置。`tl_chain_swap`(V2)会把报价 API 最优路径中的代币路径交给 V2 路由执行,路径包含非 V2 池子时会失败(例如 Nile 上的 TRX→USDT)。Shasta 的 URL 会使用主网默认值,因此 Shasta 上无法兑换:
@@ -2332,7 +2537,6 @@ Claude Code 自动检测:
"TL_MODE": "prod",
"TL_HEADLESS": "false",
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2359,7 +2563,6 @@ Claude Code 自动检测:
"cwd": ".",
"env": {
"TL_TRONGRID_URL": "https://nile.trongrid.io",
- "AGENT_WALLET_PASSWORD": "your-wallet-password",
"TL_SUNSWAP_ROUTER": "TYMjxCXfqLpMWW1QToP6hbcjpion7EE25p",
"TL_SUNSWAP_V3_ROUTER": "TFkswj6rUfK3cQtFGzungCkNXxD2UCpEVD",
"TL_MULTISIG_BASE_URL": "https://apinile.walletadapter.org",
@@ -2406,7 +2609,7 @@ mcp-server-tronlink/
│ │ ├── state-snapshot.ts # UI 状态提取
│ │ └── tron-crypto.ts # 地址派生、签名、Base58
│ └── flows/
-│ ├── index.ts # 流程注册(32 个配方)
+│ ├── index.ts # 流程注册(24 个配方)
│ ├── switch-network.ts # 网络切换流程
│ ├── transfer-trx.ts # 转账流程
│ ├── multisig.ts # 6 个多签流程
@@ -2424,7 +2627,7 @@ mcp-server-tronlink/
## 依赖项
-锁定到 `mcp-server-tronlink@0.1.1` 的 `package.json`。升级钱包、MCP 或密码学库 major 版本时务必重新核对。
+依赖范围取自 `mcp-server-tronlink@0.1.1` 的 `package.json`。升级钱包、MCP 或密码学库 major 版本时务必重新核对。
| 包名 | 版本 | 用途 |
|------|------|------|
@@ -2432,14 +2635,14 @@ mcp-server-tronlink/
| `@noble/hashes` | ^2.0.1 | Keccak-256、SHA256 |
| `@tronlink/tronlink-mcp-core` | ^0.1.0 | 核心 MCP 服务框架 |
| `playwright` | ^1.49.0 | 浏览器自动化 |
-| `@bankofai/agent-wallet` | ^2.3.0 | 加密本地钱包管理(`local_secure`)——**已钉版本,不用 `latest`**,确保钱包行为可复现 |
+| `@bankofai/agent-wallet` | ^2.3.0 | 加密本地钱包管理(`local_secure`)。允许安装 2.3.0 至 3.0.0 之前的兼容版本。用 `npm ls @bankofai/agent-wallet` 查看实际安装版本。 |
| `ws` | ^8.18.0 | WebSocket(多签监控) |
---
## 工具契约与副作用
-**输入/输出 schema 与错误契约。** 每个工具的输入/输出 schema 及结构化错误信封由底层框架定义——见 [TronLink MCP Core](tronlink-mcp-core.md#error-codes) 的 SSOT 错误码表(`code` / `retryable` / `hint` / 典型触发)。每个响应均带 `meta.schemaVersion`,major 版本内字段含义稳定。Agent 应基于 `error.code` 与 `error.retryable` 分支,**不要**解析人类可读的 `message`。
+**工具结果与错误。** 服务端使用 Core 0.1.0 时,先检查 Core 响应中的 `ok`。失败时,根据 `error.code` 在 [Core 错误码表](tronlink-mcp-core.zh.md#error-codes) 中查找重试条件。错误响应包含 `error.message`,也可能包含 `error.details`。对于结果未知的写操作,先核对交易状态,再决定是否重试。
**逐工具输入 schema 可在运行时发现。** 每个工具的参数都由 core 用 Zod 校验,并通过 MCP `list_tools` 方法以 JSON `inputSchema` 形式暴露,因此客户端无需阅读本页即可枚举参数名、类型和必填项。下方表格按能力归纳工具;`list_tools` 才是权威的机器可读来源。
@@ -2454,11 +2657,9 @@ mcp-server-tronlink/
- **人工确认(HITL):** 写操作工具使用加密的本地 `agent-wallet` 签名;浏览器模式下由用户在 TronLink UI 审批。生产环境应将每个「远程写」工具视为需要确认。
- **重试:** 只读工具可安全重试;「远程写」工具除非证明幂等,否则不得自动重试。
-
-
### 精选工具 schema(文档侧镜像)
-以下是最关键工具输入的**文档侧镜像**——当 agent 需要在没有打开 MCP 会话的情况下写工具调用站点时使用。运行时 `list_tools` 仍是权威源:那里有完整的 Zod 元信息(描述、`default` 等)以及 `meta.schemaVersion`。下方字段抄自 `@tronlink/tronlink-mcp-core` `src/mcp-server/schemas.ts`,遵循 JSON Schema Draft 7。**未**镜像全部 52 个工具——以 core 仓库为 SSOT。
+下表摘录了部分工具的输入参数。对实际安装的服务调用 `tools/list`,从各工具的 `inputSchema` 读取参数说明和默认值。以下示例使用 JSON Schema Draft 7。
> 下方各块的字段名和 required 标记由文档 CI 与上游 `schemas.ts` 自动比对;如有不一致,以 `list_tools` 为准。
@@ -2585,7 +2786,7 @@ mcp-server-tronlink/
| 边界 | 保证 | Agent / 运维方义务 |
|---|---|---|
-| **Prompt 注入** | 工具输入按原始值作为调用参数使用,server 不会把工具输入拼接进任何向 LLM 二次提交的 prompt。**但**从链上或第三方 API 拿回来的字符串(账户备注、合约 revert 原因、交易 note 等)**可能含攻击者控制内容**,必须视为不可信。 | 不要让 agent 基于 read 工具返回的 prose 自动路由到 Remote Write。分支必须基于结构化字段(`txId`、`code`、`retryable`)。 |
+| **Prompt 注入** | 工具输入按原始值作为调用参数使用,server 不会把工具输入拼接进任何向 LLM 二次提交的 prompt。**但**从链上或第三方 API 拿回来的字符串(账户备注、合约 revert 原因、交易 note 等)**可能含攻击者控制内容**,必须视为不可信。 | 不要让 agent 基于 read 工具返回的 prose 自动路由到 Remote Write。分支必须基于结构化字段(`txId`、`error.code`)。 |
| **出站 host 白名单(SSRF)** | server 只向 3 个配置端点发起 HTTPS——`TL_TRONGRID_URL`(TronGrid;SunSwap 路由合约也通过它的 `triggersmartcontract` 接口调用)、`TL_MULTISIG_BASE_URL`、`TL_GASFREE_BASE_URL`——以及内置的 SunSwap 报价 API(主网 `rot.endjgfsv.link`,Nile `tnrouter.endjgfsv.link`,不可配置)。工具不接收会被原样请求的用户 URL。 | 生产环境把这些 env 钉死到已知 host,并把报价 API host 加入出站白名单;禁止 LLM 输入回填任何 `*_BASE_URL`。 |
| **API key 处理(token passthrough)** | `TL_TRONGRID_API_KEY`、`TL_MULTISIG_SECRET_KEY`、`TL_GASFREE_API_SECRET` 仅在启动时从 env 读取,仅用于出站;**不**会出现在任何工具响应、错误 `details` 或 Knowledge Store 记录中。server 不接受 MCP 客户端传入的 Authorization header 并转发到上游。 | 审计 MCP host 配置对 env 的捕获(部分 host 会落日志);secret 放进 host 的 secret manager,不要写进会提交 git 的 `.mcp.json`。 |
| **浏览器 JS 执行** | `tl_evaluate` 会在受控 Playwright 浏览器上下文中执行任意 JS。这是 **High-risk / Destructive** 原语——可读 DOM、点击隐藏元素、外泄状态、绕过 UI 上的 HITL。 | 严格不需要时,从 MCP host 的工具白名单中禁用 `tl_evaluate`。绝不要把它暴露给远程/多用户 MCP 部署。 |
@@ -2597,7 +2798,7 @@ mcp-server-tronlink/
兑换属于 **远程写**,且对接公开 DEX 路由器,因此暴露在 **价格滑点** 与 **三明治攻击 / MEV** 之下:在报价和执行之间池子价格变动时,实际成交可能比报价更差。
-- **必须设置 minOut / 滑点上限。** 通过 `list_tools` 查看 `tl_chain_swap_v3` 的输入 schema(`SwapV3Params`),核对实际的 minimum-output / 滑点字段名;**不要**依赖未声明的默认值,缺省或 0 的 minOut 一律视为不安全。
+- **必须显式设置 `slippage`。** `tl_chain_swap_v3` 没有最小输出参数,服务端根据 `slippage`(百分比,默认 0.5)计算最小输出。**不要**依赖默认值;请与用户确认滑点,并在 `list_tools` 的 schema 中核对该字段。
- **执行前现取报价。** 通过 Skills `tron-swap` 的 `swap-quote` / `swap-route`(或同等接口)取最新报价/路径,选定可接受的滑点容忍度并显式传入。
- **核对 router。** 请将 `TL_SUNSWAP_ROUTER` / `TL_SUNSWAP_V3_ROUTER` 设置为 SunSwap 官方合约地址中对应网络的 Router(见环境变量);过期或错误的 router 会把资金路由到非预期目标。
- **不可自动重试。** swap 失败或结果未知都属于远程写——先在链上确认再决定是否重发(`TL_CHAIN_SWAP_FAILED` 不可重试)。
@@ -2649,9 +2850,9 @@ mcp-server-tronlink/
Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签名。解锁这把钱包有两条路径,请按目的明确选择。
-**路径 A — 手动(生产推荐)。** 离线创建钱包,将 `AGENT_WALLET_PASSWORD` 放进 MCP host 的 secret manager,再启动 server。密码仅存在于进程内存,server 不写任何文件。
+**手动创建(生产推荐)。** 离线创建钱包,将 `AGENT_WALLET_PASSWORD` 放进 MCP host 的 secret manager,再启动 server。此路径从运行环境读取提供的密码。
-**路径 B — 自动创建(仅适合本地开发)。** 启动时若无钱包且 agent 调用了 `tl_wallet_create`,server 将:
+**自动创建(仅适合本地开发)。** 启动时若无钱包且 agent 调用了 `tl_wallet_create`,server 将:
1. 生成随机密码。
2. **将密码以明文写入 `~/.agent-wallet/runtime_secrets.json`**,以便重启后能复用同一钱包。
@@ -2660,7 +2861,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
| 方面 | 行为 |
|---|---|
| **文件** | `~/.agent-wallet/runtime_secrets.json`(含密码的明文 JSON) |
-| **建议权限** | `chmod 600`——文件在用户 `$HOME` 下创建,但**没有 umask 兜底**,首次运行后请手工核查。 |
+| **建议权限** | 0.1.1 新建文件时指定权限 `0600`。启动后请核对实际权限。 |
| **Git 隔离** | `~/.agent-wallet/` 默认在任何仓库之外。若把 `AGENT_WALLET_DIR` 指到仓库内部,必须显式加 `.gitignore`。 |
| **Knowledge Store 脱敏边界** | Knowledge Store 自动脱敏 `password`、`mnemonic`、`private_key`、`seed` 等字段;**不**读取或处理 `runtime_secrets.json`。该文件与 Knowledge Store 互相独立。 |
| **日志 / stderr** | 自动生成的密码不会落日志;文件路径可能出现在启动输出中。 |
@@ -2668,11 +2869,11 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
**生产建议。**
-- 优先路径 A。`AGENT_WALLET_PASSWORD` 来自 host 的 secret manager(Claude Desktop env、vault 等)。
-- 必须用路径 B 时(如临时 CI),把 `AGENT_WALLET_DIR` 指到任务结束即销毁的 tmpfs。
+- 优先手动创建。`AGENT_WALLET_PASSWORD` 来自 host 的 secret manager(如 vault)。
+- 必须用自动创建时(如临时 CI),把 `AGENT_WALLET_DIR` 指到任务结束即销毁的 tmpfs。
- 涉及真实资金的工具,生产环境优先选 `mcp-tronlink-signer`(浏览器审批、不落盘密码),避免 Direct-API。
-**如何强制路径 A(文档侧的当下做法)。**
+**如何强制手动创建(文档侧的当下做法)。**
1. **server 启动前**离线创建钱包:
@@ -2681,7 +2882,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
# 此处输入的密码请单独保管——它是唯一的副本
```
-2. 让密码通过 MCP host 的 secret manager 注入到 server 的 `env`:
+2. 使用 Claude Code 时,通过凭据管理器将密码导出到客户端启动环境,并在服务配置中引用变量:
```jsonc
// .mcp.json — secret 来自 host env,而不是这个文件本身
@@ -2698,7 +2899,7 @@ Direct-API 路径使用 `@bankofai/agent-wallet` 管理的本地加密钱包签
3. **禁止 agent 调用 `tl_wallet_create`。** 用与 `tl_evaluate` 相同的方式禁用(Claude Code `permissions.deny`、Claude Desktop `disabledTools`,或客户端侧基于 `list_tools` 用名字 `tl_wallet_create` 过滤)。
-4. 首次启动后验证:`list_tools` 中不应出现 `tl_wallet_create`;`~/.agent-wallet/runtime_secrets.json` 不存在即说明路径 B 没有走过。
+4. 首次启动后验证:`list_tools` 中不应出现 `tl_wallet_create`;`~/.agent-wallet/runtime_secrets.json` 不存在即说明自动创建没有走过。
**待解决(代码侧)。** 长期方案是在 server 启动时加 `--no-auto-create` / `AGENT_WALLET_DISABLE_AUTOCREATE=1` 开关,使无钱包时直接 fail-loud。上游 PR ship 之前,上面这套文档级强制方案是 defense-in-depth。
@@ -2725,10 +2926,10 @@ npm install && npm run build
export TL_TRONGRID_URL="https://nile.trongrid.io"
# 3. 如果本地还没有钱包,二选一:
-# 方案 A:在 MCP 会话里调用 tl_wallet_create
-# 方案 B:本地执行
+# 自动创建(本地开发):在 MCP 会话里调用 tl_wallet_create
+# 手动创建(生产推荐):本地执行
# agent-wallet start local_secure --generate --wallet-id main
-# 然后把同一个密码写进 .mcp.json 的 AGENT_WALLET_PASSWORD
+# 通过凭据管理器设置 Claude Code 启动环境中的 AGENT_WALLET_PASSWORD,并按上述手动创建配置引用该变量
# 4. 配合 Claude Code 使用
# 配置好 .mcp.json 后自然语言使用:
@@ -2745,19 +2946,17 @@ export TL_TRONGRID_URL="https://nile.trongrid.io"
### 兼容性与迁移策略
-- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更工具名、输入 schema、`error.code` 值或 `meta.schemaVersion` 语义。1.0 之后:标准 semver,仅 major 允许破坏。
+- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更工具名、输入 schema 或 `error.code` 值。1.0 之后:标准 semver,仅 major 允许破坏。
- **稳定契约**(patch 不会动):
- 工具名(`tl_chain_send`、`tl_chain_swap_v3`、`tl_multisig_*`、`tl_gasfree_*`、`tl_evaluate` 等)
- `error.code` 枚举(SSOT:[TronLink MCP Core 错误码](tronlink-mcp-core.md#error-codes))
- - `error.retryable` 语义
- - `meta.schemaVersion` 的 major 分量
- 必需环境变量名(`TL_TRONGRID_URL`、`TL_MULTISIG_SECRET_KEY`、`AGENT_WALLET_PASSWORD` 等)
- **不稳定契约**(随时可能变化):
- `message` 自然语言文本、日志行格式、stderr 输出
- 内部 Knowledge Store key(消费者不应解析)
- 预检查的错误 detail 文本(分支用 `code`,别用 `details.reason`)
-- **废弃窗口。** 工具或入参字段被废弃时,下一 minor 至少保留旧形式与新形式并存 **一个 minor 周期**,`list_tools` 会带 `meta.deprecated` 标记;移除最早在再下一周期。
-- **升级后校验。** 重新 `list_tools` 确认依赖的工具名 + `inputSchema` 仍在,再继续工作流;将 `meta.schemaVersion` 与会话开始时缓存的值对比。
+- **弃用检查。** [@tronlink/mcp-server-tronlink 0.1.1](https://www.npmjs.com/package/@tronlink/mcp-server-tronlink/v/0.1.1) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
+- **升级后校验。** 记录已安装的 Server 和 Core 版本,通过 `tools/list` 核对依赖的工具名和 `inputSchema`,再验证客户端能处理只读工具的 `ok: true` 和 `ok: false` 两种响应。
---
@@ -3122,7 +3321,7 @@ interface GasFreeCapability {
## 标准化响应格式
-所有工具返回一致的结构:
+[Core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) 的调用方先检查 `ok`,再读取 `result` 或 `error`。失败时读取 `error.code` 和 `error.message`,`error.details` 为可选字段。响应元数据包含 `timestamp`、`sessionId` 和 `durationMs`。
```typescript
// 成功
@@ -3131,7 +3330,7 @@ interface GasFreeCapability {
result: { /* 工具特定数据 */ },
meta: {
timestamp: "2026-03-09T10:15:23.456Z",
- sessionId: "tl-1741504523",
+ sessionId: "tl-1773051323",
durationMs: 234
}
}
@@ -3142,19 +3341,15 @@ interface GasFreeCapability {
error: {
code: "TL_CLICK_FAILED", // 稳定错误码 — 见下表
message: "Element not found",
- retryable: false, // 给 agent 的显式提示
- hint: "重新生成可达性快照并用新的 a11yRef 重试。",
details: { /* 可选 */ }
},
- meta: { timestamp, sessionId, durationMs, schemaVersion: "1.0" }
+ meta: { timestamp: "2026-03-09T10:15:23.456Z", sessionId: "tl-1773051323", durationMs: 234 }
}
```
-
-
### 错误码
-这是本框架所有工具返回错误码的**唯一数据源**(SSOT)。基于本框架的下游 server(`mcp-server-tronlink`)继承这些错误码并可扩展自有错误码;`mcp-tronlink-signer` 是独立的 server,不使用这些错误码。`retryable` 反映框架层面的安全性,agent 仍**必须**叠加调用工具的副作用分级——无论 `retryable` 为何,**结果未确认的 Remote Write 绝不能自动重试**。
+本表是 Core 错误码及其重试规则的唯一权威来源(SSOT)。根据返回的 `error.code` 查下表,判断是否可重试以及如何恢复。**Retryable** 和 **Hint** 是文档中的两列。Core 0.1.0 的响应不包含 `error.retryable`、`error.hint` 或 `meta.schemaVersion`。远程写操作结果未知时,先核对交易状态,再决定是否重试。基于 Core 的下游服务(如 `mcp-server-tronlink`)可以扩展此表;独立的 `mcp-tronlink-signer` 使用自己的错误格式。
| 错误码 | Retryable | Hint | 典型触发 |
|---|:---:|---|---|
@@ -3170,8 +3365,8 @@ interface GasFreeCapability {
| `TL_WAIT_TIMEOUT` | true | 提高超时或换一个 selector。 | `tl_wait_for`、`tl_wait_for_notification` |
| `TL_SCREENSHOT_FAILED` | true | 偶发故障;可重试。 | `tl_screenshot`、`tl_describe_screen` |
| `TL_CAPABILITY_NOT_AVAILABLE` | false | 当前 session 未注入该 capability;重配后重启。 | 依赖可选 capability 的工具 |
-| `TL_CHAIN_QUERY_FAILED` | true | TronGrid 暂时不可用或限流;退避后重试。 | `tl_chain_get_*` |
-| `TL_CHAIN_SEND_FAILED` | false | **禁止**自动重试。先用 `tl_chain_get_tx` 确认上一笔是否落账。 | `tl_chain_send`、`tl_chain_stake`、`tl_chain_resource` |
+| `TL_CHAIN_QUERY_FAILED` | true | TronGrid 暂时不可用或限流;退避后重试。**例外:** `tl_chain_resource` 的代理/取消代理写操作失败时也返回此码,应按 `TL_CHAIN_SEND_FAILED` 处理,先核对交易再决定是否重新发起。 | `tl_chain_get_*`、`tl_chain_resource` |
+| `TL_CHAIN_SEND_FAILED` | false | **禁止**自动重试。先用 `tl_chain_get_tx` 确认上一笔是否落账。 | `tl_chain_send`、`tl_chain_stake` |
| `TL_CHAIN_SWAP_FAILED` | false | 同上——重试前必须确认前一笔未落账。 | `tl_chain_swap`、`tl_chain_swap_v3` |
| `TL_GASFREE_QUERY_FAILED` | true | 偶发故障;可重试。 | `tl_gasfree_get_account`、`tl_gasfree_get_transactions` |
| `TL_GASFREE_SEND_FAILED` | false | **禁止**自动重试;先向 GasFree 查询最新状态。 | `tl_gasfree_send` |
@@ -3183,7 +3378,7 @@ interface GasFreeCapability {
下游 server 扩展自定义错误码必须满足:
- 不复用上表错误码表达不同含义。
-- 每个新错误码必须声明 `retryable`。
+- 为每个新增错误码写明重试条件和恢复步骤。
- major 版本内含义稳定。
- 新错误码在使用方文档说明,禁止悄悄引入。
@@ -3374,19 +3569,19 @@ npm run clean # 删除 dist/
### 兼容性与迁移策略
-本包是 `mcp-server-tronlink` 及任何下游 MCP server 在工具 schema、错误码、`meta.schemaVersion` 上的 **SSOT**,兼容面比普通库更宽:
+本包定义了 `mcp-server-tronlink` 及其他下游服务使用的工具 schema、错误码和响应结构。
- **语义化版本。** 1.0 之前:**minor** 升级可能改 `ISessionManager` 接口、能力 shape、`Tool[]` 注册顺序;**patch** 不会。1.0 之后:标准 semver,仅 major 允许破坏。
- **稳定契约**(patch 不会动):
- - `error.code` 枚举(导出为 `ERROR_CODES`,SSOT)——新增 code 非破坏;改名或删除是破坏。
- - `{ ok, result/error, meta }` 响应包络与 `meta.schemaVersion` 的 major 分量。
+ - `error.code` 枚举(导出为 `ErrorCodes`,SSOT)——新增 code 非破坏;改名或删除是破坏。
+ - `{ ok, result/error, meta }` 响应结构。
- 工具名与各工具 `inputSchema` 的**结构**——新增可选字段非破坏;改名或将字段改必填是破坏。
- 9 个能力接口(`OnChainCapability`、`MultiSigCapability`…)——新增可选方法非破坏。
- **不稳定契约**(随时可能变化):
- `src/internal/*` 下的内部 helper 导出、Knowledge Store key、recipe-runner 内部。
- 预检查错误 `details` 文本(分支用 `code`,别用 `details.reason`)。
-- **废弃窗口。** 废弃的工具 / 字段 / 能力方法在 `list_tools` 中带 `meta.deprecated` 标记,至少保留 **一个 minor 周期** 与替代并存,移除最早发生在再下一周期。
-- **下游升级。** 升级 `@tronlink/tronlink-mcp-core` 之前,先在下游对新 core 跑一遍 `list_tools` 快照测试;断言 `meta.schemaVersion` major 与你的 harness 编写时一致。
+- **弃用检查。** [@tronlink/tronlink-mcp-core 0.1.0](https://www.npmjs.com/package/@tronlink/tronlink-mcp-core/v/0.1.0) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
+- **下游升级。** 记录实际安装的包版本。用 `tools/list` 核对客户端依赖的工具名和输入 schema,再用只读工具的成功与失败响应检验客户端的处理逻辑。
---
@@ -3398,13 +3593,13 @@ npm run clean # 删除 dist/
**GitHub**: [https://github.com/TronLink/tronlink-skills](https://github.com/TronLink/tronlink-skills)
-> **版本范围。** 本页的命令说明(6 大技能、33 个命令)基于 **v1.0.x** 编写。默认分支(即 `git clone` 和 `install.sh` 安装的版本)现为 **v1.1.0**(commit `7d2d58cb`):新增 7 个只读命令(共 40 个),并要求精确版本 **Node.js 24.22.1**。详见文末「版本与许可证」;以你本地安装版本的 `tron_api.mjs --help` / MCP `tools/list` 为准。
+> **版本范围。** 本页的命令说明(6 大技能、33 个命令)基于 **v1.0.x** 编写。默认分支(即 `git clone` 和 `install.sh` 安装的版本)现为 **v1.1.0**(commit `b12b5868`):新增 7 个只读命令(共 40 个),并要求精确版本 **Node.js 24.22.3**。详见文末「版本与许可证」;以你本地安装版本的 `tron_api.mjs --help` / MCP `tools/list` 为准。
**TronLink Wallet Skills** 是一套 AI Agent 技能集,通过自然语言提供完整的 TRON 区块链钱包和 DeFi 功能。专为 Claude Code、Cursor、OpenCode、Codex CLI 及其他 AI 代理设计。
**核心亮点:**
- **6 大技能,33 个命令**,涵盖钱包、代币研究、市场数据、兑换、资源和质押
-- **零 npm 依赖**:使用原生 Node.js `fetch` 和 `crypto`(要求精确版本 Node.js 24.22.1,见下方「依赖项」),无需 `npm install`
+- **零 npm 依赖**:使用原生 Node.js `fetch` 和 `crypto`(要求精确版本 Node.js 24.22.3,见下方「依赖项」),无需 `npm install`
- **TRON 专属领域知识** — 专门处理能量 + 带宽资源模型
- **多平台支持** — Claude Code、Cursor、OpenCode、Codex CLI、LangChain/CrewAI
- **纯只读安全设计**:所有命令均为查询操作,不涉及私钥或签名
@@ -3435,7 +3630,7 @@ TronLink Skills 以深度 TRON 领域知识填补了这一空白。
AI 代理 (Claude Code / Cursor / OpenCode / 自定义)
|
v
-tron_api.mjs (Node.js 24.22.1, 原生 fetch, 零依赖)
+tron_api.mjs (Node.js 24.22.3, 原生 fetch, 零依赖)
├── 零 npm 依赖
├── TronGrid HTTP API(公共或带 API Key)
└── Tronscan API 用于代币元数据
@@ -3463,7 +3658,7 @@ tron_api.mjs (Node.js 24.22.1, 原生 fetch, 零依赖)
**特点:** 同时支持 Base58Check(T...)和 hex 地址格式,内置常用代币符号,自动转换精度。
-**何时不要用:** 发送 TRX / 代币——这些命令是只读的,请走 [signer SDK](tronlink-signer.md) 或 [MCP Server TronLink](mcp-server-tronlink.md)。代币层面的深度分析(rug-pull / 流动性锁定)请用 `tron-token`。
+**何时不要用:** 转出 TRX 或 TRC-20 代币并由用户在浏览器中批准时,使用 [Signer SDK](tronlink-signer.zh.md) 的 `sendTrx` 或 `sendTrc20`。使用本地 agent 钱包时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_send`。代币风险与流动性分析使用 `tron-token`。
### 2. tron-token(7 个命令)
@@ -3514,7 +3709,7 @@ DEX 兑换报价与路由优化。
**特点:** 聚合多源流动性、估算能量成本、处理多跳路由。
-**何时不要用:** 真正执行 swap——报价是只读的,实际兑换走 [MCP Server TronLink](mcp-server-tronlink.md)(`tl_chain_swap_v3`)或 signer SDK;历史成交数据——`tron-market`。
+**何时不要用:** 执行兑换时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_swap_v3`,将 `action` 设为 `"execute"`,并按用户确认的滑点百分比填写 `slippage`。历史成交数据使用 `tron-market`。
### 5. tron-resource(6 个命令)
@@ -3531,7 +3726,7 @@ DEX 兑换报价与路由优化。
**特点:** 成本优化决策树逻辑、追踪每日免费带宽、计算 TRX 燃烧等值。
-**何时不要用:** 真正冻结 TRX 获取能量/带宽——那是 Remote Write,请走 signer SDK / MCP Server;冻结后的 SR 投票策略——见 `tron-staking`。
+**何时不要用:** 冻结 TRX 获取能量或带宽时,调用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`,将 `action` 设为 `"freeze"`。投票前查询超级代表信息可使用 `tron-staking`。
### 6. tron-staking(3 个命令)
@@ -3545,15 +3740,13 @@ Stake 2.0 查询与 SR 信息。
**特点:** Stake 2.0 状态查询、APY 计算、SR 佣金追踪。
-**何时不要用:** 执行 freeze / 投票 / 解冻动作——这些是 Remote Write,请走 signer SDK / MCP Server;单次操作能量成本——`tron-resource`。
+**何时不要用:** 投票使用 [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink vote`,领取投票奖励使用同一 CLI 的 `tronlink reward`。冻结或解冻 TRX 使用 [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`。估算能量消耗使用 `tron-resource`。
---
-
-
## Skill ↔ MCP 工具映射
-`scripts/mcp_server.mjs`(即[方式二](#mcp)的封装)将 **33 个 CLI 命令中的 25 个** 暴露为 MCP 工具——签名、输入字段、输出结构都由同一份 `tron_api.mjs` 实现派生,因此 CLI 与 MCP 工具保证等价。剩余 8 个 CLI-only 命令仍可通过方式一(skill 提示词)和方式三(直接 CLI)使用。需要按用户提问路由到具体工具,或核对 `tools/list` 输出时,请用下表。
+在 v1.0.x 命令集中,`scripts/mcp_server.mjs` 将 **33 个 CLI 命令中的 25 个** 暴露为 MCP 工具。在默认分支提交 `b12b5868` 中,40 个命令里有 39 个暴露为 MCP 工具,只有 `swap-route` 仅限 CLI;下表中的“仅 CLI”标记针对 v1.0.x。包装层运行对应的 CLI 命令,以文本形式返回 MCP 工具结果。其余 8 个命令可通过 Skills 或 CLI 使用。
| Skill | CLI 命令 | MCP 工具名 | 副作用 | 可重试 |
|---|---|---|---|:---:|
@@ -3591,7 +3784,7 @@ Stake 2.0 查询与 SR 信息。
| `tron-staking` | `staking-info` | `tron_staking_info` | Network Read | 可 |
| `tron-staking` | `staking-apy` | `tron_staking_apy` | Network Read | 可 |
-**汇总。** 33 个 CLI 命令 · 25 个 MCP 工具 · 8 个仅 CLI 命令。所有命令都是只读——不签名、不广播、不动资金。若需执行交易,请路由到 [MCP Server TronLink](mcp-server-tronlink.md)(`tl_chain_*`)或 [signer SDK](tronlink-signer.md)(`sendTrx`、`sendTrc20`、`sign*`)。
+上表涵盖 v1.0.x 的 33 个只读 CLI 命令,其中 25 个也可通过 MCP 调用。需要发起交易时,按下方路由示例选择工具。
### 用户提问 → Skill → 工具路由
@@ -3625,16 +3818,16 @@ Stake 2.0 查询与 SR 信息。
### ❌ 不要走这里(反例)
-Skills 是**只读**的。如果用户意图涉及签名或 Remote Write,**不要**派发到 skill——底层命令会成功,但只是做了查询/估算,用户真正的目标并没有完成。这种意图请改路由到 signer SDK 或 `mcp-server-tronlink`:
+Skills 提供查询和估算。涉及签名或广播时,按下表选择工具。[TronLink CLI](tronlink-cli.zh.md) 和 signer SDK 通过浏览器请求用户批准。MCP Server 的直连链上工具使用本地 agent 钱包签名,宿主应用须在调用前取得用户确认。
| 用户提问(意图) | ❌ 误路由(看起来合理,但只读) | ✅ 正确路由 |
|---|---|---|
-| 「给 `T…` 转 100 TRX」 | `tron-wallet wallet-balance` 就停下——只查了余额,没转。 | [signer SDK](tronlink-signer.md) `sendTrx`(HITL)或 [`mcp-server-tronlink`](mcp-server-tronlink.md) `tl_chain_send` |
-| 「冻 1000 TRX 换能量」 | `tron-resource optimize-cost`——只算了建议,没冻。 | `mcp-server-tronlink` `tl_chain_stake`(Remote Write、HITL) |
-| 「给 SR `T…` 投 5000 票」 | `tron-staking sr-list`——只读了 SR 列表,没投票。 | `mcp-server-tronlink` `tl_chain_stake` / signer SDK `signTransaction` |
-| 「给 SunSwap 路由器授权 USDT 额度」 | `tron-token token-info` / `contract-info`——纯元数据查询,没发送 approve。 | [signer SDK](tronlink-signer.md) `signTransaction` 或 `mcp-server-tronlink` `tl_chain_send` |
-| 「现在把 100 TRX 换成 USDT」 | `tron-swap swap-quote`——只报了价,没执行。 | `mcp-server-tronlink` `tl_chain_swap_v3`(Remote Write、HITL,必传 `minOut`) |
-| 「领我的质押奖励」 | `tron-staking staking-info`——只看了待领数量。 | `mcp-server-tronlink` `tl_chain_stake`(withdraw / claim)或 signer SDK |
+| 「给 `T…` 转 100 TRX」 | `tron-wallet wallet-balance` 就停下——只查了余额,没转。 | [signer SDK](tronlink-signer.zh.md) `sendTrx`(HITL)或 [`mcp-server-tronlink`](mcp-server-tronlink.zh.md) `tl_chain_send` |
+| 「冻 1000 TRX 换能量」 | `tron-resource optimize-cost`——只算了建议,没冻。 | [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_stake`(`action="freeze"`,`amount_trx=1000`,`resource="ENERGY"`) |
+| 「给 SR `T…` 投 5000 票」 | `tron-staking sr-list`——只读了 SR 列表,没投票。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink vote --votes :5000`。投票会替换该账户当前的全部投票;如需保留对其他 SR 的投票,请在同一条命令中一并列出。 |
+| 「给 SunSwap 路由器授权 USDT 额度」 | `tron-token token-info` / `contract-info`——纯元数据查询,没发送 approve。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink trigger --contract --method 'approve(address,uint256)' --args '["","1000000"]'`。代币合约和路由器地址须对应所选网络。路由器是被授权方;USDT 精度为 6 时,`1000000` 表示授权 1 USDT。 |
+| 「现在把 100 TRX 换成 USDT」 | `tron-swap swap-quote`——只报了价,没执行。 | [mcp-server-tronlink](mcp-server-tronlink.zh.md) 的 `tl_chain_swap_v3`(`action="execute"`,`slippage` 填用户确认的滑点百分比) |
+| 「领取我的投票奖励」 | `tron-staking staking-info`——只看了待领数量。 | [TronLink CLI](tronlink-cli.zh.md) 的 `tronlink reward` |
**判断口诀。** 用户动词只要出现 *send / freeze / unfreeze / vote / unvote / approve / swap(执行)/ claim / sign / broadcast*,答案就**不在**这个 Skills 集里起步。Skills 仍然可以做**前置**(报价、估算成本、校验地址、查余额)——只是别声称"Skills 调用完成了用户的请求"。
@@ -3688,8 +3881,8 @@ tron-resource(检查状态)→ tron-resource(估算成本)→ tron-resou
- 冻结 TRX → 获取能量或带宽 → 投票给 SR → 赚取奖励
- 解冻需 **14 天等待期** 才能提取
- 解冻后投票重置;重新冻结后需重新投票
-- 1 冻结 TRX ≈ 每天 4.5 能量——**动态值**:取决于全网总质押量;实时数请用 `tron-resource estimate-energy`。数据截至 2026-05。
-- 投票奖励每 6 小时可领取一次
+- 质押所得能量取决于目标网络当前的质押总量。用该网络的 `TotalEnergyLimit / TotalEnergyWeight` 估算每质押 1 TRX 可获得的额度。`estimate-energy` 用于估算合约调用消耗。[GetAccountResource](https://developers.tron.network/reference/getaccountresource)
+- 投票奖励每 24 小时可领取一次
---
@@ -3699,8 +3892,11 @@ tron-resource(检查状态)→ tron-resource(估算成本)→ tron-resou
```bash
# 克隆后直接使用
-git clone
+# v1.1.0 需要 Git、nvm 和 Node.js 24.22.3;交互步骤还需安装 Claude Code。
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
claude # 自动发现 SKILL.md 文件
```
@@ -3712,8 +3908,8 @@ claude # 自动发现 SKILL.md 文件
# 注册为 MCP 服务器
claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
-# 提供 25 个 MCP 工具,可被 Claude Desktop / Claude Code 直接调用
-# (逐项对照见上文 "Skill ↔ MCP 工具映射";剩余 8 个命令仅 CLI 可用)
+# b12b5868 提供 39 个 MCP 工具(v1.0.x 为 25 个),可被 Claude Desktop / Claude Code 直接调用
+# (b12b5868 中只有 swap-route 仅限 CLI;v1.0.x 的逐项对照见上文 "Skill ↔ MCP 工具映射")
```
### 方式三:命令行直接使用
@@ -3721,10 +3917,16 @@ claude mcp add tronlink -- node ~/.tronlink-skills/scripts/mcp_server.mjs
```bash
# 直接执行命令
node scripts/tron_api.mjs wallet-balance --address T地址...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs swap-quote --from TRX --to USDT --amount 100
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs swap-quote --from-token TRX --to-token USDT --amount 100
```
+#### 处理 Skills CLI 和 MCP 错误
+
+在 Skills v1.1.0(`b12b5868`)中,未知 CLI 命令或缺少必填参数会向 stderr 输出原因,并以 `1` 退出。命令也可能以 `0` 退出,同时在 stdout 返回错误。例如,`staking-apy --amount 0` 返回的 JSON 包含 `error`、`status: 400` 和 `parameter: "amount"`。调用查询命令时,先检查退出码,再解析 stdout 中的 JSON;确认没有 `error` 后再使用结果。[Skills CLI 实现](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/tron_api.mjs)
+
+通过 MCP 调用 `tools/call` 时,先检查 JSON-RPC 错误(未知工具返回 `-32602`)。对于已识别的工具,再解析 `result.content[0].text` 中的 JSON,检查其中的 `error` 字段。包装层可以在这段文本中返回命令错误,同时省略 `isError` 标记。[Skills MCP 实现](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/scripts/mcp_server.mjs)
+
### 方式四:其他 AI 平台
| 平台 | 集成方式 |
@@ -3781,7 +3983,10 @@ def tron_call(cmd: str) -> dict:
["node", "scripts/tron_api.mjs", *cmd.split()],
cwd="/absolute/path/to/tronlink-skills",
)
- return json.loads(out)
+ result = json.loads(out)
+ if isinstance(result, dict) and "error" in result:
+ raise RuntimeError(result["error"])
+ return result
tron_wallet_balance = Tool.from_function(
func=lambda addr: tron_call(f"wallet-balance --address {addr}"),
@@ -3879,7 +4084,7 @@ tronlink-skills/
| 依赖 | 是否必需? | 用途 |
|------|-----------|------|
-| Node.js 24.22.1(精确版本;默认分支 v1.1.0) | 是 | 运行时(原生 fetch、crypto)。默认分支通过 `.nvmrc` 与 `package.json` 的 `engines` 固定该版本;`install.sh` 检测到其他版本会直接报错退出。安装前先执行 `nvm install 24.22.1 && nvm use 24.22.1`。 |
+| Node.js 24.22.3(精确版本;默认分支 v1.1.0) | 是 | 运行时(原生 fetch、crypto)。默认分支通过 `.nvmrc` 与 `package.json` 的 `engines` 固定该版本;`install.sh` 检测到其他版本会直接报错退出。安装前先执行 `nvm install 24.22.3 && nvm use 24.22.3`。 |
| npm install | 不需要 | 所有操作均无需安装任何 npm 依赖 |
---
@@ -3892,7 +4097,7 @@ tronlink-skills/
| 副作用 | 每个命令都是 **Network Read**:调用公共 API,但不改变任何状态。所有命令均可安全重试,无需人工确认(HITL) |
| 无需密钥 | 仅可选 TRONGRID_API_KEY 用于提高请求频率 |
| 频率限制 | 公共 TronGrid API;使用 TRONGRID_API_KEY 获取更高限额 |
-| 错误处理 | 失败均为查询类错误:限流(可重试,需退避)、网络错误(可重试)、地址/参数非法(不可重试——修正输入)。如需执行交易(转账、兑换、质押),请使用 [signer SDK](tronlink-signer.md) 或 [MCP Server TronLink](mcp-server-tronlink.md)——这些技能本身从不签名或广播 |
+| 错误处理 | 失败均为查询类错误:限流(可重试,需退避)、网络错误(可重试)、地址/参数非法(不可重试——修正输入)。 |
---
@@ -3923,28 +4128,31 @@ tronlink-skills/
```bash
# 1. 克隆
-git clone
+# v1.1.0 需要 Git、nvm 和 Node.js 24.22.3;交互步骤还需安装 Claude Code。
+git clone https://github.com/TronLink/tronlink-skills.git
cd tronlink-skills
+git checkout b12b5868
+nvm install && nvm use
# 2. 配合 Claude Code 使用(只读操作无需安装)
claude
-> "查一下 T地址... 的 TRX 余额"
-> "展示 TRON 上最热门的代币"
-> "发送 USDT 需要多少能量?"
-> "获取能量最好的方式是什么——冻结、租赁还是燃烧?"
+# "查一下 T地址... 的 TRX 余额"
+# "展示 TRON 上最热门的代币"
+# "发送 USDT 需要多少能量?"
+# "获取能量最好的方式是什么——冻结、租赁还是燃烧?"
-# 3. 或直接使用命令行
-node scripts/tron_api.mjs wallet-balance --address T地址...
-node scripts/tron_api.mjs token-price --token USDT
-node scripts/tron_api.mjs optimize-cost --address T地址...
+# 3. 也可在 shell 中直接执行。将 ACCOUNT 设为待查询地址。
+node scripts/tron_api.mjs wallet-balance --address "${ACCOUNT:?set ACCOUNT}"
+node scripts/tron_api.mjs token-price --contract USDT
+node scripts/tron_api.mjs optimize-cost --address "${ACCOUNT:?set ACCOUNT}"
```
## 版本与许可证
- **包:** `tronlink-skills` v1.0.1——本页命令表所描述的版本。
-- **默认分支:** v1.1.0(commit `7d2d58cb`,`package.json` 中 `version: 1.1.0`),`git clone` / `install.sh` 安装的就是该版本。与 v1.0.1 相比,影响 agent 的差异:
- - 新增 7 个只读命令(同时以 `tron_` 形式暴露为 MCP 工具):`wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`。共 40 个命令,仍全部为 Network Read。
- - Node.js 固定为精确版本 24.22.1(`.nvmrc`、`engines`);`install.sh` 检测到其他版本会直接退出。
+- **默认分支:** v1.1.0(commit `b12b5868`,`package.json` 中 `version: 1.1.0`),`git clone` / `install.sh` 安装的就是该版本。与 v1.0.1 相比,影响 agent 的差异:
+ - 新增 7 个只读命令(同时以 `tron_` 形式暴露为 MCP 工具)。该提交中 `mcp_server.mjs` 将 40 个命令中的 39 个暴露为 MCP 工具,只有 `swap-route` 仅限 CLI。新增命令:`wallet-approvals`, `wallet-overview`, `token-overview`, `bandwidth-price`, `tx-cost`, `chain-params`, `health-check`。共 40 个命令,仍全部为 Network Read。
+ - 此提交的 [`.nvmrc`](https://github.com/TronLink/tronlink-skills/blob/b12b58685ec38febc21843d2173dd43d969b8eb0/.nvmrc) 指定 Node.js 24.22.3。复现[旧提交 `7d2d58cb`](https://github.com/TronLink/tronlink-skills/blob/7d2d58cb/.nvmrc) 时使用 Node.js 24.22.1。在检出的仓库根目录运行 `nvm install && nvm use`,即可按该提交的配置选择版本。
- **许可证:** MIT —— `SPDX-License-Identifier: MIT`
- **变更记录 / 发布:** [https://github.com/TronLink/tronlink-skills/releases](https://github.com/TronLink/tronlink-skills/releases) —— 截至当前 v1.0.x 尚无 GitHub tag 发布;打 tag 之前请直接看 commit 历史。
@@ -3955,13 +4163,12 @@ Skills 已进入 **v1.0.x**,适用标准 semver——只有 **major** 升级
- **稳定契约**(minor / patch 不会动):
- 33 个 CLI 命令名与其必填 / 可选 flag(`tron_api.mjs [...]`)。
- [Skill ↔ MCP 工具映射](#skill-mcp-tool-map) 列出的 25 个 MCP 工具名(`tron_*` 形式)及其 `inputSchema` 字段名。
- - Exit code:`0` 成功,`1` 查询错误 / 参数非法,`2` 未支持 / 未知命令。
- `Network Read` 副作用分级——任何命令未经 major 升级都不会变成 Remote Write。
- **不稳定契约**(minor 允许变化):
- JSON `stdout` 输出的具体字段——新增字段任意 minor 都允许;改名或删除属于 major。请用宽容解析。
- 内置代币 symbol 快捷表(`USDT`、`USDC`、`WTRX`…)——minor 允许新增 symbol;已存在的映射 minor 不会重指。
- 启发式与阈值(`whale-transfers` 默认阈值、`optimize-cost` 决策树权重等)。
-- **子集关系。** MCP 工具子集(目前 25 / 33)可能在 minor 中 **扩大**(CLI-only 命令被新增为 MCP 工具);不会在 minor 中 **缩小**。
+- **子集关系。** MCP 工具子集(v1.0.x 为 25 / 33;`b12b5868` 为 39 / 40)可能在 minor 中 **扩大**(CLI-only 命令被新增为 MCP 工具);不会在 minor 中 **缩小**。
- **废弃窗口。** 被标 deprecated 的命令 / 工具至少在 **一个 minor 周期** 内继续可用;移除最早发生在下一个 major。
- **升级后校验。** 重新 `tron_api.mjs --help`,使用 MCP 时再跑 `tools/list`,确认依赖的名字仍在。MCP `initialize` 阶段返回的 `serverInfo.version` 应与升级后的 `package.json` 版本一致。
@@ -4096,8 +4303,6 @@ claude mcp add -s user tronlink-signer -- node /path/to/packages/mcp-tronlink-si
当调用 `sign_transaction` 且 `broadcast: true` 时,服务器会在广播后自动轮询链上确认状态,并返回执行结果(`success`、`pending` 或 `failed`)。如果交易在链上失败(如 `OUT_OF_ENERGY`、Solidity revert),结果为 `status: "failed"`,`error` 中带解码后的原因,并标记 `isError: true`。
-
-
## 错误
v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一段文本 `Error: `,没有结构化的 `code` 或 `retryable` 字段。已知的消息如下:
@@ -4120,14 +4325,12 @@ v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一
|---|---|---|
| **Prompt 注入** | 工具输入按原始值作为调用参数,server 不会再次提交给 LLM。TronLink 审批页渲染的是解析后的交易字段,不是 agent 的自由文本。 | 链上拿到的字符串(备注、revert 原因)视为不可信;分支应基于 `txId` / `status`,而非 prose。 |
| **本地 HTTP listener** | 本地审批 server **仅绑定 `127.0.0.1`**(端口 `TRON_HTTP_PORT`,默认 3386,被占用时自增),永远不接受跨主机连接。每个 server session 有唯一 ID,前一次 session 的浏览器标签会被自动失效。 | 不要把 3386 端口转发到外网。同一台机器不要用相同 `TRON_HTTP_PORT` 跑两份。 |
-| **出站 host 白名单(SSRF)** | signer 只与 [Networks](#environment-variables) 列出的 TronGrid 端点以及本地浏览器通信,工具不接受会被原样请求的用户 URL。 | 生产环境钉死 `TRON_NETWORK`、`TRON_API_KEY`。 |
+| **出站 host 白名单(SSRF)** | signer 只与 [网络端点](../reference/networks.md#networks) 列出的 TronGrid 端点以及本地浏览器通信,工具不接受会被原样请求的用户 URL。 | 生产环境钉死 `TRON_NETWORK`、`TRON_API_KEY`。 |
| **API key 处理(token passthrough)** | `TRON_API_KEY` 仅在启动时从 env 读取,仅用于到 TronGrid 的出站;**不**会出现在任何工具响应、错误 `details` 或 MCP resource 中。server 不接受 MCP 客户端传入的 Authorization header 并转发到上游。 | API key 放进 MCP host 的 secret manager,不要写进会提交 git 的 `mcpServers` 配置。 |
| **签名必须 HITL** | 所有签名工具(`send_trx`、`send_trc20`、`sign_message`、`sign_typed_data`、`sign_transaction`)都会打开 TronLink 审批页,**不存在程序化绕过**。私钥始终留在 TronLink。 | 不需要运维额外强制 HITL——这是结构性保证。不要试图通过移除浏览器层来"加固"。 |
| **浏览器标签劫持** | 审批页基于 server session ID 验证每次请求,过期的标签会被忽略;心跳检测会在断连时关闭 session。 | 同一用户跑多个 agent 时,请让每个 agent 启动自己的 signer 实例;跨实例的请求串扰由 session ID 屏蔽,但 UI 层混淆不防。 |
| **Confused deputy** | signer 以已连接的 TronLink 账户身份执行,没有来自 MCP 客户端的逐次授权 scope。 | 一个 signer 实例 = 一个 TronLink 账户,不要把多个终端用户复用到同一个实例。 |
-
-
## 环境变量
| 变量名 | 说明 | 默认值 |
@@ -4142,8 +4345,6 @@ v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一
- **许可证:** MIT —— `SPDX-License-Identifier: MIT`
- **变更记录 / 发布:** [https://github.com/TronLink/mcp-tronlink-signer/releases](https://github.com/TronLink/mcp-tronlink-signer/releases)
-
-
### 内联 changelog
本页是下游 README 镜像;以 GitHub releases 与各包 `CHANGELOG.md` 为准。下方条目只覆盖 **MCP 可见面**(工具、schema、安全边界),内部重构不列。
@@ -4178,7 +4379,7 @@ v0.1.4 中,错误以 MCP 工具结果返回:`isError: true`,内容是一
### 兼容性与迁移策略
- **语义化版本。** 1.0 之前:**minor** 升级(0.x → 0.y)允许破坏性变更;**patch** 升级(0.1.x → 0.1.y)不变更 MCP 工具名或输入 schema。1.0 之后:标准 semver,仅 major 允许破坏。
-- **废弃窗口。** 当某工具或入参字段被废弃时,下一 minor 至少保留旧形式与新形式并存 **一个 minor 周期**,schema 内置 `meta.deprecated` 标记;移除最早发生在再下一周期。
+- **弃用检查。** [mcp-tronlink-signer 0.1.4](https://www.npmjs.com/package/mcp-tronlink-signer/v/0.1.4) 的已注册工具没有弃用标记。升级前请查阅目标版本的发布说明,并用 `tools/list` 比对依赖的工具名称和输入字段。
- **稳定契约。** 工具名、`status` 值(`success` / `pending` / `failed`)属于公开面,patch 不会动。
- **不稳定契约。** 错误 `message` 文本(匹配[错误](#errors)中列出的已知取值,其他按未知处理)、日志行格式、审批页的视觉布局 **不属于** 公开面,随时可能变化。
- **升级后校验。** 升级后 **必须** 重新 `list_tools` 确认你依赖的名字 + schema 仍存在,再继续工作流。
@@ -4201,18 +4402,26 @@ npm install tronlink-signer
## 快速开始
+在 Nile 选择有测试币的账户,并将 Node.js 环境变量 `RECIPIENT` 设为测试收款地址。此示例会请求授权转出 1 个测试 TRX。
+
```ts
import { TronSigner } from "tronlink-signer";
+const recipient = process.env.RECIPIENT;
+if (!recipient) throw new Error("Set RECIPIENT to the Nile recipient address");
const signer = new TronSigner();
await signer.start();
-const { address, network } = await signer.connectWallet();
-const { txId, status } = await signer.sendTrx("TXxx...", 1); // status: "success" | "pending" | "failed"
-const { txId: txId2, status: s2 } = await signer.signTransaction(tx, "nile", true); // 广播 + 自动确认
-const { balance } = await signer.getBalance("TXxx...");
-
-await signer.stop();
+try {
+ const { address } = await signer.connectWallet("nile");
+ const { balance } = await signer.getBalance(address, "nile");
+ console.log(address, balance);
+ // Signer 以 TRX 为单位,这里发送 1 TRX。
+ const { txId, status } = await signer.sendTrx(recipient, 1, "nile");
+ console.log(txId, status);
+} finally {
+ await signer.stop();
+}
```
## API
@@ -4291,26 +4500,50 @@ const { signature } = await signer.signTypedData({
| `broadcast` | `boolean` | 签名后是否广播(默认:`false`) |
| `options` | `SignerOptions` | 可选 — 取消、确认控制、广播回调 |
-```ts
+在 Node.js 中构建 Nile 未签名转账前,请安装 `tronlink-signer` 和 `tronweb@6`,在 TronLink 选择有测试币的 Nile 付款账户,并将 `RECIPIENT` 设为预期的 Nile 收款地址。在同一个 ES 模块中运行以下准备代码,再选一种调用方式。
+
+```js
+import { TronSigner } from "tronlink-signer";
+import { TronWeb } from "tronweb";
+
+const signer = new TronSigner();
+const tronWeb = new TronWeb({ fullHost: "https://nile.trongrid.io" });
+const recipient = process.env.RECIPIENT;
+if (!TronWeb.isAddress(recipient)) throw new Error("Set RECIPIENT to a TRON address");
+await signer.start();
+const { address } = await signer.connectWallet("nile");
+// 交易构建器以 SUN 为单位,这里构建 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+const tx = await tronWeb.transactionBuilder.sendTrx(recipient, 10, address);
+```
+
+以下为不同调用方式,请选择一种使用。
+
+```js
// 仅签名
-const { signedTransaction } = await signer.signTransaction(tx);
+const { signedTransaction } = await signer.signTransaction(tx, "nile");
+```
+```js
// 签名、广播并等待确认(默认行为)
const { signedTransaction, txId, status, error } = await signer.signTransaction(tx, "nile", true);
// status === "success" — 已在链上确认
// status === "pending" — 广播成功但在超时时间内未被确认
// status === "failed" — 链上执行失败;`error` 包含失败原因
+```
+```js
// 广播但不等待确认
const result = await signer.signTransaction(tx, "nile", true, { confirm: false });
+```
+```js
// 在交易进入内存池时立即收到通知
const result = await signer.signTransaction(tx, "nile", true, {
onBroadcasted: ({ txId }) => console.log("Broadcast:", txId),
});
```
-
+参照快速开始,用 `try / finally` 包住连接、构建及所选调用,在 `finally` 中执行 `await signer.stop()`。广播结果未知时先按交易 ID 查询状态。
### 广播结果
@@ -4765,6 +4998,8 @@ tronlink transfer --type trx --toAddress TYqx5gm3p3wLDE9Bv8TBJAbK4ELNbSLfJV --am
若网络抖动导致 CLI 本地广播与签名器残留的广播都打到节点(例如断线重连、同一 nonce 的两次 CLI 调用),第二次提交会被节点拒绝——TRON 节点按交易 ID 去重,结果只会是一次入块 + 一次 `DUP_TRANSACTION_ERROR` 类失败,绝不会出现两次链上效果。已确认入块后再看到此类错误视为良性;尚未确认前出现则按结果未知的网络失败处理(CLI 退出 `1`),先用区块浏览器核对再决定是否重试。
+## 输入校验
+
所有输入在连接 TronLink 前会进行校验:
- **金额**:仅支持非负数字,不允许科学计数法或多个小数点
@@ -4842,7 +5077,10 @@ v1.0.1 在 `--json` 模式下将失败信息写入 **stderr**,并以 `1` 退
2. 对于带 `--address` 的读操作:直接通过 TronGrid 查询
3. 对于写操作或不带 `--address` 的读操作:连接 TronLink 浏览器扩展以获取钱包信息
4. 使用本地 TronWeb `transactionBuilder` 构建未签名交易
-5. Pre-flight 校验:所有写命令(transfer、stake、unstake、delegate、reclaim、vote、trigger)在签名前会执行此步——校验 TRX / 代币 / 已质押 / 已委托余额,模拟合约调用以捕获 revert,估算能量与带宽消耗,校验 SR 地址(vote)、NFT 所有权(TRC721)、委托解锁时间(reclaim)
+5. Pre-flight 校验:以下命令(transfer、stake、unstake、delegate、reclaim、vote、trigger)在签名前会执行此步——校验 TRX / 代币 / 已质押 / 已委托余额,模拟合约调用以捕获 revert,估算能量与带宽消耗,校验 SR 地址(vote)、NFT 所有权(TRC721)、委托解锁时间(reclaim)
+
+ v1.0.1 中,`withdraw` 查询付款账户的 `unfrozenV2`,没有到期可提取的 TRX 时在签名前报错。`reward` 调用 `getReward(address)`,金额小于等于零时直接结束(JSON 状态为 `No Rewards`)。任一查询失败都会在签名前终止命令。
+
6. 将交易发送给 TronLink 进行签名(浏览器授权页面)
7. 广播:默认由签名器广播;使用 `--local-broadcast` 时由 CLI 在本地广播。两种模式下 CLI 都会轮询 `getUnconfirmedTransactionInfo` 直至交易被打包入块(约 3 秒),并将 OUT_OF_ENERGY / REVERT / FAILED 作为错误抛出
8. 输出结果
@@ -4946,11 +5184,15 @@ tronlink reward --json
### 示例:AI 转账流程
```bash
-# 1. 先查询余额
-tronlink balance --address TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL --network mainnet --json
+# 将 PAYER 设为 TronLink 当前付款地址,RECIPIENT 设为收款地址。
+# 若账户或网络变化,请取消操作,重新查询实际付款账户的余额。
+NETWORK=mainnet
+
+# 1. 查询付款账户余额
+tronlink balance --address "${PAYER:?set PAYER}" --network "$NETWORK" --json
# 2. 发送 10 TRX(会打开浏览器签名,需等待返回)
-tronlink transfer --type trx --toAddress TRecipientAddress --amount 10 --network mainnet --json
+tronlink transfer --type trx --toAddress "${RECIPIENT:?set RECIPIENT}" --amount 10 --network "$NETWORK" --json
# 3. 验证结果 — 输出包含 txId 和浏览器链接
# { "Status": "Success", "TxID": "abc...", "Explorer": "https://tronscan.org/#/transaction/abc..." }
@@ -5060,50 +5302,124 @@ try {
## 查询账户的 active permissions
-`multiSign` 需要传入一个**有效的** `permissionId`。账户的 active permissions 通过 `tronWeb.trx.getAccount(address)` 返回的 `active_permission[]` 数组取得,每个 entry 暴露 `id`、`permission_name`、`threshold` 以及 `keys[]`(地址 + 权重)。owner 权限 id 固定为 `0`,在 `owner_permission` 字段下单独返回。
+选择持有资金的账户。如果当前签名人就是 owner,可使用其地址;共同签名人应填写被控制账户的地址。在交易所属网络查询该 owner 的权限,选择包含签名人且允许 TRX 转账的活动权限,使用该条目自身的 `id`。
```javascript
const tronweb = window.tron.tronWeb;
-const account = await tronweb.trx.getAccount(tronweb.defaultAddress.base58);
-// account.active_permission 是数组——挑选 keys[] 里包含你要签名地址、
-// 且 weight + threshold 足够覆盖本次交易的 id。
-const activePermissions = account.active_permission ?? [];
-console.log(activePermissions.map(p => ({ id: p.id, name: p.permission_name, threshold: p.threshold })));
+const owner = "REPLACE_WITH_OWNER_ADDRESS";
+const account = await tronweb.trx.getAccount(owner);
+console.table(account.active_permission);
```
-把查出来的 `id` 作为下面的 `permissionId` 传入。
-
## 技术规范
-### 代码示例
+### 签名并检查累计权重
+
+在交易所用网络上,将已授权的 TronWeb 实例传给以下函数。广播前,由节点根据交易 owner 当前的权限检查签名。[GetSignWeight](https://developers.tron.network/reference/getsignweight)
```javascript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TRKb2nAnCBfwxnLxgoKJro6VbyA6QmsuXq";
-// fromAddress = 资金所在、由该 active 权限控制的账户(交易 owner)。
-// 它不一定是当前连接的签名账户:若当前账户只是该权限 keys[] 里的共同签名人,
-// 请把 fromAddress 改成被控制的账户地址。
-const fromAddress = tronweb.defaultAddress.base58;
-const activePermissionId = 2; // 通过 tronWeb.trx.getAccount(fromAddress).active_permission 查出
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId }
-); // 步骤1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- const res = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- if (!res.result) {
- // 节点拒绝以返回值给出,不会抛异常——见下方错误码。
- console.error(res.code, res.message && tronweb.toUtf8(res.message));
+function validateSignWeight(check, permissionId) {
+ const { permission, result, current_weight: weight } = check ?? {};
+ if (result?.code === "PERMISSION_ERROR") throw new Error("请核对交易 owner 和权限");
+ if (!result || typeof result !== "object" || Array.isArray(result) ||
+ !permission || !Number.isSafeInteger(permission.threshold) ||
+ permission.threshold <= 0 || !Number.isSafeInteger(weight) || weight < 0 ||
+ !/^[0-9a-f]{64}$/i.test(permission.operations)) {
+ throw new Error("无法确认权限或累计权重");
+ }
+ // 活动权限位图中的第 1 位对应 TransferContract。
+ const allowsTransfer = (parseInt(permission.operations.slice(0, 2), 16) & 2) !== 0;
+ if (permission.type !== "Active" || permission.id !== permissionId || !allowsTransfer) {
+ throw new Error("请核对交易 owner 和权限");
+ }
+ return { code: result.code, weight, threshold: permission.threshold };
+}
+
+async function checkAndBroadcast(tronweb, signedTx, permissionId) {
+ const check = await tronweb.trx.getSignWeight(signedTx);
+ const { code, weight, threshold } = validateSignWeight(check, permissionId);
+ if (code === "NOT_ENOUGH_PERMISSION" && weight < threshold) {
+ return { status: "collect", signedTx };
+ }
+
+ // 节点可能省略默认的 ENOUGH_PERMISSION 状态码。
+ if ((code !== undefined && code !== "ENOUGH_PERMISSION") || weight < threshold) {
+ throw new Error("签名权重检查失败");
+ }
+
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) {
+ const message = receipt.message ? tronweb.toUtf8(receipt.message) : "";
+ throw new Error([receipt.code, message].filter(Boolean).join(" ") || "广播被拒绝");
+ }
+ return { status: "submitted", txID: signedTx.txID };
+}
+
+async function signAndCheck(tronweb, tx) {
+ const permissionId = tx.raw_data.contract[0].Permission_id;
+ if (!Number.isSafeInteger(permissionId) || permissionId < 2) {
+ throw new Error("请填写有效的活动权限 ID");
+ }
+
+ let signedTx;
+ try {
+ signedTx = await tronweb.trx.multiSign(tx, undefined, permissionId);
+ } catch (error) {
+ if (error === "Confirmation declined by user") return { status: "declined" };
+ throw error;
}
-} catch (e) {}
+
+ return checkAndBroadcast(tronweb, signedTx, permissionId);
+}
```
-如果用户在弹窗中选择【拒绝】,则会抛出异常,开发者可捕获此异常进行业务处理。
+### 第一位签名人
-如果用户在弹窗中选择【签名】,DApp 可以拿到签名后的交易,继续进行广播。
+替换收款地址,并填写上面从交易 owner 的活动权限中选出的 ID。
+
+```javascript
+const recipient = "REPLACE_WITH_RECIPIENT_ADDRESS";
+const permissionId = 2; // 替换为所选活动权限的 ID。
+if (!account.active_permission?.some(p => p.id === permissionId)) {
+ throw new Error("请选择交易 owner 的活动权限");
+}
+
+// 构建一笔 10 SUN 的转账(1 TRX = 1_000_000 SUN)。
+const tx = await tronweb.transactionBuilder.sendTrx(recipient, 10, owner, { permissionId });
+const outcome = await signAndCheck(tronweb, tx);
+```
+
+### 后续共同签名人
-注意:此次调用只收集**一个**签名——完整的多签交易需要凑齐 `threshold`,通常对应**多次** `multiSign` 调用(每个 co-signer 一次)。在凑齐前应在链下(或通过 MCP 的 `tl_multisig_*` 工具)跟踪部分签名的交易,凑齐后再广播。
+结果为 `collect` 时,通过 DApp 的交接流程将其中的 `signedTx` 传给下一位有权限的共同签名人。每位共同签名人在同一网络连接钱包。签名前,先确认交易数据与其 `txID` 一致,再解析 owner、收款地址、金额和过期时间并展示给共同签名人,确认无误后再继续。调用 `coSignTransfer` 时传入收到的交易对象,以及一个在共同签名人确认后返回 `true` 的 `confirmTransfer` 回调。`signAndCheck` 会在该对象上调用 `multiSign`,保留已有签名和交易 ID。
+
+```javascript
+function describeTransfer(tronweb, tx) {
+ // 签名针对 txID,展示前先确认 raw_data 的哈希与其一致。
+ const txCheck = tronweb.utils?.transaction?.txCheck;
+ if (!txCheck || !txCheck(tx)) throw new Error("交易数据与 txID 不一致");
+ const contract = tx.raw_data.contract[0];
+ if (contract.type !== "TransferContract") throw new Error("不是 TRX 转账");
+ const { owner_address, to_address, amount } = contract.parameter.value;
+ return {
+ owner: tronweb.address.fromHex(owner_address),
+ recipient: tronweb.address.fromHex(to_address),
+ amount: `${tronweb.fromSun(amount)} TRX`,
+ permissionId: contract.Permission_id,
+ expires: new Date(tx.raw_data.expiration).toISOString(),
+ };
+}
+
+async function coSignTransfer(partiallySignedTx, confirmTransfer) {
+ const tronweb = window.tron.tronWeb;
+ const details = describeTransfer(tronweb, partiallySignedTx);
+ // 在 DApp 界面中展示这些信息,共同签名人确认后再签名。
+ if (!(await confirmTransfer(details))) return { status: "declined" };
+ return signAndCheck(tronweb, partiallySignedTx);
+}
+```
+
+返回 `collect` 时继续交接,返回 `declined` 时停止本次签名。权重查询失败或缺少必要字段时暂停,恢复后重新执行完整权重检查。权限被撤销或已不允许本次操作时,核对交易 owner 和权限 ID,重建交易并重新收集全部签名。广播超时则先按交易 ID 查询结果。
## 错误码
@@ -5112,7 +5428,7 @@ try {
| 码 | 含义 | 来源 | 可重试? |
| :---: | --- | --- | :---: |
| `'Confirmation declined by user'`(字符串) | 用户在签名弹窗里点【拒绝】 | `tronWeb.trx.multiSign(...)` | 否——用户拒绝 |
-| `code: 'SIGERROR'`,`message` 解码为 `Validate signature error: permission isn't exit` | `fromAddress` 上不存在该 `permissionId`(填错或已撤销)。`sendTrx` **不会**校验权限,由节点在广播时拒绝 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——重新查 `getAccount(fromAddress).active_permission` 后重建交易 |
+| `code: 'SIGERROR'`,`message` 解码为 `Validate signature error: permission isn't exit` | `owner` 上不存在该 `permissionId`(填错或已撤销)。`sendTrx` **不会**校验权限,由节点在广播时拒绝 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——重新查 `getAccount(owner).active_permission` 后重建交易 |
| `code: 'SIGERROR'`,其他 `Validate signature error: …` 信息 | 签名不满足该权限——如总权重低于 `threshold`,或签名人不在其 `keys[]` 中 | `sendRawTransaction(...)` 的返回值(不抛异常) | 否——补齐缺少的签名(每个 co-signer 一次 `multiSign`) |
| `REVERT` / `OUT_OF_ENERGY` / `FAILED` | 广播成功但链上执行失败 | `getTransactionInfo(txid)` | **否——交易已 final,永远不要自动重试** |
@@ -5144,7 +5460,13 @@ try {
// 用同一个字符串验签,返回签名者的 base58 地址
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+}
```
### 参数
@@ -5165,11 +5487,7 @@ try {
0xb0e0b150b9b10dc348f25c7f38fc87f16e18c0d230d23946aac519a5ad9e45937f656012d33c09e9d9dec00b03fbb304e797f8991bb823dce676ac91e03a55991b
```
-如果报错,则会返回如下信息:
-
-```text
- Uncaught (in promise) Invalid transaction provided
-```
+消息为空或钱包签名失败时可能返回 `Invalid transaction provided`。用户拒签时返回 `Confirmation declined by user`。其他失败请查看具体错误原因。
## 交互流程
@@ -5332,7 +5650,7 @@ TRON 地址有两种可互转的编码:
- **ABI** —— Application Binary Interface,合约可调用方法与事件的 JSON 描述。若代币合约的 ABI 缺少可识别的方法(如 `transfer`、`approve`),TronLink 可能无法提供相应操作。
- **`chainId`** —— 网络标识。TronLink 在 `wallet_switchEthereumChain` 和 `chainChanged` 用十六进制形式(如 `0x2b6653dc`),在 EIP-712 的 `domain.chainId` 用十进制 EVM 形式(如 `728126428`)。参见[网络与地址](networks.md)。
- **`ProviderRpcError`** —— EIP-1193 在 `disconnect` 时抛出的错误对象,结构为 `{ code: number; message: string; data?: unknown }`。
-- **permission id** —— 多签交易使用的活动权限索引(传给 `tronWeb.trx.multiSign`)。参见[多签转账](../dapp/multi-sign-transfer.md)。
+- **permission id** —— 交易 owner 账户中所选活动权限条目的 `id` 字段值(传给 `tronWeb.trx.multiSign`)。参见[多签转账](../dapp/multi-sign-transfer.md)。
- **base58 / hex 地址** —— TRON 地址的两种编码(`T...` 与 `41...`)。参见[网络与地址](networks.md)。
## AI 工具
@@ -5352,7 +5670,7 @@ TronLink 智能体在一次用户请求里跨 DApp provider → DeepLink → MCP
**错误结构:** 在 TronLink 注入的 `tronWeb` 上(插件 4.0.0 起),用户拒绝 `trx.sign`、`trx.multiSign` 或 `trx.signMessageV2` 时,Promise 以**纯字符串** `'Confirmation declined by user'` reject——不是 `Error` 对象,也没有数字 `code`。`{ code: 4001, message: 'User rejected the request.' }` 对象只由 `window.tron.request(...)` 方法(如 `eth_requestAccounts`)返回。其他失败(钱包未解锁、载荷非法、观察钱包等)返回其他值——参见[处理拒签](#handling-rejections)。不要自动重试签名。
-| 业务含义 | DApp provider([EIP-1474][provider]) | DeepLink([5 位码][deeplink]) | MCP([`TL_*`][mcp]) | CLI v1.0.1([退出状态][cli]) | 可重试? |
+| 业务含义 | DApp provider([EIP-1474][provider]) | [DeepLink 回调码][deeplink] | MCP([`TL_*`][mcp]) | CLI v1.0.1([退出状态][cli]) | 可重试? |
| --- | :---: | :---: | :---: | :---: | :---: |
| **用户拒绝**签名或连接弹窗 | `window.tron.request(...)` 为 `4001`;`tronWeb.trx.sign` / `multiSign` / `signMessageV2` 为字符串 `'Confirmation declined by user'` | `300`(交易取消) | —(HITL——只能在新的 tool 调用里再次唤起) | `1` | **否** |
| **参数非法** / payload 错 | `tronWeb` 构造器抛错 | `10001`–`10020`、`10024`、`10025` | `TL_INVALID_INPUT` | `1` | **否**——修参数 |
@@ -5370,8 +5688,6 @@ TronLink 智能体在一次用户请求里跨 DApp provider → DeepLink → MCP
[mcp]: ../ai-support/tronlink-mcp-core.md
[cli]: ../ai-support/tronlink-cli.md
-
-
## 处理拒签
除上文所述的用户拒绝值外,签名方法还可能返回:`'User has not unlocked wallet'`(钱包未解锁,或 DApp 授权后已断开连接)、`'Invalid transaction provided'`(载荷非法,或钱包内部签名失败)、`'Transaction integrity check failed'`(4.11.1 起;载荷未通过 TronLink 完整性校验,如非字符串消息——在用户关闭 TronLink 警告弹窗后返回)、`{ code: 4100, message: 'Watch accounts cannot sign' }`(观察钱包;4.10.0 起)。无法识别的值应按意外错误处理,不要当作用户拒绝。
@@ -5436,7 +5752,7 @@ try {
## DApp 需要特定网络
-用 `wallet_switchEthereumChain`(TIP-3326)请求切换,传入目标十六进制 `chainId`。参见 [chainId 取值](networks.md)与[切换网络](../plugin-wallet/active-requests.md)。通过 `chainChanged` 确认当前网络。
+用 `wallet_switchEthereumChain`(TIP-3326)请求切换,传入目标十六进制 `chainId`。参见 [chainId 取值](networks.md)与[切换网络](../plugin-wallet/active-requests.md#tip-3326)。通过 `chainChanged` 确认当前网络。
## 交易因资源不足而失败
diff --git a/docs/llms.txt b/docs/llms.txt
index 2ee39de..dd732a6 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -2,7 +2,7 @@
> TronLink is a decentralized wallet for the TRON ecosystem, available as a browser extension and a mobile app. This documentation covers integrating DApps with TronLink across the browser extension, the mobile app (via DeepLink), and AI/agent tooling (MCP servers, CLI, signer SDK).
-> Updated: 2026-11-04T10:12:58Z · Commit: 56f294d79923
+> Updated: 2026-11-26T12:11:13Z · Commit: 7d9fecacf230
How integration works: TronLink injects a `window.tron` provider into every page, exposing a `tronWeb` instance, a `request` method, and `on` / `removeListener` for events. A DApp detects the wallet via TIP-6963, requests authorization via `eth_requestAccounts` (TIP-1102), then builds, signs, and broadcasts transactions through `tronWeb`. Account/network changes arrive as passive `accountsChanged` / `chainChanged` events.
@@ -19,6 +19,7 @@ Networks: Mainnet `chainId` `0x2b6653dc` (EVM `728126428`), Shasta testnet `0x94
- [Proactively Request TronLink Plugin Features](plugin-wallet/active-requests/): Connect website (TIP-1102 / EIP-1102), provider discovery (TIP-6963), normal/multi-sig transfer, message signing, `wallet_watchAsset`, switch network (TIP-3326), and legacy `window.tronLink` methods
- [Receive Messages from TronLink](plugin-wallet/passive-messages/): `accountsChanged`, `chainChanged`, `connect`, `disconnect` (TIP-1193) events and legacy 3.x messages
- [Ledger v-field Compatibility](plugin-wallet/ledger-signing-update/): Planned (not yet released) normalization of the signature `v` byte (`01`→`1c`, `00`→`1b`) for transaction, message, and EIP-712 signing
+- [Extension Core (Open Source)](plugin-wallet/extension-core/): Derive TRON and EVM accounts and sign locally with `@tronlink/core`
## DApp Integration
@@ -32,6 +33,8 @@ Networks: Mainnet `chainId` `0x2b6653dc` (EVM `728126428`), Shasta testnet `0x94
- [Asset Management](mobile/asset-management/): Adding custom TRC-20 / TRC-721 tokens
- [DeepLink](mobile/deeplink/): `tronlinkoutside://` scheme for open wallet, open DApp, login, transfer, sign transaction, sign message, plus result codes
- [DApp Support](mobile/dapp-support/): In-app DApp Explorer injection (`tronWeb`, `tronLink`, `iTron`)
+- [Android Core (Open Source)](mobile/android-core/): Integrate the Android wallet AAR, create a wallet, and verify a release signature
+- [iOS Core (Open Source)](mobile/ios-core/): Install the TLCore pod and run the Swift wallet examples
## AI Support
@@ -47,7 +50,7 @@ Networks: Mainnet `chainId` `0x2b6653dc` (EVM `728126428`), Shasta testnet `0x94
- [Networks & Addresses](reference/networks/): chainIds (mainnet/Shasta/Nile), RPC endpoints, explorers, faucets, address formats, units, and common token contracts
- [Glossary](reference/glossary/): Definitions of TRX/SUN, TRC standards, Energy/Bandwidth, TIP/EIP standards, ABI, chainId, and wallet objects
-- [Error Code Map](reference/error-code-map/): Horizontal join of DApp provider (EIP-1474), DeepLink (5-digit), MCP (`TL_*`), and CLI exit status keyed by business meaning, with retryable flags
+- [Error Code Map](reference/error-code-map/): Horizontal join of DApp provider (EIP-1474), DeepLink callback codes, MCP (`TL_*`), and CLI exit status keyed by business meaning, with retryable flags
- [FAQ](reference/faq/): Common integration questions — wallet detection, connection rejection, tronWeb readiness, network switching, resources
## Localized
diff --git a/docs/llms.zh.txt b/docs/llms.zh.txt
index d211fa0..c042294 100644
--- a/docs/llms.zh.txt
+++ b/docs/llms.zh.txt
@@ -2,7 +2,7 @@
> TronLink 是 TRON 生态的去中心化钱包,提供浏览器扩展和移动 App。本文档涵盖 DApp 通过浏览器扩展、移动端(DeepLink)以及 AI/智能体工具链(MCP 服务、CLI、签名 SDK)与 TronLink 集成。
-> Updated: 2026-11-04T10:12:58Z · Commit: 56f294d79923
+> Updated: 2026-11-26T12:11:13Z · Commit: 7d9fecacf230
集成原理:TronLink 向页面注入 `window.tron` provider,暴露 `tronWeb` 实例、`request` 方法以及 `on` / `removeListener` 事件订阅。DApp 通过 TIP-6963 检测钱包,用 `eth_requestAccounts`(TIP-1102)请求授权,再经 `tronWeb` 构建、签名并广播交易。账户/网络变化以 `accountsChanged` / `chainChanged` 被动事件送达。
@@ -21,6 +21,7 @@
- [主动请求 TronLink 插件功能](plugin-wallet/active-requests/):连接网站(TIP-1102 / EIP-1102)、provider 发现(TIP-6963)、普通/多签转账、消息签名、`wallet_watchAsset`、切换网络(TIP-3326)及旧版 `window.tronLink` 方法
- [被动接收 TronLink 插件的消息](plugin-wallet/passive-messages/):`accountsChanged`、`chainChanged`、`connect`、`disconnect`(TIP-1193)事件及旧版 3.x 消息
- [对 Ledger 签名后的 v 字段兼容](plugin-wallet/ledger-signing-update/):交易、消息、EIP-712 签名的 `v` 字节归一化计划(`01`→`1c`,`00`→`1b`,尚未上线)
+- [插件开源核心库](plugin-wallet/extension-core/):使用 `@tronlink/core` 派生 TRON 和 EVM 账户并在本地签名
## DApp 集成
@@ -34,6 +35,8 @@
- [资产管理](mobile/asset-management/):添加自定义 TRC-20 / TRC-721 代币
- [DeepLink](mobile/deeplink/):`tronlinkoutside://` 协议——打开钱包、打开 DApp、登录、转账、签名交易、签名消息及回传码
- [DApp 支持](mobile/dapp-support/):应用内 DApp 浏览器注入(`tronWeb`、`tronLink`、`iTron`)
+- [Android 开源核心库](mobile/android-core/):集成 Android 钱包 AAR、创建钱包及验证发布签名
+- [iOS 开源核心库](mobile/ios-core/):集成 TLCore 并运行 Swift 钱包示例
## AI 支持
@@ -49,7 +52,7 @@
- [网络与地址](reference/networks/):chainId(主网/Shasta/Nile)、RPC 端点、浏览器、水龙头、地址格式、单位、常用代币合约
- [术语表](reference/glossary/):TRX/SUN、TRC 标准、能量/带宽、TIP/EIP 标准、ABI、chainId、钱包对象等释义
-- [错误码对照表](reference/error-code-map/):以业务含义为主轴,横向 join DApp provider(EIP-1474)、DeepLink(5 位码)、MCP(`TL_*`)、CLI 退出状态,带 retryable 列
+- [错误码对照表](reference/error-code-map/):以业务含义为主轴,横向 join DApp provider(EIP-1474)、DeepLink 回调码、MCP(`TL_*`)、CLI 退出状态,带 retryable 列
- [常见问题](reference/faq/):集成高频问题——钱包检测、连接拒绝、tronWeb 就绪、网络切换、资源
## 可选
diff --git a/docs/mobile/android-core.en.md b/docs/mobile/android-core.en.md
new file mode 100644
index 0000000..3cf005b
--- /dev/null
+++ b/docs/mobile/android-core.en.md
@@ -0,0 +1,57 @@
+# Android Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-android-core](https://github.com/TronLink/tronlink-android-core)
+
+Integrate the wallet functions used by TronLink Android to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+The library requires Android API level 21 or later; the Java version is set in the upstream [build configuration](https://github.com/TronLink/tronlink-android-core/blob/main/core/build.gradle). Add JitPack to the repositories Gradle uses to resolve dependencies (Groovy DSL).
+
+```groovy
+repositories {
+ maven { url "https://jitpack.io" }
+}
+```
+
+Add the AAR to the app module’s dependencies. Replace `` with a tag from the [releases](https://github.com/TronLink/tronlink-android-core/releases), normally the latest.
+
+```groovy
+dependencies {
+ implementation 'com.github.TronLink:tronlink-android-core:@aar'
+}
+```
+
+## Create a wallet
+
+Create a wallet in your app and read its TRON address.
+
+```java
+import org.tron.walletserver.Wallet;
+
+// Inside an application method
+Wallet wallet = new Wallet(true);
+String address = wallet.getAddress();
+```
+
+The wallet tests also show how to restore an address from a mnemonic or private key. For transaction signing, see the transaction tests. The tests include no message-signing example; the library implements it in `org.tron.common.bip32.Sign` (`signPrefixedMessage`, `signPrefixedMessageV2`). [Wallet examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/WalletCoreUnitTest.java) · [Transaction signing examples](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/TransactionCoreUnitTest.java) · [`Sign.java`](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/main/java/org/tron/common/bip32/Sign.java)
+
+## Verify the AAR
+
+Verification requires the exact AAR signed by TronLink and its matching detached `.asc` signature. JitPack and the GitHub releases do not provide signature files, so obtain the signed AAR and matching signature from the maintainers. See the [upstream verification instructions](https://github.com/TronLink/tronlink-android-core#integrity-check).
+
+Download the [public key](https://keys.openpgp.org/vks/v1/by-fingerprint/7B910EA80207596075E6D7BA5D34F7A6550473BA) as `tronlink-build.asc`. Check the signing subkey fingerprint against the one in the upstream instructions, `7B910EA80207596075E6D7BA5D34F7A6550473BA`. Once it matches, import the key and verify the two files supplied by the maintainers, substituting their filenames below.
+
+```bash
+gpg --show-keys --with-subkey-fingerprint tronlink-build.asc
+gpg --import tronlink-build.asc
+gpg --verify release.aar.asc release.aar
+```
+
+## Privacy
+
+Embedding the library does not start usage reporting. The reporting code in `org.tron.metrics` records and uploads data only after the host app wires up its repositories and calls `DataUploader.init(...)` and `upload(...)`. Read the upstream [privacy policy](https://github.com/TronLink/tronlink-android-core/blob/main/PRIVACY-POLICY.md) before enabling it.
+
+## Version & License
+
+The examples and links on this page follow the upstream `main` branch. When you pin an older tag, check that its APIs match. [Apache License 2.0](https://github.com/TronLink/tronlink-android-core/blob/main/LICENSE)
diff --git a/docs/mobile/android-core.zh.md b/docs/mobile/android-core.zh.md
new file mode 100644
index 0000000..6ad4a41
--- /dev/null
+++ b/docs/mobile/android-core.zh.md
@@ -0,0 +1,59 @@
+# Android 开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-android-core](https://github.com/TronLink/tronlink-android-core)
+
+在 Android 应用中集成 TronLink 的钱包功能,可以创建 TRON 钱包、读取地址,并对交易或消息签名。
+
+## 安装
+
+环境要求为 Android API 21 及以上;Java 版本见上游[构建配置](https://github.com/TronLink/tronlink-android-core/blob/main/core/build.gradle)。在 Gradle 解析依赖的仓库列表中加入 JitPack。以下示例使用 Groovy DSL。
+
+```groovy
+repositories {
+ maven { url "https://jitpack.io" }
+}
+```
+
+在应用模块中声明 AAR 依赖。将 `` 替换为[发布页](https://github.com/TronLink/tronlink-android-core/releases)中的标签,通常使用最新版本。
+
+```groovy
+dependencies {
+ implementation 'com.github.TronLink:tronlink-android-core:@aar'
+}
+```
+
+## 创建钱包
+
+在应用中创建钱包并读取 TRON 地址。
+
+```java
+import org.tron.walletserver.Wallet;
+
+// 在应用的方法中执行
+Wallet wallet = new Wallet(true);
+String address = wallet.getAddress();
+```
+
+钱包测试还演示了如何通过助记词或私钥恢复地址。交易签名的用法见交易测试。测试中没有消息签名示例,库中的实现位于 `org.tron.common.bip32.Sign`(`signPrefixedMessage`、`signPrefixedMessageV2`)。[钱包示例](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/WalletCoreUnitTest.java) · [交易签名示例](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/test/java/org/tron/TransactionCoreUnitTest.java) · [`Sign.java`](https://github.com/TronLink/tronlink-android-core/blob/main/core/src/main/java/org/tron/common/bip32/Sign.java)
+
+## 验证 AAR 签名
+
+验签需要 TronLink 签署的 AAR 原件及配套的独立签名文件 `.asc`。JitPack 和 GitHub 发布页不提供签名文件,如需验签,请向维护者索取签署的 AAR 和配套签名。参见[上游验签说明](https://github.com/TronLink/tronlink-android-core#integrity-check)。
+
+下载[发布公钥](https://keys.openpgp.org/vks/v1/by-fingerprint/7B910EA80207596075E6D7BA5D34F7A6550473BA),保存为 `tronlink-build.asc`。先查看签名子密钥的指纹,与上游公布的 `7B910EA80207596075E6D7BA5D34F7A6550473BA` 核对。一致后导入公钥,再用维护者提供的两个文件验签;请替换下例中的文件名。
+
+```bash
+gpg --show-keys --with-subkey-fingerprint tronlink-build.asc
+gpg --import tronlink-build.asc
+gpg --verify release.aar.asc release.aar
+```
+
+## 隐私
+
+集成本库不会自动开始使用统计上报。`org.tron.metrics` 中的上报代码只有在宿主应用接入相应的数据仓库,并调用 `DataUploader.init(...)` 和 `upload(...)` 后,才会记录和上传数据。启用前请参阅上游的[隐私说明](https://github.com/TronLink/tronlink-android-core/blob/main/PRIVACY-POLICY.md)。
+
+
+
+## 版本与许可证
+
+本页示例和链接以上游 `main` 分支为准。固定使用较旧的标签时,请核对其接口是否一致。[Apache License 2.0](https://github.com/TronLink/tronlink-android-core/blob/main/LICENSE)
diff --git a/docs/mobile/dapp-support.en.md b/docs/mobile/dapp-support.en.md
index e3e02e8..99795c9 100644
--- a/docs/mobile/dapp-support.en.md
+++ b/docs/mobile/dapp-support.en.md
@@ -2,9 +2,11 @@
## TronLink Integration
-TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with TronLink DApps and the TRON network.
+TronLink injects a version of TronWeb into the DApp that runs in TronLink's DApp Explorer. This enables the DApp to interact with the TronLink App and the TRON network.
-Details: [Go to DApp](../../dapp/getting-started)
+Once the in-app browser has supplied an authorized TronWeb instance, the transaction-building steps in [Start Developing](../dapp/getting-started.md) apply. That guide demonstrates provider discovery (TIP-6963), authorization (`eth_requestAccounts`) and events for the browser extension. Check support for each of those interfaces on the target App version.
+
+From an external mobile browser, use [DeepLink](deeplink.md) to open TronLink.
## DApp Explorer
diff --git a/docs/mobile/dapp-support.zh.md b/docs/mobile/dapp-support.zh.md
index 790c0f2..431dde5 100644
--- a/docs/mobile/dapp-support.zh.md
+++ b/docs/mobile/dapp-support.zh.md
@@ -7,7 +7,9 @@
TronLink App 内置 DApp 浏览器,对于在其上运行的 TRON DApp,TronLink 会自动将 tronWeb 及 tronLink 对象注入到该 DApp。从而允许 DApp 与 TronLink App,以及TRON 网络交互。
-详情:参考[DApp章节](../../dapp/getting-started)
+在 App 内置浏览器中取得已授权的 TronWeb 实例后,可参考[开始开发](../dapp/getting-started.md)中的交易构建步骤。该指南中的 Provider 发现(TIP-6963)、授权(`eth_requestAccounts`)和事件示例面向浏览器插件,请在目标 App 版本上逐项确认接口支持情况。
+
+从外部移动浏览器唤起 TronLink 请参考 [DeepLink](deeplink.md)。
## Dapp 浏览器
diff --git a/docs/mobile/deeplink.en.md b/docs/mobile/deeplink.en.md
index 338da4f..12982e1 100644
--- a/docs/mobile/deeplink.en.md
+++ b/docs/mobile/deeplink.en.md
@@ -10,7 +10,14 @@ img {
}
-For every action below, the `param` value of `tronlinkoutside://pull.activity?param={}` is the protocol data in JSON format. Note: the JSON string must be URL-encoded before being placed in the link.
+The `param` query parameter contains URL-encoded JSON. Each sample link encodes the request shown below it. For your integration, replace the sample values and generate a new URL.
+
+```javascript
+const buildDeepLink = (request) =>
+ "tronlinkoutside://pull.activity?param=" + encodeURIComponent(JSON.stringify(request));
+```
+
+For login, transfer and signing, use your DApp URL and callback, the target chain ID, and a fresh action ID. For transaction signing, set `data` to the JSON string of a newly built transaction. The sample transaction contains an expired timestamp.
## Open Wallet
@@ -19,7 +26,7 @@ For every action below, the `param` value of `tronlinkoutside://pull.activity?pa
Available since TronLink v4.10.0.
```html
-Open Tronlink
+Open Tronlink
```
`param` (request):
@@ -39,7 +46,7 @@ Available since TronLink v4.10.0.
Available since TronLink v4.10.0.
```html
-Open DApp
+Open DApp
```
`param` (request) — `url` is the target DApp:
@@ -58,14 +65,14 @@ Available since TronLink v4.10.0.
Available since TronLink v4.11.0.
```html
-Login/Request Address
+Login/Request Address
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -94,14 +101,14 @@ Callback:
Available since TronLink v4.11.0.
```html
-Transfer
+Transfer
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -137,14 +144,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign transaction
+Sign transaction
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -178,14 +185,14 @@ Callback (`actionId` matches the request):
Available since TronLink v4.11.0.
```html
-Sign message
+Sign message
```
`param` (request):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -214,40 +221,38 @@ Callback:
## Result Code
-> Note: `tokenId` and `contract` are mutually exclusive in a transfer request — supplying both returns code `10025`.
-
-| Code | Message |
-|:-------|:-------|
-| 0 | success |
-| 10001 | Incorrect JSON format |
-| 10002 | Missing Action |
-| 10003 | Unknown Action |
-| 10004 | Missing ActionId |
-| 10005 | Incorrect DApp URL format |
-| 10006 | Incorrect CallbackUrl format |
-| 10007 | Empty DApp name |
-| 10008 | Version number not supported |
-| 10009 | Current network not supported |
-| 10010 | The URL is not supported to open TronLink |
-| 10011 | Unknown SignType |
-| 10012 | Incorrect Transaction format |
-| 10013 | Incorrect Method format |
-| 10014 | Incorrect Message format |
-| 10015 | Incorrect toAddress |
-| 10016 | No wallet created in TronLink |
-| 10017 | Incorrect fromAddress |
-| 10018 | Incorrect contractAddress |
-| 10019 | Incorrect chainId |
-| 10020 | Incorrect amount |
-| 10021 | The initiating address does not match the current wallet |
-| 10022 | Incorrect loginAddress |
-| 10023 | System contract not support |
-| 10024 | Incorrect tokenId |
-| 10025 | TokenId & Contract address should not exist together |
-| 300 | Transaction canceled |
-| 301 | Transaction executed in TronLink |
-| 302 | Broadcast failure - returned with incorrect info |
-| -1 | Unknown reason |
+| Code | Message | Notes |
+|:-------|:-------|:-------|
+| 0 | success | |
+| 10001 | Incorrect JSON format | |
+| 10002 | Missing Action | |
+| 10003 | Unknown Action | |
+| 10004 | Missing ActionId | |
+| 10005 | Incorrect DApp URL format | |
+| 10006 | Incorrect CallbackUrl format | |
+| 10007 | Empty DApp name | |
+| 10008 | Version number not supported | |
+| 10009 | Current network not supported | |
+| 10010 | The URL is not supported to open TronLink | |
+| 10011 | Unknown SignType | |
+| 10012 | Incorrect Transaction format | |
+| 10013 | Incorrect Method format | |
+| 10014 | Incorrect Message format | |
+| 10015 | Incorrect toAddress | |
+| 10016 | No wallet created in TronLink | |
+| 10017 | Incorrect fromAddress | |
+| 10018 | Incorrect contractAddress | |
+| 10019 | Incorrect chainId | |
+| 10020 | Incorrect amount | |
+| 10021 | The initiating address does not match the current wallet | |
+| 10022 | Incorrect loginAddress | |
+| 10023 | System contract not support | |
+| 10024 | Incorrect tokenId | |
+| 10025 | TokenId & Contract address should not exist together | Conflicting asset identifiers in a transfer request. |
+| 300 | Transaction canceled | |
+| 301 | Transaction executed in TronLink | |
+| 302 | Broadcast failure - returned with incorrect info | |
+| -1 | Unknown reason | |
## JSON Schema Reference
@@ -342,7 +347,13 @@ Every `param` shares this prefix:
}
```
-**Transfer** request — `tokenId` (TRX / TRC10) and `contract` (TRC20) are **mutually exclusive**; supplying both returns `10025`. Set the unused one to `""` (empty string):
+**Transfer** uses the field values below. Send the unused field as an empty string, following the transfer sample and the DeepLink demo request format. Omitting the unused key produces a request that differs from these samples; this page does not define how the App treats an omitted key, so keep both keys present.
+
+| Asset | `tokenId` | `contract` |
+|---|---|---|
+| TRX | `"0"` | `""` |
+| TRC10 | Decimal token ID as a string | `""` |
+| TRC20 | `""` | Token contract address |
```json
{
@@ -356,8 +367,8 @@ Every `param` shares this prefix:
"from": { "type": "string", "description": "Sender TRON address (base58)" },
"to": { "type": "string", "description": "Recipient TRON address (base58)" },
"loginAddress": { "type": "string", "description": "Address that authorized this session — must match the current wallet (otherwise code 10021)" },
- "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX; pass '' when sending TRC20" },
- "contract": { "type": "string", "description": "TRC20 contract address; pass '' when sending TRX / TRC10" },
+ "tokenId": { "type": "string", "description": "TRC10 token id or '0' for TRX" },
+ "contract": { "type": "string", "description": "TRC20 contract address" },
"amount": { "type": "string", "description": "Decimal string in human units (e.g. '1.5'); the app handles decimals" },
"memo": { "type": "string", "description": "Optional transaction memo" },
"dappName": { "type": "string" },
diff --git a/docs/mobile/deeplink.zh.md b/docs/mobile/deeplink.zh.md
index 9f063f0..f5a2c81 100644
--- a/docs/mobile/deeplink.zh.md
+++ b/docs/mobile/deeplink.zh.md
@@ -10,14 +10,21 @@ img {
}
-下文每个操作中,`tronlinkoutside://pull.activity?param={}` 的 `param` 参数都是 JSON 格式的协议数据。注意:JSON 字符串放入链接前需要进行 urlencode 编码。
+`param` 查询参数包含 URL 编码后的 JSON。每个示例链接都由其下方的请求对象编码而成。接入时请替换示例值,并重新生成链接。
+
+```javascript
+const buildDeepLink = (request) =>
+ "tronlinkoutside://pull.activity?param=" + encodeURIComponent(JSON.stringify(request));
+```
+
+登录、转账和签名时,请使用自己的 DApp 地址、回调地址、目标 chainId 和新生成的 actionId。交易签名时,将 `data` 设为新构建交易的 JSON 字符串。示例交易的有效期已过。
## 打开钱包
使用 DeepLink 方式唤起钱包。可用版本:TronLink v4.10.0 起。
```html
-Open Tronlink
+Open Tronlink
```
`param`(请求):
@@ -35,7 +42,7 @@ img {
使用 DeepLink 方式唤起钱包,并在 DApp 浏览器中打开 DApp。可用版本:TronLink v4.10.0 起。
```html
-Open DApp
+Open DApp
```
`param`(请求),`url` 为目标 DApp:
@@ -54,14 +61,14 @@ img {
使用 DeepLink 方式唤起钱包,并在钱包中选择获取钱包地址。可用版本:TronLink v4.11.0 起。
```html
-Login/Request Address
+Login/Request Address
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -90,14 +97,14 @@ img {
使用 DeepLink 方式唤起 TronLink,并发送转账数据,在钱包中转账并广播。可用版本:TronLink v4.11.0 起。
```html
-Transfer
+Transfer
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -133,14 +140,14 @@ img {
可用版本:TronLink v4.11.0 起。
```html
-Sign transaction
+Sign transaction
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -174,14 +181,14 @@ img {
可用版本:TronLink v4.11.0 起。
```html
-Sign message
+Sign message
```
`param`(请求):
```json
{
- "url": "https://justlend.org/#/home",
+ "url": "https://your-dapp.example.com/",
"callbackUrl": "https://your-backend.example.com/api/tron/v1/callback",
"dappIcon": "https://your-dapp.example.com/icon.png",
"dappName": "Test demo",
@@ -212,8 +219,6 @@ img {
## 回传消息码
-> 注意:转账请求中 `tokenId` 与 `contract` 互斥,两者同时传入会返回消息码 `10025`。
-
| 消息码 | 消息 | 备注 |
|:-------|:-------|:-------|
| 0 | success | |
@@ -241,7 +246,7 @@ img {
| 10022 | Incorrect loginAddress | |
| 10023 | System contract not support | |
| 10024 | Incorrect tokenId | |
-| 10025 | TokenId & Contract address should not exist together | |
+| 10025 | TokenId & Contract address should not exist together | 转账请求中的资产标识冲突。 |
| 300 | Transaction canceled | |
| 301 | Transaction executed in TronLink | |
| 302 | Broadcast failure - returned with incorrect info | |
@@ -340,7 +345,13 @@ img {
}
```
-**转账** 请求——`tokenId`(TRX / TRC10)与 `contract`(TRC20)**互斥**;同时传入会返回 `10025`。不用的那个传 `""`(空字符串):
+**转账**字段按下表填写。沿用转账示例和 DeepLink Demo 的请求格式,将未使用的字段设为空字符串。省略未使用的字段会得到与示例不同的请求,本页未定义 App 对省略字段的处理方式,因此请保留两个字段。
+
+| 资产 | `tokenId` | `contract` |
+|---|---|---|
+| TRX | `"0"` | `""` |
+| TRC10 | 十进制字符串形式的代币 ID | `""` |
+| TRC20 | `""` | 代币合约地址 |
```json
{
@@ -354,8 +365,8 @@ img {
"from": { "type": "string", "description": "发起方 TRON 地址(base58)" },
"to": { "type": "string", "description": "收款方 TRON 地址(base58)" },
"loginAddress": { "type": "string", "description": "本次会话的授权地址——必须与当前钱包一致,否则返回 10021" },
- "tokenId": { "type": "string", "description": "TRC10 token id,或 '0' 表示 TRX;发送 TRC20 时传 ''" },
- "contract": { "type": "string", "description": "TRC20 合约地址;发送 TRX / TRC10 时传 ''" },
+ "tokenId": { "type": "string", "description": "TRC10 token id,或 '0' 表示 TRX" },
+ "contract": { "type": "string", "description": "TRC20 合约地址" },
"amount": { "type": "string", "description": "人类单位的十进制字符串(如 '1.5'),App 内部处理 decimals" },
"memo": { "type": "string", "description": "可选交易备注" },
"dappName": { "type": "string" },
diff --git a/docs/mobile/ios-core.en.md b/docs/mobile/ios-core.en.md
new file mode 100644
index 0000000..3f5befc
--- /dev/null
+++ b/docs/mobile/ios-core.en.md
@@ -0,0 +1,39 @@
+# iOS Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-iOS-core](https://github.com/TronLink/tronlink-iOS-core)
+
+Use TronLink’s native iOS wallet module to create a TRON wallet, read its address, and sign transactions or messages.
+
+## Installation
+
+Add the dependency to your app target in the Podfile. The minimum iOS version and the Swift version are declared in the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec).
+
+```ruby
+pod 'tronlink-iOS-core'
+```
+
+Run `pod install`, open the generated `.xcworkspace` in Xcode, and import the module in Swift.
+
+```swift
+import TLCore
+```
+
+## Run the example project
+
+To explore the wallet APIs in the upstream Xcode project, install its pods from the example directory.
+
+```bash
+git clone https://github.com/TronLink/tronlink-iOS-core.git
+cd tronlink-iOS-core/Example
+pod install
+```
+
+Open the workspace in `Example/`. The Swift tests show wallet creation, transaction and message signing, and how to export a private key or mnemonic. [Swift wallet examples](https://github.com/TronLink/tronlink-iOS-core/blob/main/Example/Tests/Tests.swift)
+
+## Privacy
+
+Installing the pod or creating a wallet does not start a statistics upload. The host app must invoke the reporter and implement the upload callback in `TRXMetricsDataSource`. To enable uploads, the app must also identify its environment as production or pre-release. The same check applies to Debug and Release builds. In TronLink iOS, Basic Mode suppresses reporting, as do watch-only wallets and Shasta activity. [iOS privacy policy](https://github.com/TronLink/tronlink-iOS-core/blob/main/PRIVACY-POLICY.md)
+
+## Version & License
+
+For the current version, see the [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec). [Apache License 2.0](https://github.com/TronLink/tronlink-iOS-core/blob/main/LICENSE)
diff --git a/docs/mobile/ios-core.zh.md b/docs/mobile/ios-core.zh.md
new file mode 100644
index 0000000..d3c0aac
--- /dev/null
+++ b/docs/mobile/ios-core.zh.md
@@ -0,0 +1,39 @@
+# iOS 开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-iOS-core](https://github.com/TronLink/tronlink-iOS-core)
+
+在 iOS 应用中使用 TronLink 的原生钱包模块,可以创建 TRON 钱包、读取地址,并对交易或消息签名。
+
+## 安装
+
+在 Podfile 中为应用 target 添加依赖。支持的最低 iOS 版本和 Swift 版本见 [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec)。
+
+```ruby
+pod 'tronlink-iOS-core'
+```
+
+运行 `pod install`,用 Xcode 打开生成的 `.xcworkspace`,然后在 Swift 文件中导入模块。
+
+```swift
+import TLCore
+```
+
+## 运行示例工程
+
+要在上游 Xcode 示例工程中查看钱包 API 的用法,请先进入示例目录安装依赖。
+
+```bash
+git clone https://github.com/TronLink/tronlink-iOS-core.git
+cd tronlink-iOS-core/Example
+pod install
+```
+
+在 Xcode 中打开 `Example/` 下的工作区。Swift 测试展示了创建钱包、签署交易和消息,以及导出私钥或助记词的用法。[Swift 钱包示例](https://github.com/TronLink/tronlink-iOS-core/blob/main/Example/Tests/Tests.swift)
+
+## 隐私
+
+安装 Pod 或创建钱包不会自动上传统计数据。要启用上传,集成方需要主动调用上报方法,实现 `TRXMetricsDataSource` 的上传回调,并将应用当前连接的环境标记为生产或预发布。Debug 和 Release 构建都遵循这项检查。TronLink iOS 还会在基础模式、观察钱包和 Shasta 测试网下停用上报。[iOS 隐私说明](https://github.com/TronLink/tronlink-iOS-core/blob/main/PRIVACY-POLICY.md)
+
+## 版本与许可证
+
+当前版本见 [podspec](https://github.com/TronLink/tronlink-iOS-core/blob/main/tronlink-iOS-core.podspec)。[Apache License 2.0](https://github.com/TronLink/tronlink-iOS-core/blob/main/LICENSE)
diff --git a/docs/plugin-wallet/active-requests.en.md b/docs/plugin-wallet/active-requests.en.md
index 51f975f..e6ea918 100644
--- a/docs/plugin-wallet/active-requests.en.md
+++ b/docs/plugin-wallet/active-requests.en.md
@@ -15,7 +15,10 @@ This method follows the Ethereum **EIP-1102** protocol.
```javascript
try {
await window.tron.request({method: 'eth_requestAccounts'});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Connection declined");
+ else console.error("Authorization failed", error);
+}
```
#### Return Value
@@ -140,10 +143,17 @@ const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+} catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+}
+if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+}
```
When executing `await tronweb.trx.sign(tx);`, TronLink displays a confirmation popup.
@@ -168,24 +178,7 @@ Refer to **Normal Transfer** above.
#### Code Example
-```typescript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
-const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
-const activePermissionId = 2;
-
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
-);
-
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
-} catch (e) {}
-```
-
-Rejecting triggers an exception; signing returns the signed transaction for broadcasting.
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting.
> **Legacy (not recommended):** [Legacy: multiSign via window.tronLink](#legacy-multisign-via-windowtronlink)
@@ -211,7 +204,13 @@ try {
// verify with the same string; returns the signer's base58 address
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+}
```
#### Parameter
@@ -232,11 +231,7 @@ If signed successfully:
0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c
```
-If an error occurs:
-
-```typescript
-Uncaught (in promise) Invalid transaction provided
-```
+An empty message or a signing failure can produce `Invalid transaction provided`. A user declining the prompt rejects with `Confirmation declined by user`. For other failures, inspect the returned reason.
### Interaction Flow
@@ -381,7 +376,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
#### Parameters
@@ -608,12 +606,27 @@ Retained for back-compat; new integrations should use `eth_requestAccounts`.
```json
{
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": { "type": "integer", "enum": [200, 4000, 4001] },
- "message": { "type": "string" }
- }
+ "oneOf": [
+ {
+ "const": ""
+ },
+ {
+ "type": "object",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [200, 4000, 4001]
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ ]
}
```
@@ -639,15 +652,22 @@ Therefore, the DApp must perform the **Connect Website** request first and wait
#### Code Example
```typescript
-const res = await tronWeb.request(
+const res: RequestAccountsResponse = await window.tronLink.request(
{
method: 'tron_requestAccounts',
params: {
websiteIcon: '',
websiteName: '',
- } as RequestAccountParams,
+ } as RequestAccountsParams,
}
);
+if (res === "") {
+ console.info("Unlock TronLink");
+} else if (res.code === 200) {
+ console.info("Connected");
+} else {
+ console.info(res.code, res.message);
+}
```
#### Parameters
@@ -660,14 +680,14 @@ interface RequestAccountsParams {
```
- **method:** fixed string `tron_requestAccounts`
-- **params:** `RequestAccountParams` type:
+- **params:** `RequestAccountsParams` type:
- `websiteIcon`: DApp website icon URI (displayed in connected site list)
- `websiteName`: DApp website name
#### Return Value
```typescript
-interface ReqestAccountsResponse {
+type RequestAccountsResponse = "" | {
code: 200 | 4000 | 4001,
message: string
}
@@ -691,34 +711,24 @@ if (window.tronLink.ready) {
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress);
+ let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
+ signedTx = await tronweb.trx.sign(tx);
+ } catch (error) {
+ if (error === "Confirmation declined by user") console.info("Signing declined");
+ else console.error("Signing failed", error);
+ }
+ if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx);
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+ }
}
```
## Legacy: multiSign via window.tronLink
-```typescript
-if (window.tronLink.ready) {
- const tronweb = tronLink.tronWeb;
- const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
- const fromAddress = tronweb.defaultAddress.base58; // tx owner: the account this active permission controls; set it explicitly if the connected account is only a co-signer
- const activePermissionId = 2;
-
- const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
- );
-
- try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId);
- await tronweb.trx.sendRawTransaction(signedTx);
- } catch (e) {}
-}
-```
+Use the [multi-signature transfer example](../dapp/multi-sign-transfer.md) to query the transaction owner’s permission, collect a signature and verify the cumulative weight before broadcasting. For the legacy provider, obtain `tronweb` from `window.tronLink.tronWeb` once `window.tronLink.ready` is true.
## Legacy: signMessageV2 via window.tronLink
@@ -730,7 +740,13 @@ if (window.tronLink.ready) {
try {
const message = "Sign in to Example DApp\nNonce: 8f3a2c"; // plain UTF-8 text
const signedString = await tronweb.trx.signMessageV2(message);
- } catch (e) {}
+ } catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("Signing declined");
+ } else {
+ console.error("Message signing or verification failed", error);
+ }
+ }
}
```
@@ -742,42 +758,48 @@ if (window.tronLink.ready) {
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc10',
options: { address: '1002000' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC20
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc20',
options: { address: 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
// Add TRC721
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc721',
options: { address: 'TVtaUnsgKXhTfqSFRnHCsSXzPiXmm53nZt' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset failed", error);
+ }
}
```
@@ -790,5 +812,8 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("Network switch declined");
+ else console.error("Network switch failed", error);
+}
```
diff --git a/docs/plugin-wallet/active-requests.zh.md b/docs/plugin-wallet/active-requests.zh.md
index 285a02d..4fc6549 100644
--- a/docs/plugin-wallet/active-requests.zh.md
+++ b/docs/plugin-wallet/active-requests.zh.md
@@ -11,7 +11,10 @@ TronLink 可用于管理钱包私钥,DApp 在进行一些需签名的操作前
```javascript
try {
await window.tron.request({method: 'eth_requestAccounts'});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("连接请求被拒绝");
+ else console.error("授权失败", error);
+}
```
#### 返回值
@@ -126,10 +129,17 @@ const tronweb = window.tron.tronWeb;
const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress); // 步骤1
+let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
-} catch (e) {}
+ signedTx = await tronweb.trx.sign(tx); // 步骤2
+} catch (error) {
+ if (error === "Confirmation declined by user") console.info("用户拒绝签名");
+ else console.error("签名失败", error);
+}
+if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+}
```
当代码执行到 `await tronweb.trx.sign(tx);` 时,TronLink 钱包会提示弹窗,需要用户进行确认,如下图:
@@ -152,24 +162,7 @@ try {
### 技术规范
#### 代码示例
-```typescript
-const tronweb = window.tron.tronWeb;
-const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
-const fromAddress = tronweb.defaultAddress.base58; // 交易 owner:由该 active 权限控制的账户;若当前账户只是共同签名人,请显式填写被控制账户
-const activePermissionId = 2;
-const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
-); // 步骤1
-try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
-} catch (e) {}
-```
-
-如果用户在弹窗中选择【拒绝】,则会抛出异常,开发者可捕获此异常进行业务处理。
-
-如果用户在弹窗中选择【签名】,DApp 可以拿到签名后的交易,继续进行广播。
+按[多签转账示例](../dapp/multi-sign-transfer.md)查询交易 owner 的权限、收集签名并核对累计权重,满足阈值后再广播。
> **旧版用法(不推荐):** [兼容用法:multiSign(window.tronLink)](#multisignwindowtronlink)
@@ -191,7 +184,13 @@ try {
// 用同一个字符串验签,返回签名者的 base58 地址
const recovered = await tronweb.trx.verifyMessageV2(message, signedString);
const ok = recovered === tronweb.defaultAddress.base58;
-} catch (e) {}
+} catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+}
```
#### 参数
消息须为非空**字符串**。TronLink 对该字符串的 UTF-8 字节签名,并加上 TIP-191 前缀 `"\x19TRON Signed Message:\n" + <字节长度>`。外观类似 hex 的字符串**不会**被解码:`"0x1234"` 按六个文本字符(字节为 `30 78 31 32 33 34`)签名,而不是两个原始字节 `12 34`。
@@ -207,10 +206,7 @@ try {
```text
0xaa302ca153b10dff25b5f00a7e2f603c5916b8f6d78cdaf2122e24cab56ad39a79f60ff3916dde9761baaadea439b567475dde183ee3f8530b4cc76082b29c341c
```
-如果报错,则会返回如下信息:
-```typescript
-Uncaught (in promise) Invalid transaction provided
-```
+消息为空或钱包签名失败时可能返回 `Invalid transaction provided`。用户拒签时返回 `Confirmation declined by user`。其他失败请查看具体错误原因。
### 交互流程
@@ -355,7 +351,10 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("用户拒绝切换网络");
+ else console.error("切换网络失败", error);
+}
```
#### 参数
params 接受一个只有单一元素的数组,单一元素为 `SwitchTronChainParameter` 类型:
@@ -390,7 +389,7 @@ interface SwitchTronChainParameter {

-解锁后,或者 TronLink 已经提前解锁,会打开连接确认的弹窗:
+解锁后,或者 TronLink 已经提前解锁,会打开网络切换确认弹窗:

@@ -581,12 +580,27 @@ interface SwitchTronChainParameter {
```json
{
- "type": "object",
- "required": ["code", "message"],
- "properties": {
- "code": { "type": "integer", "enum": [200, 4000, 4001] },
- "message": { "type": "string" }
- }
+ "oneOf": [
+ {
+ "const": ""
+ },
+ {
+ "type": "object",
+ "required": [
+ "code",
+ "message"
+ ],
+ "properties": {
+ "code": {
+ "type": "integer",
+ "enum": [200, 4000, 4001]
+ },
+ "message": {
+ "type": "string"
+ }
+ }
+ }
+ ]
}
```
@@ -607,15 +621,22 @@ TronLink 提供外部发起 TRX 转账、合约签名、授权等功能。基于
### 技术规范
#### 代码示例
```typescript
-const res = await tronWeb.request(
+const res: RequestAccountsResponse = await window.tronLink.request(
{
method: 'tron_requestAccounts',
params: {
websiteIcon: '',
websiteName: '',
- } as RequestAccountParams,
+ } as RequestAccountsParams,
}
);
+if (res === "") {
+ console.info("请解锁 TronLink");
+} else if (res.code === 200) {
+ console.info("已连接");
+} else {
+ console.info(res.code, res.message);
+}
```
#### 参数
@@ -626,7 +647,7 @@ interface RequestAccountsParams {
}
```
* method: `tron_requestAccounts` 固定的字符串
-* params: `RequestAccountParams` 类型,具体参数如下
+* params: `RequestAccountsParams` 类型,具体参数如下
* websiteIcon: DApp 网站的 Icon 的 URI,具体会展示在用户已连接网站列表中
* websiteName: DApp 网站名称
@@ -634,7 +655,7 @@ interface RequestAccountsParams {
#### 返回值
类型说明:
```typescript
-interface ReqestAccountsResponse {
+type RequestAccountsResponse = "" | {
code: 200 | 4000 | 4001,
message: string
}
@@ -657,32 +678,24 @@ if (window.tronLink.ready) {
const fromAddress = tronweb.defaultAddress.base58;
const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
const tx = await tronweb.transactionBuilder.sendTrx(toAddress, 10, fromAddress); // 步骤1
+ let signedTx;
try {
- const signedTx = await tronweb.trx.sign(tx); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- } catch (e) {}
+ signedTx = await tronweb.trx.sign(tx); // 步骤2
+ } catch (error) {
+ if (error === "Confirmation declined by user") console.info("用户拒绝签名");
+ else console.error("签名失败", error);
+ }
+ if (signedTx) {
+ const receipt = await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
+ if (!receipt.result) console.error(receipt.code, receipt.message && tronweb.toUtf8(receipt.message));
+ }
}
```
## 兼容用法:multiSign(window.tronLink)
-```typescript
-if (window.tronLink.ready) {
- const tronweb = tronLink.tronWeb;
- const toAddress = "TDvSsdrNM5eeXNL3czpa6AxLDHZA9nwe9K";
- const fromAddress = tronweb.defaultAddress.base58; // 交易 owner:由该 active 权限控制的账户;若当前账户只是共同签名人,请显式填写被控制账户
- const activePermissionId = 2;
- const tx = await tronweb.transactionBuilder.sendTrx(
- toAddress, 10, fromAddress,
- { permissionId: activePermissionId}
- ); // 步骤1
- try {
- const signedTx = await tronweb.trx.multiSign(tx, undefined, activePermissionId); // 步骤2
- await tronweb.trx.sendRawTransaction(signedTx); // 步骤3
- } catch (e) {}
-}
-```
+按[多签转账示例](../dapp/multi-sign-transfer.md)查询交易 owner 的权限、收集签名并核对累计权重,满足阈值后再广播。使用旧版 provider 时,等待 `window.tronLink.ready` 为真,再从 `window.tronLink.tronWeb` 取得示例中的 `tronweb`。
## 兼容用法:signMessageV2(window.tronLink)
@@ -693,7 +706,13 @@ if (window.tronLink.ready) {
try {
const message = "Sign in to Example DApp\nNonce: 8f3a2c"; // 普通 UTF-8 文本
const signedString = await tronweb.trx.signMessageV2(message);
- } catch (e) {}
+ } catch (error) {
+ if (error === "Confirmation declined by user") {
+ console.info("用户拒绝签名");
+ } else {
+ console.error("消息签名或验签失败", error);
+ }
+ }
}
```
@@ -705,42 +724,48 @@ if (window.tronLink.ready) {
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc10',
options: { address: '1002000' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
// 添加 TRC20
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc20',
options: { address: 'TN3W4H6rK2ce4vX9YnFQHwKENnHjoxb3m9' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
// 添加 TRC721
if (window.tronLink.ready) {
const tronweb = tronLink.tronWeb;
try {
- tronweb.request({
+ await tronweb.request({
method: 'wallet_watchAsset',
params: {
type: 'trc721',
options: { address: 'TVtaUnsgKXhTfqSFRnHCsSXzPiXmm53nZt' },
},
});
- } catch (e) {}
+ } catch (error) {
+ console.error("wallet_watchAsset 调用失败", error);
+ }
}
```
@@ -753,5 +778,8 @@ try {
method: 'wallet_switchEthereumChain',
params: [{chainId: '0x2b6653dc'}]
});
-} catch (e) {}
+} catch (error) {
+ if (error?.code === 4001) console.info("用户拒绝切换网络");
+ else console.error("切换网络失败", error);
+}
```
diff --git a/docs/plugin-wallet/extension-core.en.md b/docs/plugin-wallet/extension-core.en.md
new file mode 100644
index 0000000..a64ef2b
--- /dev/null
+++ b/docs/plugin-wallet/extension-core.en.md
@@ -0,0 +1,45 @@
+# Extension Core (Open Source)
+
+**GitHub**: [https://github.com/TronLink/tronlink-extension-core](https://github.com/TronLink/tronlink-extension-core)
+
+`@tronlink/core` is the JavaScript and TypeScript wallet library used by the TronLink extension. Embed it in a wallet application to derive TRON and EVM accounts and sign locally. For a DApp that asks the user’s installed extension to connect or sign, use the [extension provider](active-requests.en.md).
+
+## Installation
+
+Install the npm package. It includes CommonJS and ES module entry points and TypeScript declarations.
+
+```bash
+npm install @tronlink/core
+```
+
+See the upstream prerequisites for the required Node.js, pnpm (development) and TypeScript versions. Browser builds need polyfills for Node modules such as `buffer`, `crypto`, and `stream`. [Prerequisites](https://github.com/TronLink/tronlink-extension-core/blob/main/README.md#prerequisites) · [Upstream webpack configuration](https://github.com/TronLink/tronlink-extension-core/blob/main/webpack.config.js)
+
+## Derive a TRON address
+
+Generate a mnemonic, derive the first account’s first address path, then use the derived private key to obtain the address.
+
+```ts
+import { BaseWallet, TronWallet } from '@tronlink/core';
+
+const wallet = new TronWallet();
+const mnemonic = BaseWallet.generateRandomMnemonic();
+const path = wallet.derivePath({ accountIndex: 0, addressIndex: 0 });
+const privateKey = wallet.derivePrivateKey({ mnemonic, path });
+const address = wallet.getAddressBy({ privateKey });
+```
+
+For an EVM address, use `EvmWallet` and call its `derivePath` before deriving the key. [TRON and EVM account example](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/create_account.ts)
+
+## Signing
+
+Both wallet classes support transaction, message, and typed-data signing. For TRON, pass a prepared transaction to `wallet.signTransaction({ privateKey, data: rawTransaction })`. For an EVM transaction, supply the chain configuration and unsigned transaction in `data`. Signing returns the result locally. Broadcasting is a separate step. [TRON signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/tron_signature.ts) · [EVM signing examples](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/evm_signature.ts)
+
+## Ledger and usage statistics
+
+Ledger signing requires a browser that exposes `navigator.hid`. Use `LedgerTrxSigner` with the device’s TRX app and `LedgerEvmSigner` with its ETH app.
+
+Importing the package, deriving an address, or signing locally does not start a statistics upload. To send a report, the host calls `checkAndReportXY(deps)` and supplies the upload callback. The optional `userStatistics` module groups mainnet activity by day and amount range, using UUIDs assigned to addresses on the device. [Privacy and reporting details](https://github.com/TronLink/tronlink-extension-core/blob/main/PRIVACY.md)
+
+## Version & License
+
+For the current version, see the [package manifest](https://github.com/TronLink/tronlink-extension-core/blob/main/package.json). [Apache License 2.0](https://github.com/TronLink/tronlink-extension-core/blob/main/LICENSE)
diff --git a/docs/plugin-wallet/extension-core.zh.md b/docs/plugin-wallet/extension-core.zh.md
new file mode 100644
index 0000000..c5bb831
--- /dev/null
+++ b/docs/plugin-wallet/extension-core.zh.md
@@ -0,0 +1,45 @@
+# 插件开源核心库
+
+**GitHub**: [https://github.com/TronLink/tronlink-extension-core](https://github.com/TronLink/tronlink-extension-core)
+
+`@tronlink/core` 是 TronLink 插件使用的 JavaScript / TypeScript 钱包库。钱包应用可以用它派生 TRON 和 EVM 账户,并在本地签名。DApp 如需连接用户已安装的 TronLink 插件并请求签名,请使用[插件提供的接口](active-requests.zh.md)。
+
+## 安装
+
+通过 npm 安装。该包提供 CommonJS、ES 模块入口以及 TypeScript 类型声明。
+
+```bash
+npm install @tronlink/core
+```
+
+所需的 Node.js、pnpm(开发用)和 TypeScript 版本见上游环境要求。面向浏览器打包时,需要为 `buffer`、`crypto`、`stream` 等 Node 模块配置 polyfill。[环境要求](https://github.com/TronLink/tronlink-extension-core/blob/main/README.md#prerequisites) · [上游 webpack 配置](https://github.com/TronLink/tronlink-extension-core/blob/main/webpack.config.js)
+
+## 派生 TRON 地址
+
+生成助记词,获取第一个账户下第一个地址的派生路径,再用该路径派生私钥并计算地址。
+
+```ts
+import { BaseWallet, TronWallet } from '@tronlink/core';
+
+const wallet = new TronWallet();
+const mnemonic = BaseWallet.generateRandomMnemonic();
+const path = wallet.derivePath({ accountIndex: 0, addressIndex: 0 });
+const privateKey = wallet.derivePrivateKey({ mnemonic, path });
+const address = wallet.getAddressBy({ privateKey });
+```
+
+派生 EVM 地址时,使用 `EvmWallet` 的 `derivePath` 获取对应路径,再派生私钥。[TRON 与 EVM 账户示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/create_account.ts)
+
+## 签名
+
+两个钱包类都支持交易、消息和结构化数据签名。对 TRON 交易签名时,将已构建的交易传入 `wallet.signTransaction({ privateKey, data: rawTransaction })`。对 EVM 交易签名时,在 `data` 中提供链配置和未签名交易。签名结果在本地返回,广播需另行执行。[TRON 签名示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/tron_signature.ts) · [EVM 签名示例](https://github.com/TronLink/tronlink-extension-core/blob/main/demo/evm_signature.ts)
+
+## Ledger 与使用统计
+
+Ledger 签名要求浏览器提供 `navigator.hid`。使用设备上的 TRX 应用时选择 `LedgerTrxSigner`,使用 ETH 应用时选择 `LedgerEvmSigner`。
+
+导入包、派生地址或在本地签名都不会自动上传统计数据。启用上报需要宿主调用 `checkAndReportXY(deps)` 并提供上传回调。可选的 `userStatistics` 模块使用设备上为地址分配的 UUID,按日期和金额区间汇总主网活动。[隐私与上报说明](https://github.com/TronLink/tronlink-extension-core/blob/main/PRIVACY.md)
+
+## 版本与许可证
+
+当前版本见[包配置](https://github.com/TronLink/tronlink-extension-core/blob/main/package.json)。[Apache License 2.0](https://github.com/TronLink/tronlink-extension-core/blob/main/LICENSE)
diff --git a/docs/plugin-wallet/passive-messages.en.md b/docs/plugin-wallet/passive-messages.en.md
index e898e37..408bc34 100644
--- a/docs/plugin-wallet/passive-messages.en.md
+++ b/docs/plugin-wallet/passive-messages.en.md
@@ -254,7 +254,7 @@ window.tron.on('disconnect', (providerRpcError) => {
})
```
-> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message) or [rejectWeb (postMessage)](#user-rejected-connection-message)
+> **Legacy (not recommended):** [disconnectWeb (postMessage)](#user-disconnected-website-message)
---
diff --git a/docs/plugin-wallet/passive-messages.zh.md b/docs/plugin-wallet/passive-messages.zh.md
index 8a0cb37..d175d4a 100644
--- a/docs/plugin-wallet/passive-messages.zh.md
+++ b/docs/plugin-wallet/passive-messages.zh.md
@@ -222,7 +222,7 @@ window.tron.on('disconnect', (providerRpcError) => {
})
```
-> **旧版用法(不推荐):** [disconnectWeb(postMessage)](#disconnectweb) 或 [rejectWeb(postMessage)](#rejectweb)
+> **旧版用法(不推荐):** [disconnectWeb(postMessage)](#disconnectweb)
## 历史遗留问题
diff --git a/docs/reference/error-code-map.en.md b/docs/reference/error-code-map.en.md
index b662671..61836b0 100644
--- a/docs/reference/error-code-map.en.md
+++ b/docs/reference/error-code-map.en.md
@@ -6,7 +6,7 @@ TronLink agents traverse three or four error-code dialects when a single user re
**Error shape:** On the TronLink-injected `tronWeb` (extension 4.0.0 and later), when the user rejects `trx.sign`, `trx.multiSign`, or `trx.signMessageV2`, the promise rejects with the **plain string** `'Confirmation declined by user'` — not an `Error` object, and without a numeric `code`. The `{ code: 4001, message: 'User rejected the request.' }` object is returned only by `window.tron.request(...)` methods such as `eth_requestAccounts`. Other failures (locked wallet, invalid payload, watch-only account) use other values — see [Handling rejections](#handling-rejections). Do not automatically retry signing.
-| Business meaning | DApp provider ([EIP-1474][provider]) | DeepLink ([5-digit][deeplink]) | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
+| Business meaning | DApp provider ([EIP-1474][provider]) | [DeepLink callback code][deeplink] | MCP ([`TL_*`][mcp]) | CLI v1.0.1 ([exit status][cli]) | Retryable? |
| --- | :---: | :---: | :---: | :---: | :---: |
| **User rejected** the signing or connection prompt | `4001` from `window.tron.request(...)`; the string `'Confirmation declined by user'` from `tronWeb.trx.sign` / `multiSign` / `signMessageV2` | `300` (Transaction canceled) | — (HITL — re-prompt only on a fresh tool call) | `1` | **No** |
| **Invalid input** / malformed params | thrown by `tronWeb` builder | `10001`–`10020`, `10024`, `10025` | `TL_INVALID_INPUT` | `1` | **No** — fix the payload |
diff --git a/docs/reference/error-code-map.zh.md b/docs/reference/error-code-map.zh.md
index f2b73d4..a00645f 100644
--- a/docs/reference/error-code-map.zh.md
+++ b/docs/reference/error-code-map.zh.md
@@ -6,7 +6,7 @@ TronLink 智能体在一次用户请求里跨 DApp provider → DeepLink → MCP
**错误结构:** 在 TronLink 注入的 `tronWeb` 上(插件 4.0.0 起),用户拒绝 `trx.sign`、`trx.multiSign` 或 `trx.signMessageV2` 时,Promise 以**纯字符串** `'Confirmation declined by user'` reject——不是 `Error` 对象,也没有数字 `code`。`{ code: 4001, message: 'User rejected the request.' }` 对象只由 `window.tron.request(...)` 方法(如 `eth_requestAccounts`)返回。其他失败(钱包未解锁、载荷非法、观察钱包等)返回其他值——参见[处理拒签](#handling-rejections)。不要自动重试签名。
-| 业务含义 | DApp provider([EIP-1474][provider]) | DeepLink([5 位码][deeplink]) | MCP([`TL_*`][mcp]) | CLI v1.0.1([退出状态][cli]) | 可重试? |
+| 业务含义 | DApp provider([EIP-1474][provider]) | [DeepLink 回调码][deeplink] | MCP([`TL_*`][mcp]) | CLI v1.0.1([退出状态][cli]) | 可重试? |
| --- | :---: | :---: | :---: | :---: | :---: |
| **用户拒绝**签名或连接弹窗 | `window.tron.request(...)` 为 `4001`;`tronWeb.trx.sign` / `multiSign` / `signMessageV2` 为字符串 `'Confirmation declined by user'` | `300`(交易取消) | —(HITL——只能在新的 tool 调用里再次唤起) | `1` | **否** |
| **参数非法** / payload 错 | `tronWeb` 构造器抛错 | `10001`–`10020`、`10024`、`10025` | `TL_INVALID_INPUT` | `1` | **否**——修参数 |
diff --git a/docs/reference/faq.zh.md b/docs/reference/faq.zh.md
index e874541..2d5aeca 100644
--- a/docs/reference/faq.zh.md
+++ b/docs/reference/faq.zh.md
@@ -24,7 +24,7 @@
## DApp 需要特定网络
-用 `wallet_switchEthereumChain`(TIP-3326)请求切换,传入目标十六进制 `chainId`。参见 [chainId 取值](networks.md)与[切换网络](../plugin-wallet/active-requests.md)。通过 `chainChanged` 确认当前网络。
+用 `wallet_switchEthereumChain`(TIP-3326)请求切换,传入目标十六进制 `chainId`。参见 [chainId 取值](networks.md)与[切换网络](../plugin-wallet/active-requests.md#tip-3326)。通过 `chainChanged` 确认当前网络。
## 交易因资源不足而失败
diff --git a/docs/reference/glossary.en.md b/docs/reference/glossary.en.md
index 359536d..d154dcb 100644
--- a/docs/reference/glossary.en.md
+++ b/docs/reference/glossary.en.md
@@ -36,7 +36,7 @@ Definitions of terms, standards, and identifiers used across this documentation.
- **ABI** — Application Binary Interface: the JSON description of a contract's callable methods and events. If a token contract's ABI lacks a recognized method (e.g. `transfer`, `approve`), TronLink may not be able to offer that action.
- **`chainId`** — the network identifier. TronLink uses the hex form (e.g. `0x2b6653dc`) for `wallet_switchEthereumChain` and `chainChanged`, and the decimal EVM form (e.g. `728126428`) for EIP-712 `domain.chainId`. See [Networks & Addresses](networks.md).
- **`ProviderRpcError`** — the EIP-1193 error object emitted on `disconnect`, shaped `{ code: number; message: string; data?: unknown }`.
-- **permission id** — the active permission index used for multi-signature transactions (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
+- **permission id** — the value of the selected active permission’s `id` field on the transaction owner’s account (passed to `tronWeb.trx.multiSign`). See [Multi-Signature Transfer](../dapp/multi-sign-transfer.md).
- **base58 / hex address** — the two TRON address encodings (`T...` vs `41...`). See [Networks & Addresses](networks.md#address-formats).
## AI tooling
diff --git a/docs/reference/glossary.zh.md b/docs/reference/glossary.zh.md
index 2563183..c7a19fa 100644
--- a/docs/reference/glossary.zh.md
+++ b/docs/reference/glossary.zh.md
@@ -36,7 +36,7 @@
- **ABI** —— Application Binary Interface,合约可调用方法与事件的 JSON 描述。若代币合约的 ABI 缺少可识别的方法(如 `transfer`、`approve`),TronLink 可能无法提供相应操作。
- **`chainId`** —— 网络标识。TronLink 在 `wallet_switchEthereumChain` 和 `chainChanged` 用十六进制形式(如 `0x2b6653dc`),在 EIP-712 的 `domain.chainId` 用十进制 EVM 形式(如 `728126428`)。参见[网络与地址](networks.md)。
- **`ProviderRpcError`** —— EIP-1193 在 `disconnect` 时抛出的错误对象,结构为 `{ code: number; message: string; data?: unknown }`。
-- **permission id** —— 多签交易使用的活动权限索引(传给 `tronWeb.trx.multiSign`)。参见[多签转账](../dapp/multi-sign-transfer.md)。
+- **permission id** —— 交易 owner 账户中所选活动权限条目的 `id` 字段值(传给 `tronWeb.trx.multiSign`)。参见[多签转账](../dapp/multi-sign-transfer.md)。
- **base58 / hex 地址** —— TRON 地址的两种编码(`T...` 与 `41...`)。参见[网络与地址](networks.md)。
## AI 工具
diff --git a/docs/reference/networks.zh.md b/docs/reference/networks.zh.md
index f82df09..92f5922 100644
--- a/docs/reference/networks.zh.md
+++ b/docs/reference/networks.zh.md
@@ -2,6 +2,8 @@
汇总本文档各处用到的网络参数与常用地址。
+
+
## 网络
| 网络 | `chainId`(十六进制) | EVM chainId(十进制) | RPC 端点 | 浏览器 |
diff --git a/docs/stylesheets/extra.css b/docs/stylesheets/extra.css
index 73a338d..5db019d 100644
--- a/docs/stylesheets/extra.css
+++ b/docs/stylesheets/extra.css
@@ -40,12 +40,8 @@ color: #3C7CF3!important;
padding-top: 0; /* 移除顶部内边距 */
}
-.md-footer {
- background-color: var(--md-default-bg-color);
-}
-
-.md-footer {
- display: none !important; /* 隐藏底部导航 */
+.md-footer__inner {
+ display: none; /* 翻页导航已在正文下方展示 */
}
.md-sidebar--secondary {
@@ -160,4 +156,4 @@ a.card-link:hover {
.md-footer__link--prev .md-footer__title {
display: block;
}
-}
\ No newline at end of file
+}
diff --git a/mkdocs.yml b/mkdocs.yml
index 5744244..7df685f 100644
--- a/mkdocs.yml
+++ b/mkdocs.yml
@@ -62,10 +62,13 @@ plugins:
- Asset Management: mobile/asset-management.en.md
- DeepLink: mobile/deeplink.en.md
- DApp Support: mobile/dapp-support.en.md
+ - Android Core (Open Source): mobile/android-core.en.md
+ - iOS Core (Open Source): mobile/ios-core.en.md
- TronLink Wallet Extension:
- Request TronLink Extension: plugin-wallet/active-requests.en.md
- Receive messages from TronLink: plugin-wallet/passive-messages.en.md
- Compatibility for the v field after Ledger signing: plugin-wallet/ledger-signing-update.en.md
+ - Extension Core (Open Source): plugin-wallet/extension-core.en.md
- AI Support:
- AI / LLMs: ai-support/ai-llms.en.md
- MCP Server TronLink : ai-support/mcp-server-tronlink.en.md
@@ -96,10 +99,13 @@ plugins:
- 资产管理: mobile/asset-management.zh.md
- DeepLink: mobile/deeplink.zh.md
- DApp支持: mobile/dapp-support.zh.md
+ - Android 开源核心库: mobile/android-core.zh.md
+ - iOS 开源核心库: mobile/ios-core.zh.md
- 插件钱包:
- 主动请求TronLink插件功能: plugin-wallet/active-requests.zh.md
- 被动接收TronLink插件的消息: plugin-wallet/passive-messages.zh.md
- 对ledger签名后的v字段兼容: plugin-wallet/ledger-signing-update.zh.md
+ - 插件开源核心库: plugin-wallet/extension-core.zh.md
- AI 支持:
- AI / LLMs: ai-support/ai-llms.zh.md
- MCP Server TronLink : ai-support/mcp-server-tronlink.zh.md
@@ -125,6 +131,7 @@ plugins:
# Markdown 扩展(开启 mermaid 图表渲染)
markdown_extensions:
- admonition
+ - attr_list
- pymdownx.details
- pymdownx.superfences:
custom_fences:
@@ -132,8 +139,12 @@ markdown_extensions:
class: mermaid
format: !!python/name:pymdownx.superfences.fence_code_format
+# 隐藏页脚中的 "Made with Material for MkDocs"
+extra:
+ generator: false
+
# 版权信息
-copyright: Copyright © 2025 TronLink Team
+copyright: Copyright © 2025–2026 TronLink Team
# 验证
validation:
diff --git a/scripts/gen_llms_full.py b/scripts/gen_llms_full.py
index 3c1a42f..29e7528 100644
--- a/scripts/gen_llms_full.py
+++ b/scripts/gen_llms_full.py
@@ -60,9 +60,12 @@
"mobile/asset-management.en.md",
"mobile/deeplink.en.md",
"mobile/dapp-support.en.md",
+ "mobile/android-core.en.md",
+ "mobile/ios-core.en.md",
"plugin-wallet/active-requests.en.md",
"plugin-wallet/passive-messages.en.md",
"plugin-wallet/ledger-signing-update.en.md",
+ "plugin-wallet/extension-core.en.md",
"ai-support/mcp-server-tronlink.en.md",
"ai-support/tronlink-mcp-core.en.md",
"ai-support/tronlink-skills.en.md",
@@ -88,9 +91,12 @@
"mobile/asset-management.zh.md",
"mobile/deeplink.zh.md",
"mobile/dapp-support.zh.md",
+ "mobile/android-core.zh.md",
+ "mobile/ios-core.zh.md",
"plugin-wallet/active-requests.zh.md",
"plugin-wallet/passive-messages.zh.md",
"plugin-wallet/ledger-signing-update.zh.md",
+ "plugin-wallet/extension-core.zh.md",
"ai-support/mcp-server-tronlink.zh.md",
"ai-support/tronlink-mcp-core.zh.md",
"ai-support/tronlink-skills.zh.md",
@@ -146,6 +152,17 @@ def page_url(rel: str, lang: str) -> str:
return f"{slug}/"
+ANCHOR_LINE_RE = re.compile(r'^\n\n?', re.M)
+HEADING_ANCHOR_RE = re.compile(r'^(#{1,6} )', re.M)
+HEADING_ID_RE = re.compile(r"^(#{1,6} .*?) \{#[^}]+\}$", re.M)
+
+
+def strip_anchor_markup(text: str) -> str:
+ """Drop site-only anchors (`` tags, heading `{#id}` attrs) that are noise in plain text."""
+ text = HEADING_ANCHOR_RE.sub(r"\1", ANCHOR_LINE_RE.sub("", text))
+ return HEADING_ID_RE.sub(r"\1", text)
+
+
def render_bundle(pages: list[str], lang: str, sha: str, generated_at: str) -> tuple[str, int, list[str]]:
"""Return (full_text, page_count, missing) for one language."""
body_parts: list[str] = []
@@ -159,7 +176,7 @@ def render_bundle(pages: list[str], lang: str, sha: str, generated_at: str) -> t
body_parts.append("")
body_parts.append(f"")
body_parts.append("")
- body_parts.append(path.read_text(encoding="utf-8").rstrip())
+ body_parts.append(strip_anchor_markup(path.read_text(encoding="utf-8")).rstrip())
body_parts.append("")
body = "\n".join(body_parts)