AI Agent 与链上自动化:从手动操作到智能合约触发
AI Agent 与链上自动化:从手动操作到智能合约触发

一、链上操作的效率困境:手动签名与多步交易的交互负担
DeFi 用户的日常操作涉及多个协议的交互:在 Uniswap 兑换代币、在 Aave 存入抵押品、在 Compound 借出资产、在 Yearn 获取收益。每一步都需要手动签名交易、等待确认、再执行下一步。一个复杂的 DeFi 策略可能需要 5-10 笔交易,用户需要全程在线监控和操作。
AI Agent 与链上自动化的核心思路是:用户定义策略目标(如"当 ETH 价格低于 2000 时买入"),AI Agent 解析目标并生成执行计划,通过智能合约自动触发交易。用户只需授权一次,后续操作由 Agent 自动完成。
二、AI Agent 链上自动化的架构设计
AI Agent 链上自动化分为三层:意图解析层(将自然语言目标转化为结构化执行计划)、策略执行层(监控链上状态并触发条件判断)、交易执行层(通过代理合约执行链上操作)。
flowchart TB
A[用户意图: 自然语言描述] --> B[AI 意图解析]
B --> C[结构化执行计划]
C --> D[策略注册到代理合约]
E[链上状态监控] --> F{触发条件满足?}
F -->|否| E
F -->|是| G[Agent 生成交易参数]
G --> H[代理合约执行]
H --> I[多步交易原子执行]
I --> J[执行结果上报]
J --> K[AI 分析结果]
K --> L{策略完成?}
L -->|否| E
L -->|是| M[通知用户]
subgraph 链下
B
E
G
K
end
subgraph 链上
D
H
I
end
三、生产级实现:AI Agent 链上自动化框架
// ai-chain-agent.ts — AI Agent 链上自动化框架
import { ethers } from 'ethers';
import OpenAI from 'openai';
// 用户意图
interface UserIntent {
description: string;
conditions: TriggerCondition[];
actions: ActionStep[];
maxGasPrice: string; // 最大 Gas 价格(Gwei)
deadline: number; // 截止时间戳
}
// 触发条件
interface TriggerCondition {
type: 'price' | 'balance' | 'time' | 'custom';
token?: string;
operator: 'lt' | 'gt' | 'eq';
value: string;
}
// 执行步骤
interface ActionStep {
protocol: string; // 目标协议(uniswap/aave/compound)
action: string; // 操作类型(swap/deposit/borrow)
params: Record<string, string>;
}
// AI 意图解析器:将自然语言转化为结构化执行计划
// 设计意图:用户不需要理解合约接口,
// 只需用自然语言描述目标
class IntentParser {
private openai: OpenAI;
constructor() {
this.openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
}
async parse(userInput: string): Promise<UserIntent> {
const prompt = `解析以下 DeFi 操作意图,输出结构化 JSON:
用户输入:${userInput}
输出格式:
{
"conditions": [{"type": "price", "token": "ETH", "operator": "lt", "value": "2000"}],
"actions": [{"protocol": "uniswap", "action": "swap", "params": {"from": "USDC", "to": "ETH", "amount": "1000"}}],
"maxGasPrice": "50",
"deadline": 0
}
注意:
1. conditions 是触发条件,actions 是触发后执行的操作
2. 价格单位为 USD,数量为最小单位
3. deadline 为 0 表示不设截止时间`;
const response = await this.openai.chat.completions.create({
model: 'gpt-4o',
messages: [{ role: 'user', content: prompt }],
temperature: 0,
response_format: { type: 'json_object' },
});
const parsed = JSON.parse(response.choices[0].message.content || '{}');
return {
description: userInput,
conditions: parsed.conditions || [],
actions: parsed.actions || [],
maxGasPrice: parsed.maxGasPrice || '50',
deadline: parsed.deadline || 0,
};
}
}
// 链上状态监控器
// 设计意图:持续监控链上状态,当触发条件满足时
// 通知策略执行器
class ChainMonitor {
private provider: ethers.JsonRpcProvider;
constructor(rpcUrl: string) {
this.provider = new ethers.JsonRpcProvider(rpcUrl);
}
// 检查价格条件
async checkPriceCondition(condition: TriggerCondition): Promise<boolean> {
if (condition.type !== 'price') return false;
// 从 Chainlink 预言机获取价格
const priceFeed = new ethers.Contract(
this.getChainlinkAddress(condition.token || 'ETH'),
['function latestRoundData() view returns (uint80, int256, uint256, uint256, uint80)'],
this.provider
);
const [, price] = await priceFeed.latestRoundData();
const currentPrice = Number(ethers.formatUnits(price, 8));
switch (condition.operator) {
case 'lt': return currentPrice < Number(condition.value);
case 'gt': return currentPrice > Number(condition.value);
case 'eq': return Math.abs(currentPrice - Number(condition.value)) < 0.01;
default: return false;
}
}
// 检查所有条件是否满足
async checkAllConditions(conditions: TriggerCondition[]): Promise<boolean> {
for (const condition of conditions) {
const met = await this.checkPriceCondition(condition);
if (!met) return false;
}
return conditions.length > 0;
}
private getChainlinkAddress(token: string): string {
const addresses: Record<string, string> = {
'ETH': '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419',
'BTC': '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c',
};
return addresses[token] || addresses['ETH'];
}
}
// 策略执行器:生成交易参数并通过代理合约执行
// 设计意图:将多步操作封装为单笔交易,
// 避免多笔交易间的状态不一致
class StrategyExecutor {
private wallet: ethers.Wallet;
private agentContract: ethers.Contract;
constructor(privateKey: string, agentContractAddress: string, rpcUrl: string) {
const provider = new ethers.JsonRpcProvider(rpcUrl);
this.wallet = new ethers.Wallet(privateKey, provider);
this.agentContract = new ethers.Contract(
agentContractAddress,
['function executeStrategy(tuple(address protocol, bytes callData)[] actions) external'],
this.wallet
);
}
async execute(intent: UserIntent): Promise<string> {
// 将执行步骤转换为合约调用数据
const actions = intent.actions.map((step) => ({
protocol: this.getProtocolAddress(step.protocol),
callData: this.encodeAction(step),
}));
// 检查 Gas 价格
const feeData = await this.wallet.provider!.getFeeData();
const currentGasPrice = Number(ethers.formatUnits(feeData.gasPrice || 0n, 'gwei'));
if (currentGasPrice > Number(intent.maxGasPrice)) {
throw new Error(`Gas 价格过高: ${currentGasPrice} Gwei > ${intent.maxGasPrice} Gwei`);
}
// 执行策略
const tx = await this.agentContract.executeStrategy(actions);
const receipt = await tx.wait();
return receipt.hash;
}
private getProtocolAddress(protocol: string): string {
const addresses: Record<string, string> = {
'uniswap': '0x68b3465833fb72A70ecDF485E0e4C7bD8665Fc45',
'aave': '0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9',
};
return addresses[protocol] || '';
}
private encodeAction(step: ActionStep): string {
// 简化实现:实际应编码为协议特定的 calldata
return ethers.AbiCoder.defaultAbiCoder().encode(
['string', 'string', 'string'],
[step.action, JSON.stringify(step.params), '0']
);
}
}
四、边界分析与架构权衡
AI Agent 链上自动化在工程落地中需要正视以下 Trade-off:
授权风险与便利性的矛盾。代理合约需要用户授权才能代为执行交易,授权范围过大可能导致资金损失。建议采用最小授权原则:每次策略仅授权所需的代币数量和操作类型,策略执行完毕后自动撤销授权。
AI 意图解析的准确性。自然语言描述可能存在歧义(如"低价买入"的"低价"是多少),AI 解析结果可能与用户真实意图不符。必须在执行前展示解析结果,用户确认后才执行。不可跳过确认步骤。
链上状态的时效性。价格条件检查和交易执行之间存在时间差(区块确认时间约 12 秒),价格可能在检查后、执行前发生剧烈变化。建议在代理合约中添加滑点保护,超出滑点范围时自动回滚。
适用边界:AI Agent 链上自动化最适合条件触发型策略(如限价单、再平衡、清算保护)。对于需要主观判断的策略(如投资决策),AI 不应自动执行,应仅提供建议。
五、总结
AI Agent 与链上自动化,将 DeFi 操作从"手动签名"推进到"意图驱动"。核心架构:AI 解析自然语言意图,链上监控器检测触发条件,代理合约原子执行多步操作。落地建议:第一,采用最小授权原则,限制代理合约的操作范围;第二,执行前必须展示解析结果供用户确认;第三,代理合约内置滑点保护和 Gas 价格检查。关键原则:自动化是工具而非替代——AI Agent 执行的是用户明确授权的操作,而非自主决策。
AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。
更多推荐



所有评论(0)