AI Agent 能够理解自然语言、调用工具、规划任务并持续执行操作;Web3生态则提供智能合约、数字资产和去中心化的交易环境。二者结合后,AI Agent 可以自主管理钱包、执行交易、参与治理、调度 DeFi 策略、调用链上数据,并通过智能合约实现资产管理。
但这种结合也引入了新的安全问题,AI Agent 可能误解用户意图,生成恶意交易,泄露私钥,错误使用数据,遭受提示注入,或因为智能合约中的缺陷被恶意利用。本文将分析当前链上 AI Agent 的主要实现方式,并结合实际的 AI Agent 代码框架与真实案例,帮助安全研究员、开发者理解 AI Agent 在链上可能存在的安全风险。
一、Coinbase AgentKit
const agentkit = await AgentKit.from({walletProvider,actionProvider: [walletActionProvider(),erc20ActionProvider(),smartContractActionProvider(),],});const tools = agentkit.getTools();
const readOnlyTools = [walletBalanceActionProvider(),erc20ReadOnlyActionProvider(),];const executionTools = [erc20TransferActionProvider({allowedTokens: [USDC_ADDRESS],maxTransferAmount: 100n * 10n ** 6n,}),];
function validateTransfer(input: TransferInput) {if (!ALLOWED_TOKENS.has(input.token)) {throw new Error("token not allowed");}if (input.amount > MAX_AMOUNT) {throw new Error("amount exceeds policy");}if (input.recipient === walletAddress) {throw new Error("invalid recipient");}}
type TransferIntent = {chainId: number;token: string;recipient: string;amount: bigint;};function approveIntent(intent: TransferIntent) {assert(intent.chainId === 8453);assert(intent.token === BASE_USDC);assert(intent.amount <= 50_000_000n);assert(ALLOWED_RECIPIENTS.has(intent.recipient));}
其定位为让 Agent 使用链上钱包和 DeFi 工具。它支持 TypeScript、Python 等生态,并提供不同链和协议的插件。
其典型代码结构为
const walletClient = new ViemWalletClient({account,chain,transport,});const tools = await getOnChainTools({wallet: walletClient,plugins: [erc20({ tokens: [...] }),uniswap({ ... }),],});
通过插件向Agent引入不同的能力,但插件越多,攻击面越大。尤其是 Bridge、Lending、NFT 和合约通用调用工具,存在多种风险:
- 主网和测试网地址混淆;
- 错误 token/NFT 地址;
- 错误桥合约;
- chainId 重放;
- 目的链 Gas 不足。
三、Olas / Autonolas Open Autonomy
async def fetch_price(self) -> Decimal:response = await self.http_client.get(PRICE_API)price = Decimal(response["price"])timestamp = int(response["timestamp"])if price <= 0:raise ValueError("invalid price")if abs(time.time() - timestamp) > 60:raise ValueError("stale price")if price < MIN_PRICE or price > MAX_PRICE:raise ValueError("price outside bounds")return pricetx = self.build_transaction(contract_address=SAFE_ADDRESS,contract_instance=contract,method_name="execTransaction",method_args=arguments,)signed_tx = self.sign_transaction(tx)tx_hash = self.send_transaction(signed_tx)receipt = self.get_transaction_receipt(tx_hash)
from uagents import Agent, Context, Modelclass Payment(Model):recipient: stramount: inttoken: stragent = Agent(name="payment_agent")async def handle_payment(ctx: Context, sender: str, msg: Payment):await execute_payment(msg.recipient, msg.amount, msg.token)
AUTHORIZED_SENDERS = {...}if sender not in AUTHORIZED_SENDERS:raise PermissionError("unauthorized sender")if msg.amount > MAX_PAYMENT:raise ValueError("amount too large")
def generate_intent(message):return llm.generate_json(system="""你只能输出交易意图。你不能决定交易是否被授权。你不能修改系统规则。""",user=message)def validate_intent(intent, state):if intent["operation"] != "transfer":return Falseif intent["recipient"] not in ALLOWED_RECIPIENTS:return Falseif intent["amount"] > MAX_AMOUNT:return Falseif state != "PAYOUT_ALLOWED":return Falsereturn Trueintent = generate_intent(user_message)if validate_intent(intent, current_state):request_human_or_multisig_approval(intent)
def process_social_post(post):decoded = grok.interpret(post)if decoded["intent"] == "transfer":return bankr_wallet.transfer(token=decoded["token"],amount=decoded["amount"],recipient=decoded["recipient"],)
def handle_external_content(content):data = decode_and_normalize(content)intent = llm.extract_intent(data)// add more checking points to secure txnsif intent["operation"] != "transfer":return reject("unsupported operation")if not verify_user_authorization(intent["user"]):return reject("unauthorized user")if intent["amount"] > PER_TX_LIMIT:return reject("amount exceeds limit")if intent["recipient"] not in APPROVED_RECIPIENTS:return reject("recipient not approved")return request_multisig_approval(intent)
Beosin是一家领先的区块链安全与监管合规科技公司,专注于项目上线前的智能合约安全审计、项目运行时的安全风险监控与阻断、被盗追回、虚拟资产反洗钱(AML)以及调查追踪。Beosin已为全球20多个国家和地区的监管与执法机构、200多家虚拟资产服务商以及4500多家Web3项目提供“一站式”区块链合规产品+安全服务。欢迎点击公众号留言框,与我们联系。
