# Monad Agentic Wallet
Agent-native 钱包与支付控制平面 —— 让 AI Agent 在用户策略约束下安全执行链上/链下支付,无需暴露根私钥。
## 目录
- [项目概览](#项目概览)
- [架构](#架构)
- [快速开始](#快速开始)
- [核心概念](#核心概念)
- [Agent 接入指南](#agent-接入指南)
- [策略引擎](#策略引擎)
- [支付路由](#支付路由)
- [会话授权](#会话授权)
- [审计与收据](#审计与收据)
- [紧急恢复](#紧急恢复)
- [管理后台](#管理后台)
- [x402 服务端](#x402-服务端)
- [环境变量](#环境变量)
- [开发](#开发)
- [安全模型](#安全模型)
- [文档索引](#文档索引)
---
## 项目概览
Monad Agentic Wallet 解决的核心问题:**如何让 AI Agent 自主执行支付,同时保证用户资金安全?**
核心设计原则:
| 原则 | 实现 |
|------|------|
| Agent 不触碰根密钥 | Session Key 隔离签名,AES-256-GCM 加密存储 |
| 默认拒绝 | 策略引擎默认 deny,白名单显式放行 |
| 热路径无人工审批 | 策略+风控自动决策,高风险自动暂停/阻断 |
| 审计优先 | 每笔支付完整审计链路,收据结构化可导出 |
| 可恢复 | 紧急暂停、会话撤销、钱包恢复全链路 |
---
## 架构
```
┌─────────────────────────────────────────────────────┐
│ Apps (应用层) │
│ ┌───────────┐ ┌──────────────┐ ┌────────────────┐ │
│ │ MCP Server│ │ Approval UI │ │ x402 Server │ │
│ │ (Agent入口)│ │ (管理后台) │ │ (付费端点) │ │
│ └─────┬─────┘ └──────┬───────┘ └───────┬────────┘ │
│ │ │ │ │
│ ┌─────┴─────┐ │ │ │
│ │ CLI │ │ │ │
│ │ (本地演示) │ │ │ │
│ └───────────┘ │ │ │
├────────────────────────┼──────────────────┼───────────┤
│ Core (核心层) │ │
│ ┌─────┐ ┌────────────┐ ┌──────────┐ ┌───┴────┐ │
│ │ SDK │ │Policy Engine│ │Risk Engine│ │Payment │ │
│ │ │ │ (策略引擎) │ │(风控引擎) │ │ Router │ │
│ └──┬──┘ └────────────┘ └──────────┘ └───┬────┘ │
│ │ ┌──────────────┐ ┌──────────┐ │ │
│ └────│ Wallet Core │ │ Audit │────┘ │
│ │(钱包/会话/存储)│ │(审计/收据)│ │
│ └──────────────┘ └──────────┘ │
├───────────────────────────────────────────────────────┤
│ Infrastructure (基础设施层) │
│ ┌──────────┐ ┌───────────┐ ┌───────────────────┐ │
│ │ PG Store │ │File Store │ │ Contracts │ │
│ │(生产存储) │ │(开发存储) │ │ (Monad智能合约) │ │
│ └──────────┘ └───────────┘ └───────────────────┘ │
└───────────────────────────────────────────────────────┘
```
### Monorepo 结构
| 路径 | 包名 | 职责 |
|------|------|------|
| `packages/sdk` | `@agentic-wallet/sdk` | 核心类型定义 + 客户端接口 |
| `packages/policy-engine` | `@agentic-wallet/policy-engine` | 默认拒绝策略评估、目标归一化 |
| `packages/risk-engine` | `@agentic-wallet/risk-engine` | 风控信号检测 |
| `packages/wallet-core` | `@agentic-wallet/wallet-core` | 会话授权、安全存储、恢复 |
| `packages/payment-router` | `@agentic-wallet/payment-router` | 三路由支付执行 |
| `packages/pg-store` | `@agentic-wallet/pg-store` | PostgreSQL 存储实现 |
| `packages/audit` | `@agentic-wallet/audit` | 审计事件与收据 |
| `apps/mcp-server` | `@agentic-wallet/mcp-server` | MCP 服务(Agent 主入口) |
| `apps/x402-server` | `@agentic-wallet/x402-server` | x402 付费端点服务 |
| `apps/approval-ui` | `@agentic-wallet/approval-ui` | 管理后台 Web UI |
| `apps/cli` | `@agentic-wallet/cli` | CLI 本地演示 |
| `contracts` | — | Monad 智能合约(规划中) |
---
## 快速开始
### 前置条件
- Node.js >= 18
- pnpm >= 10
- PostgreSQL(生产模式必须,开发模式可选)
### 安装
```bash
git clone <repo-url>
cd Monad
pnpm install
pnpm build
```
### 环境配置
**生产模式(PostgreSQL)**:
```bash
# .env
PG_HOST=localhost
PG_PORT=5432
PG_DATABASE=agentic_wallet
PG_USER=wallet
PG_PASSWORD=your_secure_password
# 可选:x402 配置
PAY_TO_ADDRESS=0xYourEvmWalletAddress
X402_FACILITATOR_URL=https://x402-facilitator.molandak.org
MONAD_RPC_URL=https://testnet-rpc.monad.xyz
```
**开发模式(文件存储)**:
MCP Server 当前强依赖 PostgreSQL。如果需要在无 PG 环境运行 CLI 演示,CLI 会使用本地文件存储。
### 启动服务
```bash
# 启动 MCP Server(Agent 通过此服务提交支付请求)
pnpm dev
# 启动 x402 付费端点(可选,提供 HTTP 402 收费 API)
pnpm dev:x402
# 启动管理后台(可选,Web UI 查看策略/审计/会话)
pnpm dev:approval-ui
# 管理后台 CLI 模式(终端 Markdown 仪表盘)
pnpm console:approval-ui
```
---
## 核心概念
### PaymentIntent(支付意图)
Agent 提交支付的核心数据结构:
```typescript
interface PaymentIntent {
intentId: string; // 唯一标识,用于幂等
context: {
taskId: string; // 关联任务 ID
agentId: string; // Agent 标识
userId: string; // 用户标识
workspaceId: string; // 工作区标识
reason: string; // 机器可读支付原因
category: PaymentCategory; // 分类: api | storage | compute | contract | transfer | other
requestedAt: string; // 请求时间 ISO 8601
};
amount: string; // 金额(最小单位)
asset: AssetSymbol; // 资产: "MON" | "USDC"
recipient: string; // 收款方(地址/合约/vendor:xxx)
chainId: string; // 链 ID("10143" = Monad Testnet)
routePreference?: PaymentRoute[]; // 路由偏好顺序
vendorId?: string; // 供应商标识
contractAddress?: string; // 合约地址
method?: string; // 调用方法
validityWindowSeconds: number; // 授权有效期(秒)
metadata?: Record<string, string>; // 路由特定元数据
}
```
### PaymentEvaluationResult(评估结果)
系统对支付意图的完整响应:
```typescript
interface PaymentEvaluationResult {
intent: PaymentIntent;
policy: PolicyDecision; // 策略决策: allowed | denied | paused | ...
risk: RiskDecision; // 风控评估
normalizedTarget?: NormalizedPaymentTarget; // 归一化收款目标
grant?: SessionGrant; // 会话授权(仅 allowed 时)
receipt?: ExecutionReceipt; // 执行收据(仅执行成功时)
auditTrail: AuditEvent[]; // 完整审计链路
outcome: PaymentOutcome; // 最终结果: blocked | executed | failed
policyVersion: string; // 命中的策略版本
matchedRuleIds: string[]; // 命中的规则
providerId?: string; // 归一化服务提供方
normalizedCategory?: string; // 归一化分类
normalizedTargetType?: string; // 归一化目标类型
}
```
### 决策状态流
```
┌─────────────────────────────────────────┐
│ PaymentIntent 提交 │
└───────────────────┬─────────────────────┘
│
┌───────────▼───────────┐
│ 策略快照是否可解析? │
└───┬───────────────┬───┘
Yes No
│ │
┌────────▼────────┐ ┌──▼──────────┐
│ 目标归一化+幂等 │ │ denied │
│ + 钱包暂停检查 │ │ policy_load │
└────────┬────────┘ │ _failed │
│ └─────────────┘
┌──────────▼──────────┐
│ 风控评估 + 策略评估 │
└──┬──────┬──────┬───┘
│ │ │
allowed blocked risk_blocked
│ │ │
│ │ └──► paused(风控阻断升级)
│ └────────► denied
│
┌────────▼────────┐
│ 预算预留 │
└──┬──────────┬───┘
OK 冲突
│ │
┌──────▼─────┐ ┌─▼───────────────────┐
│会话授权检查 │ │ denied │
└──┬─────┬──┘ │ budget_reservation │
OK 失败 │ _conflict │
│ │ └──────────────────────┘
│ └────► requires_reauthorization
│
┌────▼─────┐
│路由执行 │
└──┬───┬───┘
成功 失败
│ │
▼ └──► 预算释放,抛出异常
receipt
committed
```
---
## Agent 接入指南
### 方式一:MCP Server(推荐)
AI Agent 通过 MCP 协议与钱包交互,这是最标准的接入方式。
#### 1. 启动 MCP Server
```bash
# 确保 PostgreSQL 已配置
pnpm dev
```
MCP Server 通过 stdio 通信,可被 Claude Desktop、Cursor、Windsurf 等 MCP 客户端直接加载。
#### 2. 在 MCP 客户端中配置
在 MCP 客户端的配置文件中添加:
```json
{
"mcpServers": {
"agentic-wallet": {
"command": "node",
"args": ["path/to/Monad/apps/mcp-server/dist/index.js"],
"env": {
"PG_HOST": "localhost",
"PG_PORT": "5432",
"PG_DATABASE": "agentic_wallet",
"PG_USER": "wallet",
"PG_PASSWORD": "your_password"
}
}
}
}
```
#### 3. Agent 可用的 MCP 工具
| 工具名 | 用途 | 关键参数 |
|--------|------|----------|
| `submit_payment` | 提交支付请求 | `intent: PaymentIntent` |
| `store_session_signer` | 存储会话签名密钥 | `grant: SessionGrant`, `privateKey: string` |
| `list_audit_events` | 查询审计事件 | `limit?: number` |
| `revoke_session_grant` | 撤销会话授权 | `sessionKey: string` |
| `emergency_pause` | 紧急暂停钱包 | `initiatedBy: string`, `reason: string` |
| `resume_wallet` | 恢复钱包 | `initiatedBy: string` |
| `revoke_agent_sessions` | 撤销 Agent 所有会话 | `agentId: string`, `initiatedBy: string`, `reason: string` |
| `submit_policy_config` | 提交策略配置变更 | `policyConfig: PolicyConfig` |
| `setup_x402_endpoint` | 配置 x402 收费端点 | `payToAddress: string`, `endpoints?: Endpoint[]` |
#### 4. Agent 提交支付示例
Agent 调用 `submit_payment` 时传入 `PaymentIntent`:
**示例 1:API 付费调用(x402 路由)**
```json
{
"intent": {
"intentId": "task-123-api-call-1",
"context": {
"taskId": "task-123",
"agentId": "coding-agent-v1",
"userId": "user-alice",
"workspaceId": "ws-engineering",
"reason": "调用 GPT-4 API 完成代码审查",
"category": "api",
"requestedAt": "2025-04-12T10:30:00Z"
},
"amount": "1000",
"asset": "USDC",
"recipient": "0xApiServiceProvider",
"chainId": "10143",
"routePreference": ["x402"],
"validityWindowSeconds": 300,
"metadata": {
"x402:url": "https://api.example.com/v1/complete",
"x402:method": "POST",
"x402:body": "{\"prompt\":\"review this code\"}",
"x402:content-type": "application/json"
}
}
}
```
**示例 2:链上合约交互(monad-direct 路由)**
```json
{
"intent": {
"intentId": "task-456-contract-1",
"context": {
"taskId": "task-456",
"agentId": "trading-agent-v1",
"userId": "user-bob",
"workspaceId": "ws-finance",
"reason": "执行 DEX swap 合约调用",
"category": "contract",
"requestedAt": "2025-04-12T11:00:00Z"
},
"amount": "5000000",
"asset": "MON",
"recipient": "0xDexContractAddress",
"chainId": "10143",
"contractAddress": "0xDexContractAddress",
"routePreference": ["monad-direct"],
"validityWindowSeconds": 60
}
}
```
**示例 3:MPP 支付(推送/拉取模式)**
```json
{
"intent": {
"intentId": "task-789-mpp-1",
"context": {
"taskId": "task-789",
"agentId": "data-agent-v1",
"userId": "user-carol",
"workspaceId": "ws-data",
"reason": "购买数据集访问权限",
"category": "api",
"requestedAt": "2025-04-12T12:00:00Z"
},
"amount": "2000",
"asset": "USDC",
"recipient": "0xDataProvider",
"chainId": "10143",
"routePreference": ["mpp"],
"validityWindowSeconds": 300,
"metadata": {
"mpp:url": "https://data-provider.example.com/charge",
"mpp:mode": "push"
}
}
}
```
#### 5. 理解支付结果
Agent 收到的响应中,关键字段:
```jsonc
{
"outcome": "executed", // 或 "blocked"
"policy": {
"status": "allowed", // 或 denied, paused, requires_reauthorization, requires_human_intervention
"reasonCodes": [], // 拒绝原因码
"allowedRoutes": ["x402"] // 允许的路由
},
"receipt": { // 仅 executed 时存在
"taskId": "task-123",
"agentId": "coding-agent-v1",
"payee": "0xApiServiceProvider",
"amount": "1000",
"asset": "USDC",
"signingMode": "x402-facilitator",
"executionRoute": "x402",
"reference": "0xTxHash..." // 链上/结算引用
}
}
```
**常见拒绝原因码及 Agent 处理策略**:
| 原因码 | 含义 | Agent 应对 |
|--------|------|-----------|
| `policy_load_failed` | 策略加载失败 | 提示用户检查策略配置 |
| `asset_not_allowed` | 资产不在白名单 | 更换资产或请求策略更新 |
| `recipient_not_allowed` | 收款方不在白名单 | 确认收款方或请求加入白名单 |
| `amount_exceeds_limit` | 金额超限 | 降低金额或请求提升额度 |
| `daily_budget_exceeded` | 日预算耗尽 | 等待次日或请求提高日预算 |
| `weekly_budget_exceeded` | 周预算耗尽 | 等待下周或请求提高周预算 |
| `risk_engine_blocked` | 风控拦截 | 检查收款方安全性,请求人工审核 |
| `budget_reservation_conflict` | 预算预留冲突 | 重试或等待其他支付完成 |
| `session_authorization_failed` | 会话授权失败 | 重新提交支付意图 |
| `grant_policy_version_invalidated` | 策略已变更,授权失效 | 重新提交(会自动用新策略) |
| `wallet_paused` | 钱包已暂停 | 请求管理员恢复钱包 |
| `idempotency_conflict` | 幂等冲突 | 检查 intentId 是否被复用 |
### 方式二:SDK 编程接入
适合自定义 Agent 框架或后端服务集成。
```typescript
import {LocalAgentWalletClient} from "@agentic-wallet/sdk";
import {LocalMcpTransport} from "@agentic-wallet/mcp-server";
// 创建客户端
const client = new LocalAgentWalletClient(new LocalMcpTransport({
// 可选:传入自定义 PaymentEvaluationOptions
// pgConfig, dataDir, routeDependencies 等
}));
// 提交支付
const result = await client.submitPayment({
intentId: `intent-${Date.now()}`,
context: {
taskId: "my-task",
agentId: "my-agent",
userId: "user-1",
workspaceId: "ws-1",
reason: "购买 API 调用额度",
category: "api",
requestedAt: new Date().toISOString(),
},
amount: "1000",
asset: "USDC",
recipient: "vendor:demo",
chainId: "10143",
validityWindowSeconds: 300,
});
if (result.outcome === "executed") {
console.log("支付成功:", result.receipt?.reference);
} else {
console.log("支付被拒:", result.policy.reasonCodes);
}
```
### 方式三:CLI 演示
```bash
# 运行内置演示(使用默认策略 + 文件存储)
npx tsx apps/cli/src/index.ts
```
---
## 策略引擎
策略引擎采用**默认拒绝**(default-deny)模型:所有支付请求初始状态为 denied,必须显式通过白名单和额度检查才能变为 allowed。
### PolicyConfig 结构
```typescript
interface PolicyConfig {
defaultAction: "deny"; // 固定为 deny
allowedAssets: AssetSymbol[]; // 允许的资产 ["MON", "USDC"]
allowedRecipients: string[]; // 允许的收款方白名单
allowedContracts: string[]; // 允许的合约白名单
allowedVendors: string[]; // 允许的供应商标识
allowedMethods: string[]; // 允许的调用方法
maxAmountPerPayment: string; // 单笔最大金额
maxDailySpend: string; // 日预算上限
maxWeeklySpend: string; // 周预算上限
longLivedAgentMaxAmount: string; // 长驻 Agent 单笔上限
temporaryAgentMaxAmount: string; // 临时 Agent 单笔上限
allowedProviderIds?: ProviderId[]; // 允许的验证服务商
allowedCategories?: PaymentCategory[]; // 允许的支付分类
verifiedProvidersOnly?: boolean; // 仅允许已验证服务商
servicePurchaseOnly?: boolean; // 仅允许服务购买(禁止个人地址转账)
humanInterventionThresholdAmount?: string; // 触发人工审核的金额阈值
}
```
### 策略版本与继承
```
Workspace 基线策略(workspace scope)
│
├── Agent A 无覆盖 → 直接使用基线策略
│
└── Agent B 有覆盖 → 基线 + Agent 覆盖合并
(覆盖只替换显式给出的字段)
```
**关键特性**:
- **追加式版本控制**:策略不可变,新版本追加,通过 ActivePolicyPointer 指向当前版本
- **Agent 级覆盖**:只替换显式给出的字段,其余沿用 workspace 基线
- **会话绑定策略版本**:Session Grant 绑定 `policyVersionId`,策略变更后授权自动失效
### 评估检查链(按顺序)
1. 分类解析失败 → deny (`category_resolution_failed`)
2. 服务商解析失败 → deny (`provider_resolution_failed`)
3. 资产不在白名单 → deny (`asset_not_allowed`)
4. 收款方不在白名单 → deny (`recipient_not_allowed`)
5. 合约不在白名单 → deny (`contract_not_allowed`)
6. 供应商不在白名单 → deny (`vendor_not_allowed`)
7. 方法不在白名单 → deny (`method_not_allowed`)
8. 有效期无效 → deny (`invalid_validity_window`)
9. 单笔金额超限 → deny (`amount_exceeds_limit`)
10. 日预算超限 → deny (`daily_budget_exceeded`)
11. 周预算超限 → deny (`weekly_budget_exceeded`)
12. 全部通过 → allowed
### 提交策略变更
通过 MCP 工具 `submit_policy_config` 提交变更,会创建待审核文件:
```json
{
"policyConfig": {
"defaultAction": "deny",
"allowedAssets": ["MON", "USDC"],
"allowedRecipients": ["vendor:demo", "vendor:openai"],
"allowedContracts": [],
"allowedVendors": ["vendor:demo", "vendor:openai"],
"allowedMethods": [],
"maxAmountPerPayment": "10",
"maxDailySpend": "50",
"maxWeeklySpend": "200",
"longLivedAgentMaxAmount": "5",
"temporaryAgentMaxAmount": "10"
}
}
```
---
## 支付路由
系统支持三种支付路由,策略引擎根据支付分类自动推断路由优先级:
| 路由 | 适用场景 | 协议 |
|------|----------|------|
| `monad-direct` | 链上转账、合约交互 | Monad RPC 直连 |
| `x402` | HTTP API 付费调用 | x402 HTTP 402 协议 |
| `mpp` | ERC-3009 推拉支付 | MPP charge 协议 |
### 路由优先级推断
| 分类 | 优先级顺序 |
|------|-----------|
| `api` | x402 → mpp → monad-direct |
| `contract` | monad-direct → mpp → x402 |
| 其他 | monad-direct → mpp → x402 |
### x402 路由详解
x402 是 HTTP 402 协议,用于 API 付费调用。流程:
```
Agent x402 Server Facilitator
│ │ │
│ 1. GET /api/premium │ │
│─────────────────────────►│ │
│ │ │
│ 2. 402 + PAYMENT-REQUIRED 头 │
│◄─────────────────────────│ │
│ │ │
│ 3. 解析 PAYMENT-REQUIRED, │
│ 用 Session Key 签名, │
│ 生成 PAYMENT-SIGNATURE │
│ │ │
│ 4. GET /api/premium │ │
│ + PAYMENT-SIGNATURE │ │
│─────────────────────────►│ │
│ │ 5. 验证签名 │
│ │────────────────────────►│
│ │ │
│ │ 6. isValid: true │
│ │◄────────────────────────│
│ │ │
│ 7. 200 + 数据 + PAYMENT-RESPONSE │
│◄─────────────────────────│ │
```
**metadata 必填字段**:
| 字段 | 说明 |
|------|------|
| `x402:url` | 目标收费 API 地址 |
| `x402:method` | HTTP 方法(默认 GET) |
| `x402:body` | 请求体(POST 时) |
| `x402:content-type` | 内容类型 |
| `x402:header:*` | 自定义请求头 |
**委托模式(Delegated Mode)**:MCP Server 默认启用委托模式,拒绝 Agent 内联传入的 `x402:payment-signature`,强制使用后端 Session Signer 生成签名。这防止了恶意 Agent 伪造签名绕过策略。
### monad-direct 路由详解
直接在 Monad 链上执行交易:
- **USDC**:ERC-20 `transfer` 调用
- **MON**:原生代币转账
需要通过 `metadata["monad:private-key"]` 或依赖注入提供私钥。
### mpp 路由详解
MPP(Machine Payment Protocol)支持两种子模式:
| 模式 | 流程 |
|------|------|
| **Push** | Agent 广播 USDC 转账 → 重试请求时携带 `x-mpp-tx-hash` |
| **Pull** | Agent 生成 ERC-3009 `TransferWithAuthorization` EIP-712 签名 → 携带 `x-mpp-authorization` 头 |
---
## 会话授权
Session Grant 是 Agent 执行支付的核心授权凭证,具有以下约束:
### SessionGrant 结构
```typescript
interface SessionGrant {
sessionId: string; // 会话 ID
agentId: string; // Agent 标识
userId: string; // 用户标识
workspaceId: string; // 工作区标识
allowedAssets: AssetSymbol[]; // 允许的资产
allowedRecipients: string[]; // 允许的收款方(空=不限制)
allowedMethods: string[]; // 允许的方法(空=不限制)
maxAmountPerPayment: string; // 单笔最大金额
maxUses: number; // 最大使用次数
remainingUses: number; // 剩余使用次数
expiresAt: string; // 过期时间
policyVersionId?: string; // 绑定的策略版本
revokedAt?: string; // 撤销时间
}
```
### 授权检查
每次支付都会检查:
1. **撤销状态**:`revokedAt` 是否存在
2. **过期时间**:`expiresAt` 是否已过
3. **剩余次数**:`remainingUses > 0`
4. **资产匹配**:`allowedAssets` 包含当前资产
5. **收款方匹配**:`allowedRecipients` 非空时需包含当前收款方
6. **方法匹配**:`allowedMethods` 非空时需包含当前方法
7. **单笔额度**:`amount <= maxAmountPerPayment`
8. **策略版本**:`policyVersionId` 与当前策略快照一致
### Session Key 安全
- Session 私钥独立于根密钥,Agent 无法获取根密钥
- 私钥使用 AES-256-GCM + scrypt 派生密钥加密存储
- 环境变量 `AGENTIC_WALLET_KEYSTORE_SECRET` 控制加密密钥
- 每次支付消费后 `remainingUses` 递减
---
## 审计与收据
### 审计事件类型
| 事件 | 触发时机 |
|------|----------|
| `payment_requested` | 收到支付请求 |
| `payment_authorized` | 策略+风控通过 |
| `payment_blocked` | 被策略/风控/预算拒绝 |
| `payment_executed` | 支付执行成功 |
### ExecutionReceipt 结构
每笔成功支付的收据:
```typescript
interface ExecutionReceipt {
taskId: string; // 关联任务
agentId: string; // Agent 标识
userId: string; // 用户标识
payee: string; // 收款方
amount: string; // 金额
asset: AssetSymbol; // 资产
matchedPolicy: string[]; // 命中的策略规则
signingMode: SigningMode; // 签名模式
riskLevel: RiskLevel; // 风险等级
result: "success" | "failed"; // 执行结果
timestamp: string; // 时间戳
executionRoute: PaymentRoute; // 执行路由
reference?: string; // 链上/结算引用
}
```
### 幂等保障
- 相同 `intentId` 不会重复执行
- 支付意图通过 SHA-256 指纹检测冲突
- 指纹覆盖:intentId + workspaceId + agentId + amount + asset + recipient + normalizedTarget + policyVersionId
---
## 紧急恢复
### 紧急暂停
```bash
# 通过 MCP 工具
emergency_pause({
initiatedBy: "admin",
reason: "检测到异常支付行为"
})
```
效果:
- 钱包状态变为 `paused`
- 所有活跃 Session Grant 被撤销
- 新支付请求将被拒绝(`wallet_paused`)
### 恢复钱包
```bash
resume_wallet({
initiatedBy: "admin"
})
```
### 撤销特定 Agent 会话
```bash
revoke_agent_sessions({
agentId: "suspicious-agent",
initiatedBy: "admin",
reason: "该 Agent 行为异常"
})
```
### 撤销单个会话
```bash
revoke_session_grant({
sessionKey: "session:userId:agentId:sessionId"
})
```
---
## 管理后台
Approval UI 提供可视化的管理界面,包含以下页面:
| 页面 | 路径 | 功能 |
|------|------|------|
| 审核工单 | `/tickets` | 查看和处理支付审核请求 |
| 会话授权 | `/sessions` | 查看/撤销 Session Grant |
| 策略管理 | `/policies` | 查看/编辑策略配置 |
| 预算预留 | `/budget` | 查看预算使用和预留记录 |
| 审计日志 | `/audit` | 浏览完整审计事件 |
| 服务商 | `/providers` | 管理已验证服务商 |
| 恢复操作 | `/recovery` | 紧急暂停/恢复钱包 |
**技术栈**:React 19 + Radix UI + Tailwind CSS 4 + Vite 6
**启动**:
```bash
pnpm dev:approval-ui
# 默认端口 4173,默认工作区 ws_demo
```
**API 端点**(供程序化访问):
| 端点 | 说明 |
|------|------|
| `GET /api/dashboard` | 仪表盘汇总 |
| `GET /api/audit-events` | 审计事件列表 |
| `GET /api/payment-receipts` | 支付收据列表 |
| `GET /api/session-grants` | 会话授权列表 |
| `GET /api/review-tickets` | 审核工单列表 |
| `GET /api/providers` | 服务商列表 |
| `GET /api/budget-reservations` | 预算预留列表 |
| `GET /api/policy` | 当前策略配置 |
| `GET /api/spend` | 消费快照 |
| `GET /api/stats` | 统计数据 |
---
## x402 服务端
独立的 HTTP 付费端点服务,实现 x402 协议的服务端。
### 默认端点
| 路径 | 价格 | 说明 |
|------|------|------|
| `/api/premium` | 0.001 USDC | Premium 内容访问 |
| `/api/agent-tool` | 0.0005 USDC | AI Agent 工具调用 |
### 启动
```bash
# 必须设置收款地址
export PAY_TO_ADDRESS=0xYourEvmWalletAddress
pnpm dev:x402
# 默认端口 3100
```
### 工具端点
| 路径 | 说明 |
|------|------|
| `GET /health` | 健康检查 |
| `GET /x402/supported` | 检查 Facilitator 可用性 |
| `GET /x402/endpoints` | 列出所有付费端点 |
### 配置 x402 端点
通过 MCP 工具动态配置:
```json
{
"payToAddress": "0xYourEvmWalletAddress",
"endpoints": [
{
"path": "/api/premium",
"price": "0.001",
"description": "Premium content access"
},
{
"path": "/api/agent-tool",
"price": "0.0005",
"description": "AI agent tool call"
}
]
}
```
### 网络常量
| 常量 | 值 |
|------|---|
| Monad Network | `eip155:10143` |
| USDC (Testnet) | `0x534b2f3A21130d7a60830c2Df862319e593943A3` |
| Facilitator | `https://x402-facilitator.molandak.org` |
| RPC | `https://testnet-rpc.monad.xyz` |
---
## 环境变量
| 变量 | 必填 | 说明 | 默认值 |
|------|------|------|--------|
| `PG_HOST` | 是* | PostgreSQL 主机 | — |
| `PG_PORT` | 否 | PostgreSQL 端口 | `5432` |
| `PG_DATABASE` | 是* | 数据库名 | — |
| `PG_USER` | 是* | 数据库用户 | — |
| `PG_PASSWORD` | 是* | 数据库密码 | — |
| `AGENTIC_WALLET_DATA_DIR` | 否 | 数据目录 | `.agentic-wallet` |
| `AGENTIC_WALLET_KEYSTORE_SECRET` | 否 | 加密存储密钥 | — |
| `PAY_TO_ADDRESS` | x402 | x402 收款地址 | — |
| `X402_PORT` | 否 | x402 服务端口 | `3100` |
| `X402_FACILITATOR_URL` | 否 | x402 Facilitator | `https://x402-facilitator.molandak.org` |
| `MONAD_RPC_URL` | 否 | Monad RPC | `https://testnet-rpc.monad.xyz` |
\* MCP Server 生产模式必填
---
## 开发
```bash
# 安装依赖
pnpm install
# 构建
pnpm build
# 类型检查
pnpm typecheck
# 运行测试
pnpm test
# 监听模式测试
pnpm test:watch
# 代码检查
pnpm lint
```
### 包管理
```bash
# 仅构建特定包
pnpm --filter @agentic-wallet/sdk build
# 仅测试特定包
npx vitest run packages/payment-router
```
### 技术栈
- **语言**:TypeScript 5.9 (strict mode)
- **运行时**:Node.js 18+
- **包管理**:pnpm 10 (workspace monorepo)
- **测试**:Vitest 4
- **链交互**:viem 2
- **x402 协议**:@x402/core 2.9 + @x402/evm 2.9
- **MCP 协议**:@modelcontextprotocol/sdk 1.29
- **数据库**:PostgreSQL (pg 8)
- **前端**:React 19 + Radix UI + Tailwind CSS 4 + Vite 6
- **验证**:Zod
---
## 安全模型
### 威胁与控制
| 威胁 | 控制措施 |
|------|----------|
| Prompt 注射导致越权支付 | 默认拒绝 + 白名单 + 预算限制 |
| 恶意 x402/MPP 挑战篡改金额/收款方 | 策略引擎独立校验,不信任外部挑战 |
| 重放/重复执行 | 幂等指纹 + SHA-256 冲突检测 |
| Session 凭证泄露 | AES-256-GCM 加密存储 + scrypt 派生 |
| 跨 Agent 权限泄露 | Agent 级策略隔离 + 独立会话 |
| 本机入侵 | 紧急暂停 + 批量撤销 |
### 关键安全决策
1. **Agent 不触碰根密钥**:Session Key 隔离,加密存储
2. **默认拒绝**:所有请求初始 denied,白名单显式放行
3. **策略版本绑定**:授权绑定策略版本,策略变更后自动失效
4. **委托签名**:MCP Server 委托模式下拒绝内联签名
5. **Fail-closed 服务商解析**:零匹配或多次匹配均拒绝
6. **决策优先级**:`denied > paused > requires_human_intervention > requires_reauthorization > allowed`
7. **预算预留-提交**:防止并发超卖
---
## 文档索引
- [需求基线](docs/requirements-baseline.md)
- [架构设计](docs/architecture.md)
- [架构蓝图](docs/architecture-blueprint.md)
- [执行分解](docs/execution-breakdown.md)
- [威胁模型](docs/threat-model.md)
- [审计模式](docs/audit-schema.md)
- [宿主集成矩阵](docs/host-integration-matrix.md)