Web3开源项目Moss 入门完全指南
# 从零开始:Moss 入门完全指南
> 一份来自实战的教程,带你快速上手 AI Agent × Web3 的开源框架
---
## 🎯 你将学到什么
- ✅ Moss 是什么,为什么值得学
- ✅ 5 分钟搭建开发环境
- ✅ 跑通第一个 Demo,看到真实链上数据
- ✅ 理解核心概念(Registry、Capability、Simulator)
- ✅ 学会用 Moss 构建自己的 AI Agent
- ✅ 如何参与开源贡献(附完整流程)
---
## 第一章:Moss 是什么?
### 1.1 一句话介绍
**Moss 是一个为 Monad 链设计的 AI Agent 能力层**,它把复杂的区块链操作变成 AI 可以理解、调用、验证的标准化能力。
### 1.2 为什么需要它?
想象一下,你想让 AI 帮你做一件事:**"把 1 MON 换成 USDC"**。
#### ❌ 传统方式的问题
```
AI → 生成交易 → 调用钱包 → 签名 → 发送
```
- AI 生成的交易可能是错的
- 一旦签名就没法撤回
- 不同协议有不同调用方式,AI 很难统一处理
#### ✅ Moss 的解法
```
AI → Moss → 构建交易 → 模拟验证 → 展示结果 → 人类确认 → 签名发送
```
- Moss 确保交易构建正确
- 模拟验证提前发现问题
- 人类始终掌控签名权
### 1.3 核心承诺
> **Moss 只构建和验证未签名交易,永不签名、永不发送。**
这意味着你可以放心让 AI 帮你准备交易,因为钱永远不会在你没同意的时候转出去。
### 1.4 适用场景
| 场景 | 说明 |
|------|------|
| AI 交易助手 | "帮我看看现在能不能把 MON 换成 USDC" |
| 资产管理 | 维持特定的资产配置比例 |
| 自动化任务 | 每日定投、收益复投 |
| AI Agent 开发 | 给你的 Agent 添加 Web3 能力 |
---
## 第二章:环境搭建(5 分钟)
### 2.1 前置要求
| 工具 | 版本要求 | 检查命令 |
|------|----------|----------|
| Node.js | >= 22.0.0 | `node --version` |
| pnpm | >= 11.0.0 | `pnpm --version` |
| Git | 任意版本 | `git --version` |
#### 安装 Node.js
```bash
# Windows
winget install OpenJS.NodeJS.LTS
# macOS
brew install node@22
# Linux
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt-get install -y nodejs
```
#### 安装 pnpm
```bash
# 用 corepack(Node 自带)
corepack enable
corepack prepare pnpm@latest --activate
# 或用 npm
npm install -g pnpm@latest
```
### 2.2 克隆项目
```bash
git clone https://github.com/nishuzumi/moss.git
cd moss
```
### 2.3 安装依赖
```bash
# 安装所有依赖
pnpm install
# 构建项目(重要!必须先构建)
pnpm build
```
### 2.4 验证环境
```bash
# 离线测试(不需要 RPC 连接)
MOSS_SKIP_E2E=1 pnpm test
```
你应该看到类似输出:
```
✓ packages/simulator/test/simulator.test.ts
✓ packages/core/test/registry.test.ts
...
Tests 47 passed (47)
```
### ❗ 常见问题
| 问题 | 解决方案 |
|------|----------|
| `pnpm: command not found` | 运行 `corepack enable` 或重新安装 |
| `Node.js version too low` | 升级到 Node 22 |
| `pnpm install` 卡住 | 检查网络,或设置代理:`pnpm config set proxy http://127.0.0.1:7890` |
| `pnpm build` 失败 | 确认 Node 版本 >= 22,重试 `pnpm install && pnpm build` |
---
## 第三章:跑通第一个 Demo
### 3.1 查看可用的示例
```bash
# 查看项目结构
ls examples/
```
```
examples/
├── simple-flow/ # 入门示例(推荐!)
└── agent-swap/ # Agent 完整流程示例
```
### 3.2 示例一:Wrap MON 成 WMON
```bash
pnpm --filter @themoss/example-simple-flow wrap
```
#### 预期输出(关键部分)
```
[1] Discovering WMON capability...
[2] Loading parameter schema...
[3] Building wrap capability (amount: 1.5 MON)...
[4] Simulating against live chain state...
=== SIMULATION RESULT ===
Status: ✅ SUCCESS
Warnings: 0
--- Effects ---
Type | From | To | Amount
--------------|------------|------------|-----------
Native MON | 0xcccc... | (burn) | 1.5
WMON | (mint) | 0xcccc... | 1.5
=== RECEIPT ===
{
"method": "wrap",
"amount": "1500000000000000000",
"account": "0xcccc..."
}
```
### 3.3 示例二:MON 换 USDC(Kuru DEX)
```bash
pnpm --filter @themoss/example-simple-flow swap
```
#### 带参数运行
```bash
# 自定义金额
pnpm --filter @themoss/example-simple-flow swap --amount 0.5
# 自定义代币
pnpm --filter @themoss/example-simple-flow swap --token-in MON --token-out USDC
# 自定义账户
pnpm --filter @themoss/example-simple-flow swap --account 0xYourAddress
```
### 3.4 示例三:组合流程(MON → USDC → MON)
```bash
pnpm --filter @themoss/example-simple-flow combined
```
这个示例展示了如何把两个交易组合成一个完整流程。
### ❗ 可能遇到的问题
| 问题 | 原因 | 解决 |
|------|------|------|
| 网络超时 | RPC 连接失败 | 设置环境变量:`MOSS_RPC_URL=https://monad-mainnet.g.alchemy.com/v2/你的key` |
| 模拟警告 | 滑点太低或价格变动 | 增加滑点或等待市场稳定 |
| `Amount too small` | 金额小于最小单位 | 增加 amount 参数 |
---
## 第四章:核心概念详解
现在你已经跑通了 Demo,让我们深入理解 Moss 的工作原理。
### 4.1 整体架构
```
┌─────────────────────────────────────────────────┐
│ AI Agent │
│ (Claude, GPT-4, 或你自己的 Agent) │
└─────────────────────┬───────────────────────────┘
│ 调用 MCP 工具
▼
┌─────────────────────────────────────────────────┐
│ Moss MCP Server │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ discover│ │ load │ │ action │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────┬───────────────────────────┘
│
▼
┌─────────────────────────────────────────────────┐
│ Moss Core │
│ ┌─────────────────────────────────────────┐ │
│ │ Registry │ │
│ │ (管理所有协议和能力) │ │
│ └─────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────┐ │
│ │ Simulator │ │
│ │ (在链上模拟交易) │ │
│ └─────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────┘
│ 读取链上数据
▼
┌─────────────────────────────────────────────────┐
│ Monad Blockchain │
└─────────────────────────────────────────────────┘
```
### 4.2 四大核心组件
#### Registry(注册表)
管理所有已注册的协议和能力。
```typescript
import { Registry } from "@themoss/core";
import * as erc from "@themoss/erc";
import * as kuru from "@themoss/protocol-kuru";
import * as system from "@themoss/system";
// 创建注册表,注册需要的协议
const registry = new Registry(runtime).use(system, erc, kuru);
```
**比喻**:Registry 就像一本电话簿,记录了所有可以调用的能力。
#### Runtime(运行时)
连接区块链的配置。
```typescript
import { monadRuntime } from "@themoss/system";
// 连接到 Monad 主网
const runtime = await monadRuntime({
rpcUrl: process.env.MOSS_RPC_URL, // 可选,默认公共 RPC
});
```
**比喻**:Runtime 就像电话线,让 Moss 能和区块链通信。
#### Capability(能力)
一个具体的、可以执行的操作。
```typescript
// 创建一个 swap 能力
const capability = await registry.action("kuru", "swap", account, {
tokenIn: NATIVE, // MON
tokenOut: USDC_ADDRESS, // USDC
amountIn: "1", // 1 MON
slippage: 50, // 0.5% 滑点
});
// Capability 包含:
// - capability.txs: 待签名的交易数组
// - capability.intent: 操作意图描述
```
**比喻**:Capability 就像一张订单,详细说明要做什么。
#### Simulator(模拟器)
在链上模拟交易,验证结果。
```typescript
import { createTraceSimulator } from "@themoss/simulator";
const simulator = createTraceSimulator(runtime, {
receipt: (capability, changes) => registry.parseReceipt(capability, changes),
});
// 模拟交易
const result = await simulator.simulate(capability);
// result 包含:
// - result.halted: 是否被阻止
// - result.results: 每个交易的结果
// - result.warnings: 警告信息
```
**比喻**:Simulator 就像试衣间,让你在买之前先穿上看看合不合身。
### 4.3 四步流程详解
#### Step 1: Discover(发现)
告诉 Agent 有哪些能力可用。
```typescript
// 列出所有 swap 类型的能力
const swaps = registry.discover({ verb: "swap" });
console.log(swaps);
// → [
// { protocol: "kuru", method: "swap", category: "dex" },
// ...
// ]
// 过滤特定协议
const kuruOnly = registry.discover({ protocol: "kuru" });
```
**为什么需要这一步?**
Agent 不知道有哪些能力可用,需要先"看看菜单"。
#### Step 2: Load(加载)
获取能力的参数说明。
```typescript
const [swapSpec] = registry.load([{ protocol: "kuru", method: "swap" }]);
console.log(swapSpec);
// → {
// intent: "Swap tokens on Kuru DEX",
// params: {
// tokenIn: { type: "address", description: "Input token address" },
// tokenOut: { type: "address", description: "Output token address" },
// amountIn: { type: "string", description: "Input amount" },
// slippage: { type: "number", description: "Max slippage in basis points" },
// }
// }
```
**为什么需要这一步?**
Agent 需要知道每个参数的含义,才能正确填写。
#### Step 3: Action(构建)
根据参数构建具体的能力。
```typescript
const capability = await registry.action("kuru", "swap", account, {
tokenIn: NATIVE,
tokenOut: USDC_ADDRESS,
amountIn: "1",
slippage: 50,
});
if (capability.kind !== "capability") {
throw new Error(`Expected capability, got ${capability.kind}`);
}
```
**为什么需要这一步?**
这是从抽象描述到具体执行的转换。
#### Step 4: Simulate(模拟)
在链上验证交易。
```typescript
const outcome = await simulator.simulate(capability);
if (outcome.halted) {
console.error("❌ 交易被阻止:", outcome.halted.reason);
return;
}
for (const result of outcome.results) {
if (result.warnings.length > 0) {
console.warn("⚠️ 警告:");
for (const warning of result.warnings) {
console.warn(" -", warning);
}
}
}
// 成功:展示模拟结果
console.log("✅ 模拟成功!");
console.log("📊 预期效果:", outcome.results[0].effects);
```
**为什么需要这一步?**
这是最重要的安全机制,确保交易不会出错。
### 4.4 完整代码示例
把上面四步合在一起:
```typescript
import { NATIVE, Registry } from "@themoss/core";
import * as erc from "@themoss/erc";
import * as kuru from "@themoss/protocol-kuru";
import { createTraceSimulator } from "@themoss/simulator";
import * as system from "@themoss/system";
import { monadRuntime, USDC_ADDRESS } from "@themoss/system";
async function main() {
// 1. 初始化
const runtime = await monadRuntime();
const registry = new Registry(runtime).use(system, erc, kuru);
const simulator = createTraceSimulator(runtime, {
receipt: (capability, changes) => registry.parseReceipt(capability, changes),
});
const ACCOUNT = "0xcccccccccccccccccccccccccccccccccccccccccccc";
// 2. Discover - 找到可用的 swap
console.log("🔍 发现能力...");
const swaps = registry.discover({ verb: "swap", protocol: "kuru" });
console.log("找到:", swaps);
// 3. Load - 获取参数说明
console.log("\n📋 加载参数规格...");
const [swapSpec] = registry.load([{ protocol: "kuru", method: "swap" }]);
console.log("参数:", Object.keys(swapSpec.params));
// 4. Action - 构建能力
console.log("\n⚙️ 构建 swap 能力...");
const capability = await registry.action("kuru", "swap", ACCOUNT, {
tokenIn: NATIVE,
tokenOut: USDC_ADDRESS,
amountIn: "1",
slippage: 50,
});
// 5. Simulate - 模拟验证
console.log("\n✅ 模拟交易...");
const outcome = await simulator.simulate(capability);
if (outcome.halted) {
console.error("❌ 被阻止:", outcome.halted.reason);
process.exit(1);
}
const result = outcome.results[0];
if (result.warnings.length > 0) {
console.warn("⚠️ 警告:", result.warnings);
process.exit(1);
}
console.log("\n🎉 成功! 预期效果:");
console.log(JSON.stringify(result.effects, null, 2));
}
main().catch(console.error);
```
---
## 第五章:实战 - 构建自己的 AI Agent
### 5.1 两种使用方式
| 方式 | 适用场景 | 难度 |
|------|----------|------|
| **MCP Server** | 直接给 AI 用(推荐) | ⭐ |
| **SDK Library** | 在 TypeScript 项目中嵌入 | ⭐⭐ |
### 5.2 方式一:配置 MCP Server(最简单)
MCP(Model Context Protocol)是 AI Agent 与外部工具通信的标准协议。
#### 步骤 1:构建 MCP Server
```bash
pnpm build
```
#### 步骤 2:获取 Server 路径
```bash
ls packages/mcp-server/dist/
# → cli.js
```
#### 步骤 3:配置 AI Client(以 Claude Desktop 为例)
编辑 `~/.config/claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"moss": {
"command": "node",
"args": ["D:/moss/moss/packages/mcp-server/dist/cli.js"],
"env": {
"MOSS_RPC_URL": "https://monad-mainnet.g.alchemy.com/v2/你的key"
}
}
}
}
```
#### 步骤 4:重启 Claude Desktop
现在你可以直接对 Claude 说:
> "帮我看看 1 MON 能换多少 USDC"
Claude 会自动调用 Moss 的 `discover` → `load` → `action` → `simulate`。
### 5.3 方式二:SDK 嵌入(更灵活)
#### 步骤 1:创建新项目
```bash
mkdir my-moss-agent
cd my-moss-agent
pnpm init
```
#### 步骤 2:添加依赖
```bash
pnpm add @themoss/core @themoss/erc @themoss/protocol-kuru @themoss/simulator @themoss/system
```
#### 步骤 3:编写 Agent
创建 `agent.ts`:
```typescript
import { NATIVE, Registry } from "@themoss/core";
import * as erc from "@themoss/erc";
import * as kuru from "@themoss/protocol-kuru";
import { createTraceSimulator } from "@themoss/simulator";
import * as system from "@themoss/system";
import { monadRuntime, USDC_ADDRESS } from "@themoss/system";
// Agent 类
class MossAgent {
private registry: Registry;
private simulator: ReturnType<typeof createTraceSimulator>;
constructor(private account: string) {}
async init() {
const runtime = await monadRuntime();
this.registry = new Registry(runtime).use(system, erc, kuru);
this.simulator = createTraceSimulator(runtime, {
receipt: (capability, changes) => this.registry.parseReceipt(capability, changes),
});
}
async swap(tokenIn: string, tokenOut: string, amount: string, slippage = 50) {
const capability = await this.registry.action("kuru", "swap", this.account, {
tokenIn: tokenIn === "MON" ? NATIVE : tokenIn,
tokenOut: tokenOut === "USDC" ? USDC_ADDRESS : tokenOut,
amountIn: amount,
slippage,
});
const outcome = await this.simulator.simulate(capability);
if (outcome.halted) {
throw new Error(`交易被阻止: ${outcome.halted.reason}`);
}
if (outcome.results[0].warnings.length > 0) {
throw new Error(`警告: ${outcome.results[0].warnings}`);
}
return {
success: true,
effects: outcome.results[0].effects,
capability, // 未签名的交易,后续可以签名发送
};
}
async getBalance(token: string) {
const result = await this.registry.action("system", "balanceOf", this.account, {
token: token === "MON" ? NATIVE : token,
owner: this.account,
});
return result.data;
}
}
// 使用 Agent
async function main() {
const agent = new MossAgent("0xYourAccountAddress");
await agent.init();
console.log("💼 余额:", await agent.getBalance("MON"));
const result = await agent.swap("MON", "USDC", "0.5", 50);
console.log("✅ Swap 成功!");
console.log("📊 预期效果:", result.effects);
}
main().catch(console.error);
```
---
## 第六章:参与开源贡献
### 6.1 贡献方向
| 方向 | 难度 | 说明 |
|------|------|------|
| 改进示例和文档 | ⭐ | 最容易上手 |
| 添加新协议支持 | ⭐⭐⭐ | 需要了解合约 ABI |
| 修复 Bug | ⭐⭐ | 需要阅读源码 |
| 核心改进 | ⭐⭐⭐⭐ | 需要深入理解架构 |
### 6.2 完整贡献流程
#### Step 1: Fork 仓库
在 GitHub 上点击 "Fork" 按钮,把仓库复制到你自己的账号。
#### Step 2: 克隆你的 Fork
```bash
git clone https://github.com/你的用户名/moss.git
cd moss
git remote add upstream https://github.com/nishuzumi/moss.git
```
#### Step 3: 创建特性分支
```bash
git checkout main
git pull upstream main # 同步最新代码
git checkout -b feat/your-feature
```
#### Step 4: 实现功能
编写代码,确保:
```bash
# 构建
pnpm build
# 类型检查
pnpm typecheck
# Lint
pnpm lint
# 测试(离线)
MOSS_SKIP_E2E=1 pnpm test
```
#### Step 5: 提交代码
```bash
git add .
git commit -m "feat(scope): description
- 具体改动 1
- 具体改动 2
- 关联的 issue(如果有)"
```
**提交规范**(Conventional Commits):
```
feat: 新功能
fix: Bug 修复
docs: 文档更新
style: 代码格式
refactor: 重构
test: 测试
chore: 构建/工具
```
#### Step 6: 推送并创建 PR
```bash
git push origin feat/your-feature
```
然后在 GitHub 上创建 Pull Request,填写:
- **标题**: `feat(scope): description`
- **描述**: 说明做了什么,为什么,如何测试
- **关联 Issue**: 如果有的话
#### Step 7: 等待审核
维护者可能会提出修改建议,根据反馈更新代码并推送即可。
### 6.3 我的贡献经历
#### 第一次提交:改进示例
**问题**: 原始示例只有基础功能,缺少错误处理和用户友好输出。
**我的改动**:
1. 添加参数解析(支持 `--amount`、`--token-in` 等)
2. 添加错误处理(验证金额、代币地址)
3. 添加进度提示(Step 1/2/3)
4. 添加组合流程示例
**遇到的坑**:
| 坑 | 原因 | 解决 |
|------|------|------|
| 模拟警告 | 从 `plan.expects` 取的金额不准确 | 改用 `simulate` 返回值 |
| 类型错误 | `results[0]` 可能是 undefined | 添加非空断言 `!` |
| 自定义日志 | 维护者建议用原生 console.log | 移除 chalk,用简单标签 |
**关键经验**:
- 先跑通再优化
- 遵循项目已有模式
- 及时响应维护者反馈
### 6.4 新手指南
#### 找一个好的起点
1. 查看 GitHub Issues,找标记为 `good first issue` 的
2. 改进现有示例
3. 补充文档
#### 提交前检查清单
- [ ] 代码能跑通
- [ ] `pnpm build` 成功
- [ ] `pnpm typecheck` 无错误
- [ ] `pnpm lint` 无警告
- [ ] `pnpm test` 通过
- [ ] 代码风格与项目一致
- [ ] 没有添加不必要的依赖
---
## 第七章:常见问题 FAQ
### Q1: 我需要真钱吗?
**不需要。** Moss 只读链上数据,模拟交易不需要资金或私钥。
### Q2: 为什么有模拟警告?
常见原因:
- 滑点太低(尝试增加到 100-200)
- 市场深度不足(尝试小金额)
- 代币流动性问题
### Q3: 如何切换 RPC?
```bash
# Windows
set MOSS_RPC_URL=https://your-rpc-url.com
# macOS/Linux
export MOSS_RPC_URL=https://your-rpc-url.com
# 或在代码中
const runtime = await monadRuntime({ rpcUrl: "..." });
```
### Q4: 支持哪些链?
目前只支持 **Monad 主网**(Chain ID: 143)。未来计划支持更多 EVM 链。
### Q5: 支持哪些协议?
| 协议 | 包名 | 能力 |
|------|------|------|
| WMON | `@themoss/system` | wrap, unwrap |
| ERC-20 | `@themoss/erc` | transfer, approve |
| ERC-721 | `@themoss/erc` | transfer |
| Kuru | `@themoss/protocol-kuru` | swap, quote |
### Q6: 如何添加新协议?
参考 `packages/protocols/_template`,这是一个协议开发模板。
### Q7: MCP Server 和 SDK 选哪个?
- 如果你想让 AI 直接用 → **MCP Server**
- 如果你想自己写 TypeScript → **SDK Library**
---
## 第八章:下一步学习
### 推荐资源
| 资源 | 链接 | 说明 |
|------|------|------|
| 官方文档 | [docs/](https://github.com/nishuzumi/moss/tree/main/docs) | 完整技术文档 |
| Getting Started | [getting-started.md](https://github.com/nishuzumi/moss/blob/main/docs/getting-started.md) | 官方入门教程 |
| ADR 文档 | [docs/adr/](https://github.com/nishuzumi/moss/tree/main/docs/adr) | 架构决策记录 |
| 协议模板 | [packages/protocols/_template](https://github.com/nishuzumi/moss/tree/main/packages/protocols/_template) | 开发新协议的起点 |
### 学习路径
```
Level 1: 跑通 Demo
↓
Level 2: 理解核心概念(Registry, Capability, Simulator)
↓
Level 3: 配置 MCP Server,让 AI 调用
↓
Level 4: 用 SDK 构建自定义 Agent
↓
Level 5: 为现有协议添加新能力
↓
Level 6: 开发新的协议包
↓
Level 7: 深入核心,改进框架
```
### 社区
- **GitHub Discussions**: 提问和讨论
- **Issues**: 报告 Bug 或请求功能
- **PR**: 贡献代码
---
## 结语
恭喜你读完了这份教程!🎉
现在你应该能够:
1. ✅ 理解 Moss 的设计理念
2. ✅ 搭建开发环境
3. ✅ 跑通示例
4. ✅ 用 Moss 构建自己的 AI Agent
5. ✅ 参与开源贡献
Moss 是一个年轻的项目,还有很多可以改进的地方。**你的每一个 Issue、每一个 PR,都在让这个项目变得更好。**
> "开源不是一个人的事情,是一群人的事情。"
---
## 致谢
感谢 Moss 项目维护者的耐心指导,感谢开源社区的包容和鼓励。
---
## 关于作者
一位对 AI × Web3 充满热情的开发者,正在探索如何让 AI 更安全地参与链上活动。
- 🐙 GitHub:(https://github.com/AGF-DOT)
---
**祝你在 Moss 的世界里玩得开心!** 🚀
更多推荐

所有评论(0)