AI Agent 结合智能合约的自动化交易系统

一、场景痛点:DeFi 交易的新范式
去中心化金融(DeFi)带来了金融交易的革命,但同时也要求用户具备技术能力来管理私钥、分析链上数据、执行复杂的交易策略。传统的 DeFi 交互方式门槛很高,普通用户难以参与。
AI Agent 的引入为这一问题提供了解决方案。AI Agent 可以代替用户执行复杂的 DeFi 策略:自动监控市场机会、执行交易、管理仓位、处理清算风险……用户只需要设定目标和约束,AI Agent 会自动完成其余工作。
但将 AI Agent 与区块链结合带来了独特的挑战:如何保证 Agent 决策的正确性、如何处理链上不确定性、如何设计安全的授权机制……
二、底层机制与原理深度剖析
2.1 AI Agent 架构设计
flowchart TD
A[用户意图] –> B[意图解析]
B –> C[策略生成]
C –> D{风险评估}
D –>|通过| E[模拟执行]
D –>|拒绝| F[返回原因]
E –> G{模拟结果}
G –>|盈利| H[链上执行]
G –>|亏损| I[策略调整]
H –> J[交易确认]
J –> K[结果验证]
K –> L[记录日志]
subgraph 链上组件
M[Agent 合约]
N[权限管理]
O[事件监控]
end
H –> M
J –> N
K –> O
style M fill:#b8d4ff
style D fill:#FFE4B5
AI Agent 交易系统的核心流程:
2.2 代理授权模式
flowchart LR
A[用户钱包] –>|授权 1| B[Agent 合约]
A –>|授权 2| C[代币合约]
B –>|execute| D[Swap Router]
C –>|transfer| B
D –>|swap| C
subgraph 权限范围
E[只能交易指定代币]
F[单笔限额]
G[时间限制]
end
B –> E
B –> F
B –> G
为了安全地授权 AI Agent,需要采用受限的权限模式:ERC-773 提案等提供了"意图授权"(Intent-based Authorization)机制,允许用户授权 Agent 执行特定类型的操作,而无法执行其他操作。
三、生产级代码实现与最佳实践
3.1 Agent 智能合约核心实现
// ==================== Agent 智能合约 ====================
// contracts/TradingAgent.sol
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
contract TradingAgent is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// 交易配置
struct TradeConfig {
address targetToken; // 目标代币
uint256 maxSlippage; // 最大滑点 (basis points)
uint256 maxTradeAmount; // 单笔最大交易金额
uint256 dailyLimit; // 日交易限额
uint256 expiryTime; // 授权过期时间
}
// 交易记录
struct TradeRecord {
address user;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOut;
uint256 timestamp;
bool success;
}
// 状态变量
mapping(address => TradeConfig) public tradeConfigs;
mapping(address => uint256) public dailyTradingVolume;
mapping(address => uint256) public lastResetDay;
address public treasury; // 手续费接收地址
uint256 public protocolFee = 50; // 50 bps = 0.5%
TradeRecord[] public tradeHistory;
// 事件
event TradeExecuted(
address indexed user,
address indexed tokenIn,
address indexed tokenOut,
uint256 amountIn,
uint256 amountOut
);
event ConfigUpdated(address indexed user, TradeConfig config);
event UnauthorizedAttempt(address indexed user, string reason);
// 路由接口
address public swapRouter;
constructor(address _swapRouter, address _treasury) {
swapRouter = _swapRouter;
treasury = _treasury;
}
/**
* @dev 设置交易配置
*/
function setTradeConfig(TradeConfig memory config) external {
require(config.targetToken != address(0), "Invalid target token");
require(config.maxSlippage <= 1000, "Slippage too high"); // <= 10%
require(config.maxTradeAmount > 0, "Invalid max amount");
tradeConfigs[msg.sender] = TradeConfig({
targetToken: config.targetToken,
maxSlippage: config.maxSlippage,
maxTradeAmount: config.maxTradeAmount,
dailyLimit: config.dailyLimit,
expiryTime: block.timestamp + 30 days
});
emit ConfigUpdated(msg.sender, config);
}
/**
* @dev 执行交易(由 Chainlink Keeper 或 AI 服务调用)
*/
function executeTrade(
address user,
address tokenIn,
uint256 amountIn
) external nonReentrant returns (bool success) {
TradeConfig memory config = tradeConfigs[user];
// 1. 验证配置有效性
require(config.expiryTime > block.timestamp, "Config expired");
require(amountIn <= config.maxTradeAmount, "Amount exceeds limit");
// 2. 验证日限额
_checkDailyLimit(user, amountIn);
// 3. 获取价格(简化,实际应使用 Chainlink)
(uint256 expectedOut, uint256 price) = _getPrice(tokenIn, config.targetToken);
// 4. 计算最小输出
uint256 minOut = expectedOut * (10000 – config.maxSlippage) / 10000;
// 5. 检查滑点
uint256 actualOut = _simulateSwap(tokenIn, config.targetToken, amountIn);
require(actualOut >= minOut, "Slippage exceeded");
// 6. 执行交易
IERC20(tokenIn).safeTransferFrom(msg.sender, address(this), amountIn);
// 7. 调用 DEX 路由器执行 swap
success = _executeSwap(tokenIn, config.targetToken, amountIn, minOut);
// 8. 记录交易
tradeHistory.push(TradeRecord({
user: user,
tokenIn: tokenIn,
tokenOut: config.targetToken,
amountIn: amountIn,
amountOut: actualOut,
timestamp: block.timestamp,
success: success
}));
// 9. 更新日交易量
dailyTradingVolume[user] += amountIn;
emit TradeExecuted(user, tokenIn, config.targetToken, amountIn, actualOut);
}
/**
* @dev 检查日限额
*/
function _checkDailyLimit(address user, uint256 amount) internal {
uint256 today = block.timestamp / 1 days;
if (lastResetDay[user] != today) {
dailyTradingVolume[user] = 0;
lastResetDay[user] = today;
}
TradeConfig memory config = tradeConfigs[user];
require(
dailyTradingVolume[user] + amount <= config.dailyLimit,
"Daily limit exceeded"
);
}
/**
* @dev 获取价格(需要集成 Chainlink 或其他预言机)
*/
function _getPrice(address tokenIn, address tokenOut)
internal
view
returns (uint256 price, uint256 confidence)
{
// 简化实现,实际应调用 Chainlink 价格源
// price = ChainlinkAggregator(tokenIn).latestAnswer() / ChainlinkAggregator(tokenOut).latestAnswer();
return (1e18, 1e16); // 假设价格
}
/**
* @dev 模拟 swap 结果
*/
function _simulateSwap(
address tokenIn,
address tokenOut,
uint256 amountIn
) internal view returns (uint256) {
// 简化实现,实际应使用 0x API 或其他聚合器
return amountIn; // 假设 1:1
}
/**
* @dev 执行 swap
*/
function _executeSwap(
address tokenIn,
address tokenOut,
uint256 amountIn,
uint256 minOut
) internal returns (bool) {
// 简化实现,实际应调用 Uniswap V3 等 DEX
// 使用 tokenIn 兑换 tokenOut
return true;
}
/**
* @dev 紧急暂停(仅所有者)
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev 提取错误资金(仅所有者)
*/
function rescueTokens(address token, uint256 amount) external onlyOwner {
IERC20(token).safeTransfer(owner(), amount);
}
}
3.2 AI 交易策略服务
// ==================== AI 交易策略服务 ====================
import { ethers } from 'ethers';
import { Web3Provider } from '@ethersproject/providers';
interface MarketData {
tokenIn: string;
tokenOut: string;
price: number;
volume24h: number;
priceChange24h: number;
volatility: number;
}
interface TradingSignal {
action: 'buy' | 'sell' | 'hold';
confidence: number;
targetPrice: number;
stopLoss: number;
reasoning: string;
}
interface Portfolio {
address: string;
holdings: Map<string, number>;
totalValue: number;
pnl24h: number;
}
class AITradingStrategy {
private provider: Web3Provider;
private agentContract: ethers.Contract;
private priceFeeds: Map<string, number> = new Map();
/**
* 市场数据分析
*/
async analyzeMarket(tokenA: string, tokenB: string): Promise<MarketData> {
// 获取价格数据(简化实现)
const price = await this.getPrice(tokenA, tokenB);
const volume = await this.get24hVolume(tokenA);
const priceChange = await this.get24hPriceChange(tokenA);
const volatility = await this.calculateVolatility(tokenA);
return {
tokenIn: tokenA,
tokenOut: tokenB,
price,
volume24h: volume,
priceChange24h: priceChange,
volatility
};
}
/**
* 生成交易信号
*/
async generateSignal(
marketData: MarketData,
portfolio: Portfolio,
riskAppetite: 'conservative' | 'moderate' | 'aggressive'
): Promise<TradingSignal> {
// 简化策略:基于价格变化和波动率生成信号
const { priceChange24h, volatility } = marketData;
// 阈值设置(根据风险偏好调整)
const thresholds = {
conservative: { buyThreshold: 2, sellThreshold: -2, minConfidence: 0.8 },
moderate: { buyThreshold: 3, sellThreshold: -3, minConfidence: 0.7 },
aggressive: { buyThreshold: 5, sellThreshold: -5, minConfidence: 0.6 }
};
const t = thresholds[riskAppetite];
let action: 'buy' | 'sell' | 'hold' = 'hold';
let confidence = 0;
let reasoning = '';
// 买入信号
if (priceChange24h > t.buyThreshold && volatility < 0.3) {
action = 'buy';
confidence = Math.min(0.95, 0.5 + (priceChange24h / 10));
reasoning = `价格在过去24小时上涨${priceChange24h.toFixed(2)}%,波动率适中`;
}
// 卖出信号
else if (priceChange24h < t.sellThreshold) {
action = 'sell';
confidence = Math.min(0.95, 0.5 + (Math.abs(priceChange24h) / 10));
reasoning = `价格在过去24小时下跌${priceChange24h.toFixed(2)}%,建议止损`;
}
return {
action,
confidence,
targetPrice: marketData.price * (1 + priceChange24h / 100),
stopLoss: marketData.price * 0.95,
reasoning
};
}
/**
* 风险评估
*/
async assessRisk(
signal: TradingSignal,
marketData: MarketData,
portfolio: Portfolio
): Promise<{
approved: boolean;
reason: string;
adjustments: any;
}> {
// 检查置信度
if (signal.confidence < 0.6) {
return { approved: false, reason: '置信度过低', adjustments: null };
}
// 检查流动性
if (marketData.volume24h < 100000) { // $100k 最小流动性
return { approved: false, reason: '流动性不足', adjustments: null };
}
// 检查波动率
if (marketData.volatility > 0.5) {
return {
approved: true,
reason: '高波动环境,建议降低仓位',
adjustments: { positionSize: 0.5 }
};
}
return { approved: true, reason: '风险评估通过', adjustments: null };
}
/**
* 执行交易
*/
async executeTrade(
user: string,
signal: TradingSignal,
marketData: MarketData,
config: any
): Promise<ethers.TransactionResponse> {
if (signal.action === 'hold') {
throw new Error('No action needed');
}
const amountIn = this.calculatePositionSize(
marketData.price,
signal.confidence,
config.maxPositionSize
);
const tokenIn = signal.action === 'buy' ? marketData.tokenOut : marketData.tokenIn;
const tokenOut = signal.action === 'buy' ? marketData.tokenIn : marketData.tokenOut;
// 调用 Agent 合约执行交易
const tx = await this.agentContract.executeTrade(
user,
tokenIn,
ethers.parseUnits(amountIn.toString(), 18)
);
return tx;
}
/**
* 计算仓位大小
*/
private calculatePositionSize(
price: number,
confidence: number,
maxSize: number
): number {
// Kelly Criterion 简化版
const kellyFraction = confidence / 2;
return Math.min(maxSize * kellyFraction, maxSize);
}
// 辅助方法(简化实现)
private async getPrice(tokenA: string, tokenB: string): Promise<number> {
return 1.0;
}
private async get24hVolume(token: string): Promise<number> {
return 1000000;
}
private async get24hPriceChange(token: string): Promise<number> {
return (Math.random() – 0.5) * 10; // -5% to +5%
}
private async calculateVolatility(token: string): Promise<number> {
return Math.random() * 0.5; // 0% to 50%
}
}
3.3 Chainlink Keeper 集成
// ==================== Chainlink Keeper 自动化 ====================
import { ethers, network } from 'hardhat';
import { BigNumber } from 'ethers';
// Keeper 接口
interface KeeperInterface {
checkUpkeep(
data: string
): Promise<{ upkeepNeeded: boolean; performData: string }>;
performUpkeep(performData: string): Promise<any>;
}
class TradingAutomation {
private agentContract: ethers.Contract;
private keeper: KeeperInterface;
/**
* 检查是否需要执行交易
*/
async checkUpkeep(data: string): Promise<{
upkeepNeeded: boolean;
performData: string;
}> {
const { execute, conditions } = JSON.parse(data);
// 检查条件是否满足
const conditionsMet = await this.evaluateConditions(conditions);
if (conditionsMet) {
return {
upkeepNeeded: true,
performData: JSON.stringify({ execute, conditions })
};
}
return { upkeepNeeded: false, performData: '' };
}
/**
* 执行自动化交易
*/
async performUpkeep(performData: string): Promise<void> {
const { execute, conditions } = JSON.parse(performData);
const strategy = new AITradingStrategy();
// 1. 获取市场数据
const marketData = await strategy.analyzeMarket(
execute.tokenIn,
execute.tokenOut
);
// 2. 获取投资组合
const portfolio = await this.getPortfolio(execute.user);
// 3. 生成信号
const signal = await strategy.generateSignal(
marketData,
portfolio,
execute.riskAppetite
);
if (signal.action === 'hold') {
console.log('No action needed');
return;
}
// 4. 风险评估
const riskAssessment = await strategy.assessRisk(
signal,
marketData,
portfolio
);
if (!riskAssessment.approved) {
console.log(`Trade not approved: ${riskAssessment.reason}`);
return;
}
// 5. 执行交易
try {
const tx = await strategy.executeTrade(
execute.user,
signal,
marketData,
execute.config
);
console.log(`Trade executed: ${tx.hash}`);
} catch (error) {
console.error('Trade execution failed:', error);
}
}
/**
* 评估条件
*/
private async evaluateConditions(conditions: any): Promise<boolean> {
if (conditions.priceChangeThreshold) {
const priceChange = await this.getPriceChange(conditions.token);
if (Math.abs(priceChange) < conditions.priceChangeThreshold) {
return false;
}
}
if (conditions.timeInterval) {
const lastExecution = await this.getLastExecutionTime(conditions.user);
const elapsed = Date.now() – lastExecution;
if (elapsed < conditions.timeInterval * 1000) {
return false;
}
}
return true;
}
private async getPortfolio(user: string): Promise<any> {
return {};
}
private async getPriceChange(token: string): Promise<number> {
return (Math.random() – 0.5) * 10;
}
private async getLastExecutionTime(user: string): Promise<number> {
return 0;
}
}
四、边界分析与 Trade-offs
4.1 AI 交易的风险
| 模型风险 | AI 预测可能失误 | 多策略组合、止损 |
| 执行风险 | 链上执行可能失败 | 重试机制、容错 |
| 预言机风险 | 价格数据可能被操纵 | 多源聚合、异常检测 |
| 智能合约风险 | 合约漏洞 | 审计、限制权限 |
4.2 安全设计要点
| 权限限制 | 只能交易指定代币、单笔限额 |
| 时间限制 | 自动过期、需定期续期 |
| 撤销机制 | 用户可随时撤销授权 |
| 紧急停止 | 合约暂停、风险熔断 |
五、总结
AI Agent + 智能合约的自动化交易代表了 DeFi 的未来方向:
关键成功因素:
AI + DeFi 的结合仍在早期阶段,但潜力巨大。
