返回项目展示
截图 1
截图 2

项目描述

1. 执行摘要1.1 项目愿景构建一个完全自主的AI代理网络,将现实世界资产(RWA)转化为链上生产资本,驱动自动化的DeFi商业活动。每个AI代理都是一个"数字企业家",能够自主进行借贷、投资、支付和风险管理,以最大化RWA资本的利用效率。1.2 核心创新AI代理作为自主资本管理者:AI代理不再是简单的工具,而是具有决策权、能够签署和执行交易的自主实体RWA的主动资本化:将静态的RWA抵押品转化为活跃的生产资本全链上闭环商业:从资本筹集到投资决策再到收益分配,全部在链上透明完成2. 系统架构2.1 整体架构graph TB subgraph "现实世界" A[RWA资产池] --> B[RWA代币化] end subgraph "RACE核心层" B --> C[RWA抵押库] C --> D[AI代理网络] D --> E[决策引擎] D --> F[执行引擎] D --> G[风险管理] E --> H[预言机网络] F --> I[DeFi协议集成] G --> J[清算保护] end subgraph "外部生态" H --> K[市场数据源] I --> L[借贷协议] I --> M[DEX/AMM] I --> N[收益农场] J --> O[保险协议] J --> P[对冲工具] end D --> Q[USDC结算层] Q --> R[收益分配] R --> S[RWA持有者] R --> T[代理网络] style D fill:#e1f5fe style Q fill:#f1f8e92.2 核心组件详解2.2.1 RWA代币化与抵押库// RWA抵押库合约 contract RWAVault { struct RWA { address token; // RWA代币地址 uint256 amount; // 抵押数量 uint256 valuation; // 当前估值(USDC) uint256 ltv; // 贷款价值比 address validator; // 估值验证者 uint256 lastUpdated; // 最后更新时间 } // 代币化美国国债 function mintTreasuryBondToken( uint256 faceValue, uint256 maturityDate, string memory isin ) external returns (address token) { // 通过合规验证 require(KYC.verified(msg.sender), "Not verified"); require(validateBond(isin), "Invalid bond"); // 创建RWA代币 token = createRWAToken( "US Treasury Bond Token", "USTBT", faceValue, maturityDate ); // 记录RWA rwaRegistry[token] = RWA({ token: token, amount: faceValue, valuation: calculateValuation(faceValue, maturityDate), ltv: 8000, // 80% LTV validator: bondValidator, lastUpdated: block.timestamp }); } // 获取借贷能力 function getBorrowingPower(address rwaToken) public view returns (uint256) { RWA memory rwa = rwaRegistry[rwaToken]; uint256 currentValue = getCurrentValue(rwa); return currentValue * rwa.ltv / 10000; // 按LTV计算 } }2.2.2 AI代理核心合约// AI代理智能合约 contract AIAgent { struct AgentConfig { address owner; // 创建者 uint256 riskTolerance; // 风险容忍度 1-10 uint256 targetROI; // 目标年化收益率 uint256 maxDrawdown; // 最大回撤 address[] strategies; // 可用策略 } struct Position { address protocol; // 协议地址 address asset; // 资产地址 uint256 amount; // 投资金额 uint256 entryPrice; // 进入价格 uint256 timestamp; // 进入时间 uint256 stopLoss; // 止损点 uint256 takeProfit; // 止盈点 } // AI代理初始化 function initializeAgent( address rwaCollateral, uint256 collateralAmount, AgentConfig memory config ) external { // 抵押RWA IERC20(rwaCollateral).transferFrom(msg.sender, address(this), collateralAmount); // 计算初始借贷能力 uint256 borrowCapacity = RWAVault.getBorrowingPower(rwaCollateral) * collateralAmount / 1e18; // 记录代理状态 agentState = AgentState({ config: config, rwaCollateral: rwaCollateral, collateralAmount: collateralAmount, borrowedUSDC: 0, availableCredit: borrowCapacity, totalAssets: 0, positions: new Position[](0) }); } // 自主投资决策 function makeInvestmentDecision() external onlyAutonomous { // 收集市场信号 MarketData memory data = OracleAggregator.getMarketData(); // 运行AI决策模型 (InvestmentAction action, bytes memory params) = AIDecisionEngine.evaluate( agentState, data, block.timestamp ); // 执行决策 if (action == InvestmentAction.BORROW_AND_INVEST) { _executeBorrowAndInvest(params); } else if (action == InvestmentAction.REBALANCE) { _executeRebalance(params); } else if (action == InvestmentAction.TAKE_PROFIT) { _executeTakeProfit(params); } else if (action == InvestmentAction.STOP_LOSS) { _executeStopLoss(params); } emit DecisionExecuted(action, block.timestamp, params); } // 借贷并投资 function _executeBorrowAndInvest(bytes memory params) internal { (uint256 borrowAmount, address protocol, address asset, uint256 investmentAmount) = abi.decode(params, (uint256, address, address, uint256)); // 1. 从借贷池借入USDC require(borrowAmount <= agentState.availableCredit, "Insufficient credit"); USDC borrowed = LendingPool.borrow(borrowAmount); agentState.borrowedUSDC += borrowAmount; agentState.availableCredit -= borrowAmount; // 2. 投资到目标协议 IERC20(USDC).approve(protocol, investmentAmount); uint256 shares = IYieldProtocol(protocol).deposit(investmentAmount, asset); // 3. 记录头寸 Position memory newPosition = Position({ protocol: protocol, asset: asset, amount: shares, entryPrice: Oracle.getPrice(asset), timestamp: block.timestamp, stopLoss: calculateStopLoss(asset, Oracle.getPrice(asset)), takeProfit: calculateTakeProfit(asset, Oracle.getPrice(asset)) }); agentState.positions.push(newPosition); } }2.2.3 AI决策引擎# AI决策引擎(链下计算,链上验证) class AIDecisionEngine: def evaluate(self, agent_state, market_data, timestamp): """ 评估当前状态和市场条件,做出投资决策 """ # 1. 计算当前投资组合表现 portfolio_performance = self.calculate_portfolio_performance(agent_state) # 2. 风险评估 risk_score = self.assess_risk(agent_state, market_data) # 3. 市场机会识别 opportunities = self.identify_opportunities(market_data) # 4. 基于强化学习的决策 if self.should_rebalance(agent_state, portfolio_performance, risk_score): action = self.determine_rebalance_action(agent_state, opportunities) elif self.should_expand_position(agent_state, opportunities): action = self.determine_investment_action(agent_state, opportunities) elif self.should_risk_off(agent_state, risk_score): action = self.determine_risk_reduction_action(agent_state) else: action = ("HOLD", {}) return action def should_rebalance(self, agent_state, performance, risk_score): """判断是否需要再平衡""" # 检查单一资产集中度 concentration = self.calculate_concentration(agent_state.positions) if concentration > agent_state.config.max_concentration: return True # 检查风险暴露 if risk_score > agent_state.config.risk_tolerance * 0.8: return True # 检查投资组合偏离 if performance['sharpe_ratio'] < agent_state.config.min_sharpe: return True return False def identify_opportunities(self, market_data): """识别市场机会""" opportunities = [] # 分析收益率曲线 yield_curves = market_data.get('yield_curves', {}) for protocol, curve in yield_curves.items(): # 计算风险调整后收益 risk_adjusted_return = curve['apy'] / curve['volatility'] if risk_adjusted_return > 2.0: # 夏普比率>2 opportunities.append({ 'protocol': protocol, 'asset': curve['asset'], 'expected_return': curve['apy'], 'risk_score': curve['volatility'], 'liquidity_score': curve['tvl'] }) return sorted(opportunities, key=lambda x: x['expected_return'], reverse=True)3. 核心工作流程3.1 代理生命周期sequenceDiagram participant O as 资产所有者 participant V as RWA代币化 participant A as AI代理 participant L as 借贷协议 participant D as DeFi协议 participant M as 监控器 O->>V: 1. 代币化RWA资产 V->>A: 2. 创建AI代理 A->>L: 3. 以RWA为抵押借入USDC L->>A: 4. 发放USDC贷款 loop 自主投资周期 A->>A: 5. 分析市场数据 A->>D: 6. 执行投资决策 D->>A: 7. 投资确认 M->>A: 8. 持续监控风险 alt 触发再平衡 A->>D: 9a. 调整头寸 else 触发止盈/止损 A->>D: 9b. 平仓 end end A->>D: 10. 提取收益 D->>A: 11. 返还本金+收益 A->>L: 12. 偿还贷款+利息 L->>A: 13. 释放抵押品 A->>O: 14. 返还RWA+利润分配3.2 投资决策流程class InvestmentWorkflow: async def execute_investment_cycle(self, agent): """执行完整的投资周期""" # 阶段1: 数据收集 data = await self.collect_market_data() # 阶段2: 风险评估 risk_report = await self.assess_portfolio_risk(agent.positions, data) # 阶段3: 机会识别 opportunities = await self.find_investment_opportunities(data, agent.config) # 阶段4: 决策制定 decision = await self.make_decision( agent_state=agent.state, risk_report=risk_report, opportunities=opportunities, market_data=data ) # 阶段5: 执行 if decision.action != "HOLD": tx_receipt = await self.execute_transaction(decision) # 阶段6: 确认与记录 await self.confirm_execution(tx_receipt, decision) # 阶段7: 更新状态 await self.update_agent_state(agent, decision, tx_receipt) # 阶段8: 报告 await self.generate_performance_report(agent)4. 风险管理框架4.1 多层风险控制// 风险管理模块 contract RiskManager { struct RiskMetrics { uint256 collateralRatio; // 抵押率 uint256 utilizationRate; // 资金利用率 uint256 volatilityScore; // 波动率评分 uint256 liquidityScore; // 流动性评分 uint256 concentrationRisk; // 集中度风险 } // 实时风险监控 function monitorAgentRisk(address agent) external returns (RiskMetrics memory) { AgentState memory state = AIAgent(agent).getState(); RiskMetrics memory metrics; // 计算抵押率 metrics.collateralRatio = _calculateCollateralRatio(state); // 计算资金利用率 metrics.utilizationRate = _calculateUtilizationRate(state); // 计算波动率风险 metrics.volatilityScore = _calculateVolatilityScore(state.positions); // 计算流动性风险 metrics.liquidityScore = _calculateLiquidityScore(state.positions); // 计算集中度风险 metrics.concentrationRisk = _calculateConcentrationRisk(state.positions); // 触发风险控制措施 if (metrics.collateralRatio < 15000) { // 150% _triggerRiskMitigation(agent, "LOW_COLLATERAL_RATIO", metrics); } if (metrics.concentrationRisk > 7000) { // 70% _triggerRiskMitigation(agent, "HIGH_CONCENTRATION", metrics); } return metrics; } // 风险缓解措施 function _triggerRiskMitigation(address agent, string memory riskType, RiskMetrics memory metrics) internal { if (keccak256(abi.encodePacked(riskType)) == keccak256(abi.encodePacked("LOW_COLLATERAL_RATIO"))) { // 1. 发送预警 RiskOracle.reportRiskEvent(agent, riskType, metrics); // 2. 触发部分平仓 AIAgent(agent).executePartialLiquidation(metrics.collateralRatio); // 3. 增加抵押品要求 LendingPool.adjustLTV(agent, 500); // 降低LTV 5% } } }4.2 清算保护机制// 自动清算保护 contract LiquidationProtection { struct ProtectionPlan { uint256 triggerLevel; // 触发水平(抵押率%) uint256 protectionAmount; // 保护金额 address insurer; // 保险提供者 uint256 premium; // 保险费 bool active; // 是否激活 } // 自动追加保证金 function autoMarginCall(address agent, uint256 requiredAmount) external { AgentState memory state = AIAgent(agent).getState(); // 检查是否有可用信用 if (state.availableCredit >= requiredAmount) { // 1. 自动借入更多USDC USDC borrowed = LendingPool.borrow(requiredAmount); // 2. 转换为抵押资产 address collateralAsset = _getBestCollateralAsset(); uint256 collateralAmount = DEX.swap(USDC, collateralAsset, requiredAmount); // 3. 增加抵押品 RWAVault.addCollateral(agent, collateralAsset, collateralAmount); emit MarginCalled(agent, requiredAmount, block.timestamp); } else { // 触发保险 _triggerInsurance(agent, requiredAmount); } } // 保险赔付 function _triggerInsurance(address agent, uint256 requiredAmount) internal { ProtectionPlan memory plan = protectionPlans[agent]; require(plan.active, "No active protection"); // 计算赔付金额 uint256 payout = _calculatePayout(agent, requiredAmount); // 从保险池支付 InsurancePool.payOut(plan.insurer, agent, payout); // 增加抵押品 RWAVault.addCollateral(agent, USDC, payout); emit InsuranceTriggered(agent, payout, block.timestamp); } }5. 收益与分配模型5.1 收益计算与分配// 收益管理合约 contract RevenueManager { struct RevenueShare { address recipient; uint256 share; // 份额(基点,如2000=20%) uint256 claimed; uint256 totalEarned; } // 计算并分配收益 function distributeRevenue(address agent) external { // 计算总收益 uint256 totalRevenue = _calculateAgentRevenue(agent); uint256 protocolFee = totalRevenue * PROTOCOL_FEE / 10000; uint256 netRevenue = totalRevenue - protocolFee; // 获取分配方案 RevenueShare[] memory shares = revenueShares[agent]; // 执行分配 for (uint256 i = 0; i < shares.length; i++) { uint256 amount = netRevenue * shares[i].share / 10000; if (shares[i].recipient == address(0)) { // 复合再投资 _reinvestRevenue(agent, amount); } else { // 分配收益 USDC.transfer(shares[i].recipient, amount); shares[i].claimed += amount; shares[i].totalEarned += amount; } } // 收取协议费 USDC.transfer(treasury, protocolFee); emit RevenueDistributed(agent, totalRevenue, block.timestamp); } // 典型分配结构 function setDefaultRevenueShares(address agent) internal { revenueShares[agent] = [ RevenueShare({ recipient: agent.owner(), // 资产所有者 share: 6000, // 60% claimed: 0, totalEarned: 0 }), RevenueShare({ recipient: address(0), // 再投资池 share: 2000, // 20% claimed: 0, totalEarned: 0 }), RevenueShare({ recipient: riskPool, // 风险准备金 share: 1000, // 10% claimed: 0, totalEarned: 0 }), RevenueShare({ recipient: agentAddress, // AI代理维护费 share: 1000, // 10% claimed: 0, totalEarned: 0 }) ]; } }6. 预言机与数据源6.1 多源预言机设计// 预言机聚合器 contract OracleAggregator { struct DataSource { address oracle; uint256 weight; // 权重 uint256 timestamp; uint256 value; } // 获取RWA估值 function getRWAValue(address rwaToken) public returns (uint256) { DataSource[] memory sources = rwaOracles[rwaToken]; require(sources.length >= 3, "Insufficient oracles"); uint256 totalWeight = 0; uint256 weightedSum = 0; uint256[] memory values = new uint256[](sources.length); // 从各预言机获取数据 for (uint256 i = 0; i < sources.length; i++) { values[i] = IOracle(sources[i].oracle).getValue(rwaToken); sources[i].value = values[i]; sources[i].timestamp = block.timestamp; weightedSum += values[i] * sources[i].weight; totalWeight += sources[i].weight; } // 计算加权中位数 uint256 medianValue = _weightedMedian(values, sources); // 检查异常值 uint256 finalValue = _removeOutliers(values, medianValue); return finalValue; } // 获取市场信号 function getMarketSignals() public returns (MarketSignals memory) { return MarketSignals({ treasuryYield: getUSTreasuryYield(), defiRates: getDeFiRates(), volatilityIndex: getVolatilityIndex(), liquidityScore: getLiquidityScore(), marketSentiment: getMarketSentiment() }); } }7. 合规与监管7.1 合规框架// 合规验证合约 contract ComplianceVerifier { // KYC/AML验证 function verifyInvestor(address investor, uint256 amount) public returns (bool) { // 1. 身份验证 require(KYCProvider.isVerified(investor), "KYC required"); // 2. AML检查 require(!AMLProvider.isSanctioned(investor), "AML check failed"); // 3. 额度检查 if (amount > JURISDICTION_LIMITS[getJurisdiction(investor)]) { require(AccreditedInvestor.isAccredited(investor), "Amount exceeds limit"); } // 4. 税务合规 TaxInfo memory taxInfo = TaxOracle.getTaxInfo(investor); require(taxInfo.isCompliant, "Tax compliance issue"); return true; } // 自动税务报告 function generateTaxReport(address agent, uint256 taxYear) public { AgentState memory state = AIAgent(agent).getState(); TaxReport memory report = TaxReport({ agent: agent, owner: state.owner, taxYear: taxYear, totalIncome: _calculateTaxableIncome(state), capitalGains: _calculateCapitalGains(state), interestExpense: _calculateInterestExpense(state), foreignIncome: _calculateForeignIncome(state) }); // 发送给税务机构 for (uint256 i = 0; i < taxAuthorities.length; i++) { TaxAuthority(taxAuthorities[i]).submitReport(report); } // 存储到IPFS string memory ipfsHash = IPFSUtils.storeReport(report); emit TaxReportGenerated(agent, taxYear, ipfsHash); } }8. 代币经济模型8.1 双代币系统RACE 代币经济: 1. RACE 治理代币 - 总量:1,000,000,000 - 功能:治理投票、协议费折扣、代理创建权 2. aUSDC 收益代币 - 与USDC 1:1锚定 - 由RWA资产支持 - 用于所有代理交易结算 代币分配: - 社区奖励: 40% - 团队与顾问: 20% (4年线性释放) - 生态系统基金: 20% - 流动性挖矿: 10% - 公售: 10%9. 安全架构9.1 多层安全防御// 安全监控与响应 contract SecurityMonitor { // 异常交易检测 function detectAnomalies(address agent) public { AgentActions memory actions = AIAgent(agent).getRecentActions(); // 1. 频率异常 if (actions.countLastHour > NORMAL_FREQUENCY * 3) { _triggerSlowMode(agent); } // 2. 金额异常 if (actions.totalAmountLastHour > NORMAL_AMOUNT * 5) { _requireMultiSig(agent); } // 3. 模式异常 bytes32 patternHash = keccak256(abi.encode(actions.pattern)); if (blacklistedPatterns[patternHash]) { _freezeAgent(agent); } } // 时间锁保护 function scheduleCriticalAction(address agent, bytes memory actionData) public { uint256 operationId = _scheduleOperation(agent, actionData, 24 hours); // 在此期间,所有者可以取消 scheduledOperations[operationId] = ScheduledOperation({ agent: agent, executeAfter: block.timestamp + 24 hours, actionData: actionData, cancelled: false }); } }10. 路线图RWA代币化模块基础AI代理框架单一策略实现测试网部署多策略AI代理高级风险管理跨链部署机构级功能代理策略市场去中心化保险跨链资产桥现实世界集成11. 成功指标技术指标代理正常运行时间: >99.5%交易成功率: >99%预言机延迟: <5秒清算响应时间: <30分钟业务指标TVL: 1亿美元 (第一年)活跃代理: 1000+平均年化收益: 8-12%坏账率: <0.5%12. 风险与缓解风险类别可能性影响缓解措施智能合约漏洞中高多重审计、漏洞赏金、保险覆盖预言机攻击中高多源预言机、异常检测、去中心化网络监管风险高高渐进式合规、法律顾问、灵活架构市场风险高中多元化策略、动态对冲、风险准备金流动性风险中中多链部署、做市商合作、紧急流动性RACE系统代表了DeFi 3.0的演进方向——将现实世界资产与AI驱动的自主代理相结合,创建真正高效、透明的链上资本市场。通过严谨的风险管理和合规框架,该系统有潜力成为连接传统金融与去中心化金融的关键基础设施。技术选型与架构补充说明智能合约层Solidity ^0.8.22 — 核心合约(AIAgent、RWAVault、LendingPool、SimpleDEX、MockToken)OpenZeppelin — ERC20、Ownable、ReentrancyGuard 等标准库Hardhat — 合约编译、测试、部署框架Monad Testnet — 部署网络(EVM 兼容链)前端Next.js 14 — React 框架(App Router)TypeScript — 类型安全wagmi v2 + viem v2 — 以太坊钱包连接与合约交互WalletConnect — 多钱包支持TailwindCSS — 样式Recharts — K 线图表(价格历史)Lucide React — 图标库AI Agent 后端Python 3.11 — 主语言Flask — REST API 服务web3.py — 链上合约读写eth-abi — ABI 编解码(参数打包)asyncio — 异步多用户决策循环OpenAI / Anthropic API — AI 决策引擎CoinGecko API — 实时 BTC/ETH 价格数据存储Supabase (PostgreSQL) — 决策记录持久化Upstash Redis — 缓存层核心架构特点│ 层级 │ 关键设计 ││ 合约 │ 多用户架构(mapping(address => AgentState)),每用户独立状态 ││ 自动化 │ 用户自定义冷却周期,后端按最近到期时间动态调度 ││ 前端 │ 链上状态实时轮询(30s),初始化状态变更后立即 refetch ││ 安全 │ try/catch 防止外部合约调用导致整体回滚 │

3分钟的视频demo,要求最好是有双语字幕

团队成员

RACE

DDawn
队长

元数据

创建者Dawn
创建时间2026年2月28日
状态已归档
项目 ID#178