---
title: "Onchain AI 代理架構：五種建構模式"
description: "五種 onchain AI 代理的建構模式，各附實作範例：wallet watchers、event-driven reactors、portfolio rebalancers、detect-then-execute 多代理拆分，以及安全的 pre-mainnet 測試。"
datePublished: "2026-09-02"
dateModified: "2026-09-02"
---

# Onchain AI 代理架構：五種建構模式

<ImageBlock
  src="https://media.alchemy.com/blog/onchain-ai-agent-architectures-hero.png"
  alt="鏈上 AI 代理架構指南封面插圖"
  width={1920}
  height={900}
  priority
/>

能夠讀寫鏈上狀態的 AI agent 已經從展示走入正式環境。模型能夠推理，agent wallet 能在有限權限下簽署交易，基礎設施能在事件上鏈後幾秒內推送給 agent。架構才是實作中仍然容易出錯的地方。Agent 可能對本該訂閱的事件改用輪詢、在讀取不可信輸入的同一個處理程序中持有簽署權限，或是拿真實資金在主網上「邊做邊學」。

一個鏈上 agent 本質上是一個迴圈：觀察、決策、行動。正式環境中的 agent 通常將這個迴圈組織成五種反覆出現的形態，下面每一種都附有實作範例。我們的[鏈上 agent 建構指南](https://www.alchemy.com/blog/how-to-build-onchain-agents)涵蓋這些形態背後共通的基礎元件（wallet、支付通道、資料來源）；本篇文章談的是如何組織這些元件。

<EmbeddedTable
  table={{
    columns: [
      { key: "pattern", width: 170, title: "Pattern", dataType: "object" },
      { key: "trigger", width: 200, title: "Trigger", dataType: "object" },
      {
        key: "reads",
        width: 180,
        title: "The agent reads",
        dataType: "object",
      },
      { key: "does", width: 180, title: "The agent does", dataType: "object" },
      {
        key: "when",
        width: 230,
        title: "Reach for it when",
        dataType: "object",
      },
    ],
    data: [
      {
        pattern: { title: "Wallet watcher", tooltip: "", icon: "" },
        trigger: {
          title: "A transfer hits a watched address",
          tooltip: "",
          icon: "",
        },
        reads: { title: "Webhook or WebSocket events", tooltip: "", icon: "" },
        does: { title: "Wakes and evaluates", tooltip: "", icon: "" },
        when: {
          title: "You track deposits, whales, or counterparties",
          tooltip: "",
          icon: "",
        },
        id: 0,
      },
      {
        pattern: { title: "Event-driven reactor", tooltip: "", icon: "" },
        trigger: { title: "A contract emits an event", tooltip: "", icon: "" },
        reads: { title: "Filtered logs", tooltip: "", icon: "" },
        does: { title: "Responds with a transaction", tooltip: "", icon: "" },
        when: {
          title: "Protocol state changes drive your strategy",
          tooltip: "",
          icon: "",
        },
        id: 1,
      },
      {
        pattern: { title: "Portfolio rebalancer", tooltip: "", icon: "" },
        trigger: {
          title: "Allocation drifts past a band",
          tooltip: "",
          icon: "",
        },
        reads: { title: "Balances and prices", tooltip: "", icon: "" },
        does: { title: "Proposes a swap", tooltip: "", icon: "" },
        when: {
          title: "You hold target weights and want them enforced",
          tooltip: "",
          icon: "",
        },
        id: 2,
      },
      {
        pattern: { title: "Detect-then-execute split", tooltip: "", icon: "" },
        trigger: {
          title: "The detector emits a signal",
          tooltip: "",
          icon: "",
        },
        reads: {
          title: "Everything, while signing nothing",
          tooltip: "",
          icon: "",
        },
        does: {
          title: "The executor verifies, then signs",
          tooltip: "",
          icon: "",
        },
        when: {
          title: "Untrusted input meets real money",
          tooltip: "",
          icon: "",
        },
        id: 3,
      },
      {
        pattern: { title: "Pre-mainnet testing", tooltip: "", icon: "" },
        trigger: { title: "Every new capability", tooltip: "", icon: "" },
        reads: { title: "Testnets and dry-runs", tooltip: "", icon: "" },
        does: { title: "Promotes the agent in stages", tooltip: "", icon: "" },
        when: {
          title: "Always, before the other four go live",
          tooltip: "",
          icon: "",
        },
        id: 4,
      },
    ],
  }}
/>

## 如何建構即時的 wallet watcher agent？

把你關心的位址註冊到 webhook，讓鏈上事件主動找上你，而不是用迴圈輪詢餘額——那樣既耗費運算資源，又還是會錯過關鍵時刻。推送式管線能在轉帳上鏈後幾秒內送達，而這正是 watcher 該做的全部工作。

假設這個 agent 追蹤某基金的交易對手 wallet，並標記任何大額 USDC 移動。在 Alchemy 上，單一個 [Address Activity webhook](https://www.alchemy.com/webhooks)就能涵蓋 native、ERC-20、ERC-721 與 ERC-1155 轉帳，最多可監看[十萬個位址](https://www.alchemy.com/docs/reference/webhook-types)，所以一個 webhook 就能監看整份交易對手名單。如果 agent 是以長駐程序運行、你也不想公開一個 URL，[WebSocket subscriptions](https://www.alchemy.com/docs/reference/subscription-api)能在程序內完成同樣的工作。用 `alchemy_minedTransactions` 訂閱，你就能取得已確認、且已過濾到你指定位址的交易，不需要自己解析 log。在 Solana 上，[Yellowstone gRPC streaming](https://www.alchemy.com/solana-grpc)以每 TB 75 美元的價格填補同樣的角色，並支援無縫重連。如果不確定該選哪種傳輸方式，我們的[webhooks vs WebSockets vs gRPC 比較](https://www.alchemy.com/overviews/webhooks-vs-websockets-vs-grpc)有詳細的說明。

處理函式本身應該盡量什麼都不做。先驗證這則事件確實來自 Alchemy、去除重複，再把事件交給 agent 的決策步驟，最後才回覆確認：

<CodeSnippet
  language="typescript"
  code={`import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";
const SIGNING_KEY = process.env.ALCHEMY_WEBHOOK_SIGNING_KEY!; // from the webhook's dashboard settings
const USDC = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"; // canonical USDC contract on Ethereum mainnet
const seen = new Set<string>();
function remember(key: string) {
  seen.add(key);
  if (seen.size > 10_000) seen.delete(seen.values().next().value!); // bound the set; only recent deliveries repeat
}
function wake(signal: unknown) {
  // The agent's decide step starts here. Queue the signal;
  // don't run model reasoning inside the request handler.
}
const app = express();
app.use(
  express.json({
    verify: (req, _res, buf) => {
      (req as { rawBody?: Buffer }).rawBody = buf; // keep the raw bytes for the HMAC check
    },
  })
);
app.post("/hooks/address-activity", (req, res) => {
  const sig = Buffer.from(String(req.headers["x-alchemy-signature"] ?? ""), "hex");
  const expected = createHmac("sha256", SIGNING_KEY)
    .update((req as { rawBody?: Buffer }).rawBody ?? Buffer.alloc(0))
    .digest();
  if (sig.length !== expected.length || !timingSafeEqual(sig, expected)) {
    return res.sendStatus(401); // not signed with our key; never process it
  }
  for (const transfer of req.body.event.activity) {
    const key = \`\${transfer.hash}:\${transfer.log?.logIndex ?? "native"}\`; // one tx can carry several transfers
    if (seen.has(key)) continue; // repeat delivery, already handled
    if (transfer.rawContract?.address?.toLowerCase() === USDC && transfer.value > 50_000) {
      wake({ kind: "large-transfer", ...transfer }); // if this throws, the key stays unmarked and the retry redelivers
    }
    remember(key); // mark handled only after the handoff succeeded
  }
  res.sendStatus(200); // ack only after queueing: a crash above gets retried, not lost
});
app.listen(8080);`}
/>

有三個習慣能讓這個模式在正式環境中穩定運作。先驗證 HMAC 簽章再信任這則傳送內容，否則只要有人知道你的 endpoint URL，就能偽造一筆轉帳事件來操控你的 agent。用合約位址而非代幣符號來比對，因為任何人都能部署一個自稱 USDC 的代幣，並傳送到你監看的位址。另外，事件傳送是 at-least-once（至少送達一次），所以去重記錄不是可有可無的選項。in-memory 的集合對單一長駐程序還算堪用；若服務會重啟或有多個副本，就需要把記錄放在共享且持久的地方，例如 Redis key 或資料庫的一筆紀錄，因為對交易 agent 來說，重複喚醒就等於重複下單。這種機械式的過濾應放在處理函式中，讓模型不必介入，因為每筆轉帳都呼叫一次 LLM，成本會遠高於傳送這筆轉帳的基礎設施本身。

## 如何讓 AI agent 監控智能合約事件並自動回應？

訂閱合約的 log，過濾出真正重要的一兩種事件，並讓處理函式具備冪等性（idempotent）。合約事件是 agent 能取得的最乾淨的觸發來源，因為合約會精確陳述發生了什麼事、以及發生的順序。

Alchemy 上有兩種介面可以處理這件事。[Custom webhooks](https://www.alchemy.com/docs/reference/custom-webhooks-quickstart)接受 GraphQL 篩選條件，你可以比對合約位址與事件 topic，只接收你要求的 log。這適合無伺服器（serverless）的 reactor。對於長駐運行的 agent，WebSocket log subscription 能把一切都留在同一個程序內。以下是一個監看 Uniswap v3 池子的 reactor，這類資料流正是交易 agent 用來察覺單筆 swap 是否大幅影響價格的方式：

<CodeSnippet
  language="typescript"
  code={`import { createPublicClient, webSocket, parseAbiItem } from "viem";
import { mainnet } from "viem/chains";
function react(args: unknown) {
  // Decide step: is this swap big enough to act on?
}
const client = createPublicClient({
  chain: mainnet,
  transport: webSocket("wss://eth-mainnet.g.alchemy.com/v2/YOUR_API_KEY"),
});
client.watchEvent({
  address: "0x88e6A0c2dDD26FEEb64F039a2c41296FcB3f5640", // USDC/WETH 0.05% pool
  event: parseAbiItem(
    "event Swap(address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick)"
  ),
  onLogs: (logs) => {
    for (const log of logs) {
      if (log.removed) continue; // reorg removal notice; irreversible actions also need the confirmation-depth rule below
      react(log.args);
    }
  },
});`}
/>

`log.removed` 這項檢查比看起來更重要。鏈會發生重組（reorganize），而 agent 已經據以行動的 log，幾個區塊後可能就從正典鏈（canonical chain）上消失。具備冪等性的處理函式，加上確認深度規則（在執行不可逆行動前等待幾個區塊），是標準的防範做法。Reactor 的另一項紀律和 watcher 相同：訂閱過濾器負責便宜的初步篩選，模型只看得到通過篩選後還存留下來的事件。

## 建構 DeFi 投資組合再平衡（rebalancing）agent 需要哪些東西？

四樣東西：目前的餘額、目前的價格、一條偏移規則，以及一條 swap 路徑。Agent 讀取前兩項，檢查第三項，只有在規則觸發時才動用第四項。

以一個持有 WETH、USDC、WBTC 各佔 50/30/20 比例的 treasury agent 為例。餘額來自 [Portfolio API](https://www.alchemy.com/docs/reference/portfolio-apis)，它能在一次請求中回傳一個 wallet 跨多條鏈的代幣持有狀況，省去逐鏈分別呼叫的麻煩。價值則來自 [Prices API](https://www.alchemy.com/docs/reference/prices-api-quickstart)。偏移規則是單純的算術問題，常見的起點是圍繞每個目標權重設定正負五個百分點的區間。以固定時間排程檢查即可，因為偏移多半來自價格變動而非代幣移動，而價格變動並不會產生任何可供反應的鏈上事件。Watcher（模式一）回報的轉帳事件則是補充性的觸發條件，能在存款或提款發生的當下立即捕捉。

<CodeSnippet
  language="typescript"
  code={`const TARGET = { WETH: 0.5, USDC: 0.3, WBTC: 0.2 } as const;
const BAND = 0.05; // rebalance when a weight drifts 5 points from target
const WALLET = "0xYourTreasuryWallet"; // the wallet the agent manages
const res = await fetch(
  \`https://api.g.alchemy.com/data/v1/\${process.env.ALCHEMY_API_KEY}/assets/tokens/by-address\`,
  {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      addresses: [{ address: WALLET, networks: ["eth-mainnet"] }],
    }),
  }
);
const { data } = await res.json();
// Price each balance with the Prices API, sum to a total, then:
for (const [symbol, target] of Object.entries(TARGET)) {
  const drift = weightOf(symbol, data) - target; // weightOf: your portfolio math
  if (Math.abs(drift) > BAND) {
    propose({ symbol, drift }); // propose: log it and request approval; never swap directly
  }
}`}
/>

執行端不應該直接持有原始私鑰。透過[限定權限的 agent wallet](https://www.alchemy.com/blog/agent-wallets-alchemy-cli)，金鑰留在託管方手中，而 session 只帶有你授予的能力。要花費一筆 ERC-20，需要先給 router 額度（allowance）才能進行 swap。每次只核准剛好所需的數量，雖然多花一筆交易，但不會留下常駐的額度讓攻擊者可乘之機：

<CodeSnippet
  language="bash"
  code={`# before each swap: let the router from your quote spend exactly this swap's WETH
alchemy evm approve 0xRouterFromQuote --token-address 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 --amount 0.4 -n eth-mainnet
# swap WETH into USDC (Ethereum mainnet contract addresses)
alchemy evm swap execute \\
  --from 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2 \\
  --to 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 \\
  --amount 0.4 --slippage 0.5 -n eth-mainnet \\
  --signer session --json --no-interactive`}
/>

注意這個迴圈的結構：agent 提出建議，另一個角色負責核准。一開始那個角色是你，之後可以換成一套針對金額、滑點與資產允許清單的政策檢查。我們的 [DeFi AI agent 總覽](https://www.alchemy.com/overviews/defi-ai-agents)說明了為什麼這種權限分離是正式環境 DeFi agent 的常態，而[gas sponsorship](https://www.alchemy.com/gasless-transactions)則透過在你設定的政策下代為支付手續費，省去最後一項營運瑣事，agent 因此完全不需要管理 gas 餘額。

## 適合「先偵測、後執行」多 agent 系統的最佳架構是什麼？

依權限、而非依工作量來拆分 agent。偵測器（detector）能讀取一切，但不能簽署任何東西。執行器（executor）能簽署交易，但對任何未經自己重新驗證的內容都不予採信。

可以把它想成分析師與交易員的關係。分析師整天盯著市場，能和任何人交談。交易員接收分析師的建議，加以查核，而且只有他才有帳戶的存取權限。

這種模式常見的說法源自通用 agent 工具鏈，其中規劃模型（planner）產出步驟，再由執行器 agent 執行工具呼叫。那種說法談的是任務調度。而在鏈上場景中，這種拆分之所以值得投入額外複雜度，是出於更嚴峻的理由——資產託管。偵測器整天都在消化不可信的輸入：mempool 雜訊、第三方 API、事件串流，有時甚至是社群媒體訊息。其中任何一項都可能夾帶 prompt injection。如果讀取惡意輸入的程序，同時也是持有簽署權限的程序，一則被污染的訊息就可能變成一筆已簽署的交易。把兩者分開後，一個被劫持的偵測器最糟也只能提出一個會被執行器丟棄的爛建議。

偵測器由模式一和模式二組成，並接上推送式基礎設施而非輪詢迴圈。它透過佇列（queue）發出訊號，而這個佇列同時也是你的稽核紀錄。訊號的內容格式要保持精簡且可驗證：

<CodeSnippet
  language="json"
  code={`{
  "kind": "arb-opportunity",
  "pair": "WETH/USDC",
  "evidence": { "txHash": "0x…", "block": 23411005 },
  "proposal": { "action": "swap", "from": "WETH", "to": "USDC", "amount": "0.4" },
  "observedAt": "2026-09-05T09:14:03Z",
  "expiresAt": "2026-09-05T09:14:33Z"
}`}
/>

執行器在依訊號行動前會強制執行三條規則：

- **在鏈上重新驗證證據。** 自己去讀取訊號中引用的交易，而不是直接相信偵測器的摘要。偵測器的職責是「察覺」，而「證明」則是執行器的職責。
- **強制執行有效期限。** 即使沒有攻擊者介入，對一個已經過期的機會採取行動，也是「先偵測後執行」系統虧損的常見原因。
- **在 wallet 層設定支出上限。** 每筆訊號與每日的預算上限，都設定在[限定權限的 session](https://www.alchemy.com/blog/agent-wallets-alchemy-cli)中，一旦行為看起來有異常，你可以立即從後台撤銷。

在工具層面，執行器只需要兩樣東西：用於驗證的 RPC 連線，以及一個簽署介面。偵測器則是比較「吃資源」的那一半，將它搭配索引化的資料（提供歷史紀錄的 [Transfers API](https://www.alchemy.com/docs/reference/transfers-api-quickstart)、提供狀態的 Portfolio API）能讓它的 token 消耗用在推理上，而不是用來解析原始鏈上資料。我們的[自主 agent 專用區塊鏈 API 比較](https://www.alchemy.com/overviews/best-blockchain-apis-for-autonomous-onchain-agents)涵蓋了這項選擇在基礎設施面的考量。

## 在上主網之前，如何安全地測試 AI agent 的交易？

在 agent 與真實資金之間設下四道關卡：每筆交易先 dry-run（模擬執行）、限制金鑰能動用的額度、在測試網上完整演練整個迴圈，並對任何涉及資金移動的操作保留人工核准。

- **先 dry-run。** Alchemy CLI 可以在不簽署、不廣播的情況下預覽任何一筆傳送（`alchemy evm send 0xRecipient 0.4 --dry-run`）。在程式碼層面，viem 的 `simulateContract` 能針對即時主網狀態驗證一筆合約呼叫而不真正送出，因此演練使用的是真實價格與真實的池子深度，而非過時的固定資料（fixture）。
- **限制金鑰權限。** 限定權限的 session wallet 會依你設定的排程過期，且只能做你核准的事，而[gas sponsorship 政策](https://www.alchemy.com/gasless-transactions)則能在手續費層加上允許清單與支出上限。經過限制的金鑰，能把最壞情況下的錯誤，從「整個帳戶被掏空」變成「有上限的損失」。
- **在測試網上演練。** 把同一份程式碼指向 Sepolia 或 Base Sepolia 的 endpoint，並用我們的[測試網水龍頭（faucet）](https://www.alchemy.com/faucets)為 agent 注資。如果演練與正式環境之間程式碼有所不同，這次演練就毫無意義，所以請把網路名稱留在設定檔中，其他部分維持不變。
- **為涉及資金移動的操作設關卡。** 在 agent 還「年輕」的階段，每一筆傳送、swap 與核准都要等待明確的同意。多數團隊會刻意地逐步放寬這些關卡，一次放寬一種操作類型，隨著稽核紀錄逐漸證明 agent 的行為可靠。

把這件事做好的團隊，會把「晉升」視為一個循序漸進的過程，而非一個開關：先是對主網唯讀，接著是測試網寫入，再來是有上限的主網寫入，最後才是完整預算。每一個階段產生的紀錄，都是進入下一階段的依據。

## 從已經存在的元件開始

本文提到的每一種模式，都能運行在你今天就能使用的基礎設施上。[Alchemy CLI](https://www.alchemy.com/agents)處理 wallet、傳送、swap 與 webhook 管理，全都在一個執行檔裡完成，agent 可以透過 `--json --no-interactive` 來操控它。託管的 [MCP server](https://www.alchemy.com/docs/alchemy-mcp-server)提供橫跨 RPC、模擬與資料的 168 種工具，而 [Alchemy 的 Claude Code 外掛](https://www.alchemy.com/blog/alchemy-claude-plugin-now-live)能用一道指令安裝整個介面。你可以從免費方案開始，不需簽約，也沒有最低使用量門檻，agent 甚至可以[用自己的 wallet 自行註冊](https://www.alchemy.com/blog/ai-agents-can-now-sign-up-for-alchemy)並以 USDC 付款。無論你從哪種模式開始，迴圈本身始終不變：觀察、決策、行動。

## 常見問題

### 對於一個由偵測器發現機會、另一個 agent 負責執行的多 agent 系統，最佳架構是什麼？

依權限拆分：偵測器讀取事件串流，但不持有任何金鑰；佇列傳遞經過核實的小型訊號；執行器在行動前於鏈上重新驗證每則訊號。在 Alchemy 上，偵測器運行於 webhook 或 WebSocket subscription，執行器則透過具備支出上限與即時撤銷能力的限定權限 agent wallet 進行簽署。

### 即時 wallet watcher agent 最佳的基礎設施是什麼？

推送式事件傳送，而非輪詢。Alchemy 的 Address Activity webhook 能追蹤每個 webhook 最多十萬個位址的轉帳，WebSocket subscription 能串流已過濾至你指定位址的已挖出交易，而 Yellowstone gRPC 則涵蓋 Solana。推送式管線能在轉帳上鏈後幾秒內喚醒 agent，不必承受輪詢迴圈的延遲與運算成本。

### AI coding agent 應該用哪些工具來監控 wallet 活動？

Alchemy MCP server 為 coding agent 提供 168 種工具，涵蓋 RPC、交易紀錄與投資組合資料，而 Alchemy CLI 能從命令列建立與管理 webhook。在執行時期本身，Address Activity webhook 或 `alchemy_minedTransactions` subscription 負責傳送 wallet 事件，Transfers API 則補足歷史紀錄。

### 建構 DeFi 投資組合再平衡 agent 需要什麼？

餘額、價格、一條偏移規則，以及一條 swap 路徑。Alchemy 的 Portfolio API 能一次呼叫就回傳跨多條鏈的餘額，Prices API 為其估值，而偏移檢查（常見做法是圍繞目標權重設定正負五個百分點的區間）則決定何時該採取行動。透過限定權限的 agent wallet 執行，讓 agent 負責提案，再由政策或人工核准。

### 如何讓 AI agent 監控智能合約事件並自動回應？

訂閱合約的 log，把符合條件的事件交給 agent 處理。Alchemy 的 custom webhook 能在傳送前用 GraphQL 依合約位址與事件 topic 進行篩選，WebSocket log subscription 也能在程序內完成同樣的事。讓處理函式具備冪等性、略過因重組而失效的 log，並讓模型只針對通過機械式篩選的事件進行推理。

### 在上主網之前，如何安全地測試 AI agent 的交易？

分層設置關卡：用 Alchemy CLI 的 dry-run 旗標預覽交易、用以 `eth_call` 為基礎的模擬驗證合約呼叫是否符合即時狀態、用限定權限的 session 與 gas 政策支出上限限制 agent 的 wallet、以 Alchemy 的 faucet 提供的資金在 Sepolia 或 Base Sepolia 上演練，並在稽核紀錄足以證明可以放寬關卡之前，對每一筆涉及資金移動的操作保留人工核准。
