dApp Docs/AI Agent DAO 治理实践指南
Development reference. Not independently verified for production.

AI Agent DAO 治理实践指南

链 ID: msg-chain-1 | 共识: DAR | 虚拟机: CosmWasm (WasmVM)
状态: 规划文档 — 主网裁决为 No-Go,所有数据均为主网预演
Gas: 1,000,000,000 attoMSG/gas
Gas 分配: 40% 验证者 / 30% 开发者 / 20% 燃烧 / 10% 基金会金库
地址格式: SHA3-512(前40位) + SHA-256 校验 | 签名: Dilithium-5 (公钥2592字节 / 私钥4864字节 / 签名4595字节)
AI Agent安全边界: 永不自主创建新合约,永不自主调整 Gas 参数,永不自主铸造/销毁代币

目录

  1. 引言
  2. DAO 架构基础
  3. 治理代币与投票权
  4. 提案生命周期
  5. DAO 多签治理
  6. 金库管理
  7. 模块化治理扩展
  8. AI Agent 自治治理集成
  9. 跨链治理
  10. 安全与审计
  11. 实践案例:创建 AI Agent DAO
  12. 总结与建议

1. 引言

1.1 AI Agent 为什么需要 DAO 治理

AI Agent 在去中心化网络中的自主操作带来了前所未有的效率提升,但也引入了新的治理挑战:

DAO(去中心化自治组织)提供了一套成熟的链上治理框架,使 AI Agent 的运营从「单一方控制」转向「社区共识驱动」。在 MSG Chain 上,CosmWasm 智能合约生态提供了完整的 DAO 基础设施,包括 cw-dao、cw3、cw4 等标准合约族,以及专为 AI Agent 场景设计的 dao_governance_v1 合约。

1.2 治理与自治的关系

治理(Governance)与自治(Autonomy)并非对立关系,而是分层协作:

层次 主体 决策方式 时间尺度
战略治理 DAO / 代币持有人 提案投票 天 ~ 周
战术决策 Agent 宪章 + 策略引擎 规则评估 秒 ~ 分
操作执行 Agent 运行时 自动执行 毫秒 ~ 秒

这种分层设计确保了:Agent 的日常操作高度自治,但关键决策(规则变更、大额支出、宪章修订)始终在 DAO 的控制之下。

1.3 适用范围

本指南涉及的所有合约部署、提案创建、投票执行等操作均以 msg-chain-1 为运行环境。


2. DAO 架构基础

2.1 CosmWasm DAO 合约族

MSG Chain 上的 DAO 治理体系基于 CosmWasm 生态的标准合约架构,核心包括以下合约族:

合约族 包路径 功能
cw-dao contracts/cosmwasm/all/cw_dao_v1/ DAO 核心:提案、投票、执行、金库
cw3-flex-multisig contracts/cosmwasm/all/cw3_flex_multisig_v1/ 灵活多签:动态投票权重
cw3-fixed-multisig contracts/cosmwasm/all/cw3_fixed_multisig_v1/ 固定多签:固定投票人
cw4-group contracts/cosmwasm/all/cw4_group_v1/ 成员组管理
cw4-stake contracts/cosmwasm/all/cw4_stake_v1/ 质押权重成员组
cw20-staked-balance-voting contracts/cosmwasm/all/cw20_staked_balance_voting_v1/ cw20 质押投票模块
cw-proposal-single contracts/cosmwasm/all/cw_proposal_single_v1/ 单一提案模块
cw-proposal-multiple contracts/cosmwasm/all/cw_proposal_multiple_v1/ 多选项提案模块
dao_governance_v1 contracts/cosmwasm/all/dao_governance_v1/ AI Agent 专用治理

上述合约在 MSG Chain 的 genesis registry v1 中通过 canonical key 注册,可通过注册中心解析实际部署地址。

2.2 DAO 合约架构层次

+----------------------------------------------------------+
|                     AI Agent DAO                           |
|  +------------------+  +-------------------------------+   |
|  | DAO Core (DAO)   |  | Proposal Modules              |   |
|  |  - 提案管理      |  |  - cw-proposal-single         |   |
|  |  - 投票统计      |  |  - cw-proposal-multiple       |   |
|  |  - 执行路由      |  |  - 自定义提案逻辑            |   |
|  +--------+---------+  +-------------------------------+   |
|           |                                                 |
|  +--------v---------+  +-------------------------------+   |
|  | Voting Module    |  | Treasury / Fund               |   |
|  |  - cw20-staked   |  |  - 金库资金管理               |   |
|  |  - cw4-group     |  |  - cw-payroll 支付流          |   |
|  |  - 委托投票      |  |  - 支出提案执行               |   |
|  +------------------+  +-------------------------------+   |
|           |                                                 |
|  +--------v---------+  +-------------------------------+   |
|  | C4 Group/Stake   |  | AI Agent 模块                 |   |
|  |  - 成员管理      |  |  - 宪章绑定                   |   |
|  |  - 权重计算      |  |  - 策略引擎集成               |   |
|  |  - 质押映射      |  |  - Agent 注册                 |   |
|  +------------------+  +-------------------------------+   |
+----------------------------------------------------------+

2.3 DAO 实例化消息结构

创建 DAO 的核心 InstantiateMsg 结构如下:

{
  "name": "AI Agent Trading DAO",
  "description": "管理 AI 交易 Agent 的去中心化组织",
  "image_url": "ipfs://Qm...",
  "automatically_add_cw20s": true,
  "automatically_add_cw721s": true,
  "voting_module": "msg1voting...",
  "proposal_modules": [
    "msg1proposal_single..."
  ],
  "threshold": {
    "absolute_count": {
      "weight": 3,
      "total_weight": null
    }
  },
  "max_voting_period": {
    "time": 604800
  },
  "only_members_execute": false,
  "allow_redelegation": false
}

字段说明:

字段 类型 说明
voting_module Addr 投票模块合约地址
proposal_modules Addr[] 提案模块合约地址列表
threshold Threshold 通过阈值(绝对数 / 百分比 / quorum)
max_voting_period Duration 最长投票期(秒或高度)
only_members_execute bool 是否仅成员可执行通过的提案
automatically_add_cw20s bool 是否自动接受 cw20 资产

2.4 DAO 核心接口

查询接口:

查询 返回值 说明
GetConfig DAO 配置 返回 DAO 的完整配置信息
GetProposal{proposal_id} 提案详情 查询指定提案
ListProposals{start_after, limit} 提案列表 分页查询提案
GetVote{proposal_id, voter} 投票记录 查询指定投票
ListVotes{proposal_id, start_after, limit} 投票列表 查询提案投票详情
Cw20Balance{address} 余额 查询 DAO 中某地址的 cw20 余额
Cw20TokenList{start_after, limit} 代币列表 DAO 持有的 cw20 列表
Cw721TokenList{start_after, limit} NFT 列表 DAO 持有的 cw721 列表
DumpState 完整状态 DAO 的完整状态快照

执行接口:

执行 说明
ExecuteProposal{proposal_id} 执行已通过的提案
CloseProposal{proposal_id} 关闭被否决或过期的提案
UpdateConfig{config} 更新 DAO 配置
WithdrawAdmin{admin} 转移管理权限
Propose{title, description, msgs, deposit} 创建提案
Vote{proposal_id, vote, rationale} 投票
UpdateCw20List{to_add, to_remove} 更新 cw20 列表

3. 治理代币与投票权

3.1 cw20-staked-balance-voting 模型

AI Agent DAO 中最常用的投票权重模型是 cw20-staked-balance-voting。它将 cw20 代币的质押余额作为投票权重的基础。

工作原理:

用户质押 cw20 代币 → 获得质押凭证 → 投票权 = 质押余额
用户可随时解除质押 → 等待解锁期 → 取回代币

投票权重计算公式:

voting_power = staked_balance * stake_multiplier

其中:
- staked_balance: 用户在 cw20-stake 合约中的质押余额
- stake_multiplier: 时间加权倍数(可选)
  - 质押 < 30 天: 1.0x
  - 质押 30-90 天: 1.2x
  - 质押 > 90 天: 1.5x

投票模块实例化:

{
  "token_address": "msg1cw20...",
  "stake_contract": "msg1stake..."
}

3.2 锁仓投票机制

为增强治理安全性,AI Agent DAO 支持锁仓投票(Locked Voting):

+-----------+     +------------------+     +--------------+
|  用户钱包  | --> |  质押合约         | --> |  投票模块     |
|           |     |  - 锁定代币       |     |  - 计算权重   |
| cw20代币  |     |  - 记录锁仓时间   |     |  - 记录投票   |
+-----------+     +------------------+     +--------------+
                        |
               +--------v--------+
               |  解锁等待期      |
               |  默认 14 天      |
               |  (可配置)        |
               +-----------------+

锁仓参数配置:

{
  "unstaking_duration": {
    "time": 1209600
  },
  "stake_multiplier": {
    "min_weight": "1.0",
    "max_weight": "2.0",
    "time_to_max": 7776000
  }
}

3.3 委托投票

委托投票允许代币持有人将投票权委派给他人,而代币本身仍然由持有人控制。这对于 AI Agent 场景尤为重要——AI Agent 自身可以接受委托,作为投票代理参与 DAO 治理。

委托流程:

委托人签名授权 → 链上注册委托 → 代理人获得投票权
委托人可随时变更或撤销委托

委托消息:

{
  "delegate": {
    "representative": "msg1agent..."
  }
}

撤销委托:

{
  "undelegate": {}
}

查询委托关系:

{
  "get_delegate": {
    "address": "msg1holder..."
  }
}
// 返回: { "representative": "msg1agent...", "delegated_at": "2026-01-01T00:00:00Z" }

3.4 AI Agent 代币发行与治理

AI Agent 通常发行自己的 cw20 治理代币作为 DAO 治理的基础。代币模型直接影响治理的去中心化程度。

代币模型 治理权重 适用场景
固定供应 + 公开销售 代币持有量 公募型 DAO
质押挖矿 质押量 激励型 DAO
声誉加权 贡献积分 服务型 AI Agent
NFT 绑定 NFT 持有量 会员制 DAO

关于 cw20 代币的具体发行流程,请参阅《AI Agent CW20 代币发行与管理指南》。


4. 提案生命周期

4.1 提案全流程

AI Agent DAO 中的提案遵循标准的生命周期,从创建到执行包含多个阶段:

+--------+     +--------+     +--------+     +--------+     +--------+
| 提案创建 | --> | 存款期  | --> | 投票期  | --> | 排队期  | --> | 提案执行 |
+--------+     +--------+     +--------+     +--------+     +--------+
    |              |              |              |              |
    | 提交提案     | 支付押金     | 成员投票     | 等待时间锁   | 执行提案消息
    | 设置标题     | 最低押金     | 统计权重     | 防止恶意      |
    | 描述和执行消息| 可退还       | 阈值检查     | 提案         |
    +--------------+--------------+--------------+--------------+

4.2 提案创建

提案类型:

类型 用途 示例
宪章修订 修改 Agent 行为规则 调整交易限额
金库支出 从 DAO 金库提取资金 支付开发费用
成员管理 添加/删除 DAO 成员 新增治理委员
参数调整 修改 DAO 配置 调整投票阈值
Agent 操作 指示 Agent 执行操作 执行跨链转账
合约升级 升级 DAO 或 Agent 合约 迁移到新版本

提案消息结构(TypeScript):

import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { GasPrice } from "@cosmjs/stargate";

const MSG_CHAIN_RPC = "https://rpc.msg-chain-1.msgchain.zone";
const MSG_CHAIN_PREFIX = "msg";
const GAS_PRICE = GasPrice.fromString("1000000000000000000attoMSG");
const DAO_CONTRACT = "msg1dao...";

async function createProposal(
  title: string,
  description: string,
  msgs: Array<{ contract: string; msg: any; funds: any[] }>,
  deposit: string
) {
  const mnemonic = process.env.MNEMONIC!;
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: MSG_CHAIN_PREFIX,
  });
  const [account] = await wallet.getAccounts();

  const client = await SigningCosmWasmClient.connectWithSigner(
    MSG_CHAIN_RPC, wallet, { gasPrice: GAS_PRICE }
  );

  const proposeMsg = {
    propose: {
      title,
      description,
      msgs,
      deposit,
    },
  };

  const result = await client.execute(
    account.address, DAO_CONTRACT, proposeMsg, "auto", `创建提案: ${title}`
  );

  const proposalId = extractProposalId(result);
  console.log(`提案已创建,ID: ${proposalId}`);
  return proposalId;
}

function extractProposalId(result: any): string {
  for (const event of result.events || []) {
    for (const attr of event.attributes) {
      if (attr.key === "proposal_id") return attr.value;
    }
  }
  throw new Error("无法解析提案 ID");
}

提案创建(Python):

import os
from cosmpy.aerial.client import LedgerClient
from cosmpy.aerial.wallet import LocalWallet
from cosmpy.aerial.client import NetworkConfig

MSG_CHAIN_RPC = "https://rpc.msg-chain-1.msgchain.zone"
MSG_CHAIN_PREFIX = "msg"
CHAIN_ID = "msg-chain-1"

def create_proposal(
    title: str, description: str, msgs: list,
    deposit: str, dao_contract: str
) -> str:
    mnemonic = os.getenv("MNEMONIC")
    wallet = LocalWallet.from_mnemonic(mnemonic, prefix=MSG_CHAIN_PREFIX)
    network_config = NetworkConfig(
        chain_id=CHAIN_ID, url=MSG_CHAIN_RPC,
        fee_minimum_gas_price=1000000000, fee_denomination="umsg",
        staking_denomination="umsg",
    )
    client = LedgerClient(network_config)

    propose_msg = {
        "propose": {
            "title": title, "description": description,
            "msgs": msgs, "deposit": deposit,
        }
    }
    tx = client.execute(wallet, dao_contract, propose_msg, gas_limit=3000000)

    for event in tx.events or []:
        for attr in event.get("attributes", []):
            if attr.get("key") == "proposal_id":
                return attr.get("value")
    raise ValueError("无法解析提案 ID")

4.3 提案存款

提案存款是防止垃圾提案的经济机制。只有当押金达到最低门槛时,提案才会进入投票阶段。

存款参数:

{
  "deposit_info": {
    "denom": "umsg",
    "amount": "10000000000",
    "refund_policy": "only_passed"
  }
}

4.4 投票

投票阶段是提案生命周期中最关键的环节。DAO 成员根据其投票权重对提案表达立场。

投票选项:

选项 含义 权重处理
yes 赞成 计入赞成票
no 反对 计入反对票
abstain 弃权 计入总投票量,不计入赞成或反对
veto 否决 计入否决票,触否决阈值则提案被拒

投票消息:

async function vote(
  proposalId: string, vote: "yes" | "no" | "abstain" | "veto",
  rationale?: string
) {
  const mnemonic = process.env.MNEMONIC!;
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: MSG_CHAIN_PREFIX,
  });
  const [account] = await wallet.getAccounts();
  const client = await SigningCosmWasmClient.connectWithSigner(
    MSG_CHAIN_RPC, wallet, { gasPrice: GAS_PRICE }
  );

  const voteMsg = {
    vote: {
      proposal_id: proposalId,
      vote: vote,
      rationale: rationale || "",
    },
  };

  return await client.execute(
    account.address, DAO_CONTRACT, voteMsg, "auto",
    `对提案 ${proposalId} 投 ${vote}`
  );
}

投票阈值模型:

{
  "threshold": {
    "threshold_quorum": {
      "threshold": {
        "percent": "0.50"
      },
      "quorum": {
        "percent": "0.20"
      }
    }
  }
}

其他阈值模型:

模型 说明 适用场景
absolute_count{weight} 绝对票数阈值 小型多签
absolute_percentage{percent} 绝对百分比 股权制 DAO
threshold_quorum{threshold, quorum} 阈值 + 法定人数 公链 DAO(推荐)

4.5 时间锁设计

时间锁(Timelock)是提案通过后到执行前的强制等待期,用于:

  1. 给持反对意见的成员留出退出时间
  2. 防止恶意提案的即时执行
  3. 允许安全监控系统检测异常提案
提案通过
    |
    v
+----------------+     +------------------+     +------------+
| 排队期开始      | --> | 时间锁等待        | --> | 可执行      |
| (提案状态: Passed)|    | (提案状态: Executable)|    | (执行后: Executed)|
+----------------+     +------------------+     +------------+
    |
    v
等待 duration
(通常 24-48 小时)

时间锁配置:

{
  "timelock_duration": {
    "time": 172800
  }
}

172800 秒 = 48 小时。在 AI Agent DAO 中,建议将涉及金库支出和宪章修订的提案时间锁设为 48-72 小时,普通提案可设为 24 小时。

4.6 提案执行

提案投票通过且时间锁到期后,任何 DAO 成员均可触发执行。

async function executeProposal(proposalId: string) {
  const mnemonic = process.env.MNEMONIC!;
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: MSG_CHAIN_PREFIX,
  });
  const [account] = await wallet.getAccounts();
  const client = await SigningCosmWasmClient.connectWithSigner(
    MSG_CHAIN_RPC, wallet, { gasPrice: GAS_PRICE }
  );

  const executeMsg = { execute: { proposal_id: proposalId } };

  const result = await client.execute(
    account.address, DAO_CONTRACT, executeMsg, "auto",
    `执行提案 ${proposalId}`
  );
  return result;
}

执行时 DAO 合约会按顺序执行提案中定义的所有消息。如果其中任何消息失败,整个执行回滚(atomic execution)。

4.7 提案状态机

                  +-----------+
                  |   Draft   |
                  +-----+-----+
                        |
                   deposit >= min
                        |
                        v
                  +-----------+
            +---->|  Open     |<----+
            |     | (Voting)  |     |
            |     +-----+-----+     |
            |           |           |
         veto  +-------+-------+  reject
         ≥33%  |       |       |  (no > threshold)
            |   v       v       |
            | Pass    Reject    |
            |   |       |       |
            |   v       v       |
            | Active  +---------+---+
            | (Passed)|  Rejected   |
            |   |     +-------------+
            |   v
            |  timelock
            |   |
            |   v
            |  +-----------+
            |  | Executable|
            |  +-----+-----+
            |        |
            |     execute()
            |        |
            |        v
            |  +-----------+
            +--| Executed  |
               +-----------+

5. DAO 多签治理

5.1 多签合约族

多签治理是 DAO 的重要补充机制,特别适合 AI Agent 的日常管理和紧急操作。MSG Chain 提供了两种多签合约:

合约 包路径 投票权重 成员变更
cw3-flex-multisig contracts/cosmwasm/all/cw3_flex_multisig_v1/ 可配置权重 动态调整
cw3-fixed-multisig contracts/cosmwasm/all/cw3_fixed_multisig_v1/ 每人 1 票 重部署

5.2 cw3-fixed-multisig:固定多签

固定多签适合成员稳定的治理小组,如 AI Agent 的紧急委员会。

实例化:

{
  "signers": [
    { "address": "msg1admin1...", "weight": 1 },
    { "address": "msg1admin2...", "weight": 1 },
    { "address": "msg1agent...", "weight": 1 }
  ],
  "threshold": {
    "absolute_count": { "weight": 2, "total_weight": null }
  },
  "max_voting_period": { "time": 86400 }
}

创建多签交易:

import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { GasPrice } from "@cosmjs/stargate";

async function createMultisigProposal(
  client: SigningCosmWasmClient,
  sender: string,
  multisigContract: string,
  msgs: Array<{ contract: string; msg: any; funds: any[] }>,
  description: string
) {
  const proposeMsg = {
    propose: {
      title: description.substring(0, 64),
      description,
      msgs,
      latest: null,
    },
  };

  const result = await client.execute(
    sender, multisigContract, proposeMsg, "auto",
    `创建多签交易: ${description}`
  );
  return result;
}

多签投票:

async function voteMultisig(
  client: SigningCosmWasmClient,
  sender: string,
  multisigContract: string,
  proposalId: string,
  vote: "yes" | "no" | "abstain" | "veto"
) {
  const voteMsg = {
    vote: {
      proposal_id: proposalId,
      vote,
    },
  };

  return await client.execute(
    sender, multisigContract, voteMsg, "auto",
    `多签投票: ${vote}`
  );
}

5.3 cw3-flex-multisig:灵活多签

灵活多签支持动态权重和成员管理,适合需要频繁调整的 AI Agent 治理组。

实例化:

{
  "group_contract": "msg1cw4group...",
  "threshold": {
    "threshold_quorum": {
      "threshold": { "percent": "0.60" },
      "quorum": { "percent": "0.30" }
    }
  },
  "max_voting_period": { "time": 43200 },
  "only_members_execute": false
}

通过 cw4-group 合约管理成员列表,多签合约自动同步最新成员和权重。

更新 cw4-group 成员:

{
  "update_members": {
    "remove": ["msg1oldmember..."],
    "add": [
      {
        "addr": "msg1newagent...",
        "weight": 5
      }
    ]
  }
}

5.4 AI Agent 的多签组合

AI Agent DAO 中多签的典型应用模式:

+---------------------------+
|      AI Agent DAO         |
|                           |
|  +--------+  +----------+ |
|  | DAO    |  | 紧急多签  | |
|  | 全面   |  | 紧急操作  | |
|  | 治理   |  | 每日预算  | |
|  +--------+  +----------+ |
|       |           |        |
|  +--------v-----------v+  |
|  |  AI Agent 操作层     |  |
|  |  (宪章约束范围内)    |  |
|  +----------------------+  |
+---------------------------+

分层多签策略:

层级 治理体 阈值 操作范围 响应时间
L1 DAO 全面治理 50% 投票 + 20% 投票率 宪章修订、大额支出、合约升级 7 天
L2 紧急多签 3/5 签名 紧急暂停 Agent、每日预算内操作 1 小时
L3 Agent 自治 宪章规则评估 日常交易、监控、报告 实时

紧急多签配置示例:

{
  "signers": [
    { "address": "msg1founder...", "weight": 1 },
    { "address": "msg1sec...", "weight": 1 },
    { "address": "msg1ops...", "weight": 1 },
    { "address": "msg1legal...", "weight": 1 }
  ],
  "threshold": {
    "absolute_count": { "weight": 3, "total_weight": null }
  },
  "max_voting_period": { "time": 3600 }
}

紧急多签的权限应受 DAO 协议约束,并通过时间锁将操作记录上链以便审计。


6. 金库管理

6.1 合约金库架构

AI Agent DAO 的金库管理通过 cw-treasury 和 cw-fund 合约实现。金库合约负责安全保管 DAO 资产,并仅在执行通过 DAO 提案或有效的多签交易时放行资金。

+------------------+       +------------------+
|   DAO 治理        |       |   金库合约        |
|   - 提案创建      | ----> |   - 资金托管      |
|   - 投票通过      | 执行  |   - 支出控制      |
|   - 授权支出      |       |   - 余额查询      |
+------------------+       |   - 资产列表      |
                            +--------+---------+
                                     |
                          +----------v----------+
                          |   AI Agent 运营账户   |
                          |   - 日常Gas费用       |
                          |   - Agent 收入归集    |
                          +---------------------+

6.2 支出提案

金库的每一次支出都必须通过 DAO 提案或授权机制。

支出提案示例:

async function createSpendProposal(
  recipient: string,
  amount: string,
  denom: string,
  reason: string
) {
  const proposeMsg = {
    propose: {
      title: `金库支出: ${amount} ${denom}`,
      description: reason,
      msgs: [
        {
          contract: treasuryContract,
          msg: {
            spend: {
              recipient,
              amount: [{ denom, amount }],
            },
          },
          funds: [],
        },
      ],
      deposit: "10000000000",
    },
  };

  // ... 执行提案创建
}

批量支付支出提案:

{
  "propose": {
    "title": "AI Agent 季度运营支出",
    "description": "支付 Q2 2026 Agent 运营成本",
    "msgs": [
      {
        "contract": "msg1treasury...",
        "msg": {
          "spend": {
            "recipient": "msg1agent_ops...",
            "amount": [
              { "denom": "umsg", "amount": "500000000000" }
            ]
          }
        },
        "funds": []
      },
      {
        "contract": "msg1treasury...",
        "msg": {
          "spend": {
            "recipient": "msg1developer...",
            "amount": [
              { "denom": "umsg", "amount": "200000000000" }
            ]
          }
        },
        "funds": []
      }
    ],
    "deposit": "10000000000"
  }
}

6.3 支付流(cw-payroll)

对于周期性支出(如 Agent 运营成本、开发者报酬),cw-payroll 合约提供了在线的支付流功能。

创建支付流:

{
  "create_payment_stream": {
    "recipient": "msg1agent_ops...",
    "denom": "umsg",
    "rate": {
      "amount": "1000000000",
      "frequency": {
        "time": 86400
      }
    },
    "max_amount": "300000000000",
    "start_at": "2026-01-01T00:00:00Z",
    "end_at": "2026-12-31T00:00:00Z"
  }
}

查询支付流可提取金额:

{
  "payment_stream_available": {
    "stream_id": "stream-001"
  }
}
// 返回: { "available_amount": "5000000000" }

提取支付流:

{
  "withdraw_from_stream": {
    "stream_id": "stream-001",
    "amount": "5000000000",
    "recipient": "msg1agent_ops..."
  }
}

6.4 金库安全策略

安全措施 说明 建议值
支出限额 单笔提案最大支出 DAO 总资产的 10%
日支出上限 每日所有支出总和上限 DAO 总资产的 2%
时间锁 支出提案通过到执行的等待期 48 小时
目标白名单 支出只能发往白名单地址 通过 DAO 提案管理
多签审批 大额支出需要多签预审 超过 1% 总资产

金库支出控制合约:

DAO 可将金库支出权限委托给专门的支出控制合约(Spend Limit Contract),该合约实施上述安全策略。

{
  "instantiate_msg": {
    "dao_contract": "msg1dao...",
    "treasury_contract": "msg1treasury...",
    "spend_limits": [
      {
        "denom": "umsg",
        "max_per_proposal": "500000000000",
        "max_daily": "2000000000000",
        "min_timelock_seconds": 172800
      }
    ],
    "whitelist": [
      "msg1agent_ops...",
      "msg1developer..."
    ]
  }
}

7. 模块化治理扩展

7.1 提案模块

DAO 治理是可组合的。通过不同的提案模块组合,可以适应复杂的 AI Agent 治理需求。

cw-proposal-single:标准单一提案模块

提案标题 + 描述 + N 条执行消息 + 押金
            |
   投票: yes / no / abstain / veto
            |
   通过 / 拒绝

cw-proposal-multiple:多选项提案模块

提案标题 + 描述 + N 个互斥选项
            |
   投票: 选择单个选项
            |
   得票最高的选项执行

提案模块组合模式:

+----------------------------------------+
|          AI Agent DAO                   |
|                                         |
|  提案模块 1: 标准提案                    |
|  (cw-proposal-single)                   |
|  - 宪章修订                            |
|  - 成员管理                            |
|  - 金库支出 (< 100K MSG)               |
|  - 投票期: 3 天                         |
|  - 阈值: 50% + 20% 投票率               |
|                                         |
|  提案模块 2: 大额支出提案                |
|  (cw-proposal-single, 高门槛)           |
|  - 金库支出 (>= 100K MSG)              |
|  - 投票期: 7 天                         |
|  - 阈值: 66.67% + 40% 投票率            |
|  - 时间锁: 72 小时                      |
|                                         |
|  提案模块 3: Agent 操作提案              |
|  (cw-proposal-single, 快速通道)         |
|  - Agent 指令                           |
|  - 投票期: 1 天                         |
|  - 阈值: 60% + 15% 投票率               |
|  - 时间锁: 6 小时                       |
+----------------------------------------+

7.2 投票模块

投票模块决定了 DAO 成员的投票权重如何计算。

投票模块 权重计算 适用场景
cw20-staked-balance-voting 质押的 cw20 余额 代币持有者治理
cw4-group-voting cw4-group 成员权重 联盟治理
cw4-stake-voting cw4-stake 质押权重 质押治理
cw721-staked-balance-voting 质押的 NFT 数量 NFT 治理

投票模块配置示例:

// cw20-staked-balance-voting
{
  "token_address": "msg1cw20...",
  "stake_contract": "msg1stake..."
}

// cw4-group-voting
{
  "group_contract": "msg1cw4group..."
}

7.3 模块组合最佳实践

模式 A:代币治理 + 多签备份

投票模块: cw20-staked-balance-voting (主)
多签合约: cw3-flex-multisig (紧急备份)

规则:
- 常规操作: 通过 DAO 提案(cw20 投票)
- 紧急暂停: 多签可直接暂停 Agent(3/5 签名)
- 多签操作: 事后必须在 DAO 中补交提案

模式 B:双阶段提案

提案模块 1: cw-proposal-single (初筛)
提案模块 2: cw-proposal-single (终审)

流程:
1. 初筛: 简单多数通过(5 天投票期)
2. 终审: 三分之二绝对多数通过(7 天投票期)
3. 适用于: 核心宪章修订、大额金库支出

模式 C:Agent 分组治理

cw4-group: agent-trading-group  {weight: 5}
cw4-group: agent-data-group     {weight: 3}
cw4-group: agent-ops-group      {weight: 2}

cw4-group-voting: 按组权重投票

规则:
- 跨组提案: 所有组总权重评估
- 组内提案: 仅相关组成员评估

7.4 子 DAO 模式

大型 AI Agent 生态可以创建子 DAO(SubDAO)实现分层管理。

+----------------------------+
|       主 DAO (Parent)       |
|  - 整体宪章                |
|  - 跨 Agent 资源分配        |
|  - 子 DAO 创建授权          |
+----------+----------------+
           |
     +-----+-----+
     |           |
+----v---+  +---v----+
| 交易 DAO|  | 数据 DAO|
| Agent A |  | Agent B |
| Agent C |  | Agent D |
+---------+  +---------+

子 DAO 创建提案:

{
  "propose": {
    "title": "创建交易子 DAO",
    "description": "为交易 Agent 群组创建独立的治理单元",
    "msgs": [
      {
        "contract": "msg1dao_factory...",
        "msg": {
          "create_sub_dao": {
            "name": "Trading Agent SubDAO",
            "voting_module": "msg1voting...",
            "proposal_modules": ["msg1proposal_single..."],
            "initial_assets": [
              { "denom": "umsg", "amount": "500000000000" }
            ]
          }
        },
        "funds": []
      }
    ],
    "deposit": "10000000000"
  }
}

8. AI Agent 自治治理集成

8.1 Agent 宪章如何映射为 DAO 提案规则

AI Agent 的宪章(Constitution)是 DAO 治理的规则基础。宪章中的 governance 字段直接定义了提案的治理参数。

宪章 → DAO 映射表:

宪章字段 DAO 映射 说明
governance.amendment_policy DAO 提案模块配置 定义修订策略
governance.voting_config.pass_threshold DAO 阈值配置 通过阈值
governance.voting_config.min_voting_period DAO 投票期配置 最小投票期
governance.voting_config.quorum DAO 法定人数配置 投票率要求
governance.voting_config.proposal_deposit DAO 押金配置 提案押金
governance.emergency_override 多签合约配置 紧急覆盖机制

宪章修订的完整流程:

1. DAO 成员创建 "修订宪章" 提案
   - 提案包含新的宪章 JSON
   - 提案中引用旧版本号和新版本号
2. DAO 投票期:
   - 根据宪章版本号决定所需票数
   - PATCH 版本: 简单多数
   - MINOR 版本: 66.67% 多数
   - MAJOR 版本: 75% 绝对多数
3. 提案通过后,执行消息调用 `ai_agent_constitution_v1` 合约
   - update_constitution { agent_id, new_constitution, new_hash }
4. 宪章合约验证:
   - 提案 ID 和 DAO 合约地址校验
   - 版本号语义校验
   - 约束兼容性检查
5. 新宪章生效,Agent 策略引擎加载新规则

宪章修订提案示例:

async function proposeCharterAmendment(
  agentId: string,
  newConstitution: object,
  oldVersion: string,
  newVersion: string
) {
  const constitutionHash = hashConstitution(newConstitution);

  const proposeMsg = {
    propose: {
      title: `修订 Agent ${agentId} 宪章: ${oldVersion} → ${newVersion}`,
      description: `宪章版本升级说明...`,
      msgs: [
        {
          contract: CONSTITUTION_CONTRACT,
          msg: {
            update_constitution: {
              agent_id: agentId,
              new_constitution: newConstitution,
              new_hash: constitutionHash,
              proposal_id: null,
            },
          },
          funds: [],
        },
      ],
      deposit: "10000000000",
    },
  };

  return await client.execute(
    sender, DAO_CONTRACT, proposeMsg, "auto",
    `宪章修订提案: ${agentId}`
  );
}

8.2 AI Agent 在 DAO 中的角色

AI Agent 在 DAO 中可以扮演多种角色,从单纯的执行者到治理参与者:

角色 权限 治理参与度 示例
执行人 仅执行已通过的提案 低 自动执行金库支出
投票代理 接受委托代为投票 中 代表小持有人投票
治理委员 拥有直接投票权 高 DAO 核心治理 Agent
提案者 可创建提案 中高 自动提交运营提案
观察者 只读监控 低 合规监控 Agent

角色 A:AI Agent 作为执行人

Agent 监听 DAO 合约的事件,当特定提案通过后自动执行后续操作。

// agent_executor.ts
import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";

async function monitorAndExecute(
  daoContract: string,
  agentActions: Record<string, (proposal: any) => Promise<void>>
) {
  const client = await CosmWasmClient.connect(MSG_CHAIN_RPC);

  // 监听已通过的提案
  const proposals = await client.queryContractSmart(daoContract, {
    list_proposals: {
      start_after: lastCheckedProposalId,
      limit: 10,
    },
  });

  for (const proposal of proposals.proposals) {
    if (proposal.status === "passed" && agentActions[proposal.id]) {
      console.log(`执行提案 ${proposal.id} 的 Agent 操作`);
      await agentActions[proposal.id](proposal);
    }
  }
}

角色 B:AI Agent 作为投票代理

Agent 接受代币持有人的委托,按照预设的投票策略参与 DAO 治理。

// agent_voting_delegate.ts
interface VotingStrategy {
  type: "follow_dao_recommendation" | "fixed_stance" | "ai_analyzed";
  params: Record<string, any>;
}

async function analyzeAndVote(
  proposalId: string,
  proposal: any,
  strategy: VotingStrategy
) {
  let vote: "yes" | "no" | "abstain" | "veto";

  switch (strategy.type) {
    case "fixed_stance":
      vote = strategy.params.defaultVote;
      break;
    case "ai_analyzed":
      vote = await aiAnalyzeProposal(proposal);
      break;
    default:
      vote = "abstain";
  }

  // 执行投票
  const voteMsg = {
    vote: {
      proposal_id: proposalId,
      vote: vote,
      rationale: "AI 代理自动投票",
    },
  };

  await client.execute(
    agentAddress, daoContract, voteMsg, "auto", `AI 代理自动投票`
  );
}

角色 C:AI Agent 作为治理委员

Agent 拥有自己的治理代币质押,直接参与 DAO 投票。

// agent_governance_member.ts
async function delegateToAgent() {
  const delegateMsg = {
    delegate: {
      representative: agentAddress,
    },
  };

  // 代币持有人将投票权委托给 Agent
  await client.execute(
    holderAddress, stakingContract, delegateMsg, "auto", "委托投票给 AI Agent"
  );
}

8.3 自治治理集成架构

+---------------------------+       +----------------------------+
|      DAO 治理层            |       |   AI Agent 自治层          |
|                           |       |                            |
|  DAO 核心合约              |       |  ai_agent_constitution_v1   |
|  - 提案管理               | <---> |  - 宪章存储               |
|  - 投票统计               | 规则  |  - 策略引擎               |
|  - 执行路由               | 映射  |  - 规则评估               |
|                           |       |                            |
|  cw-proposal-single       |       |  Agent 注册中心            |
|  - 宪章修订提案           |       |  - 能力声明               |
|  - 版本验证               |       |  - 宪章哈希绑定           |
|                           |       |                            |
|  cw20-staked-balance-voting|      |  Agent 运行时              |
|  - 权重计算               |       |  - 交易执行               |
|  - 委托管理               |       |  - 事件响应               |
+---------------------------+       +----------------------------+
              |                                  |
              +-----------+  IBC / 事件  +--------+
                          |               |
                   +------v---------------v------+
                   |     链上事件总线              |
                   |     - 提案事件               |
                   |     - 投票事件               |
                   |     - 执行事件               |
                   |     - Agent 操作事件          |
                   +-----------------------------+

8.4 自动治理提案

AI Agent 可以根据预设条件自动创建治理提案,实现"条件触发 → 治理响应"的自动化闭环。

自动化提案场景:

触发条件 自动提案类型 示例
Agent 余额低于阈值 补充运营资金 余额 < 10,000 MSG 时申请充值
市场波动率超标 调整交易限额 VIX > 30 时提案降低杠杆
宪章约束过时 提案修订宪章 检测到新合规要求时更新规则
新 Agent 加入 提案批准加入 自动提交成员添加提案
定期报告 自动审计提案 每月自动创建资金使用报告

自动提案 Agent 实现:

// auto_proposer.ts
interface AutoProposalRule {
  checkCondition: () => Promise<boolean>;
  buildProposal: () => Promise<ProposalPayload>;
  cooldownSeconds: number;
  lastTriggeredAt: number;
}

async function autoProposalLoop(rules: AutoProposalRule[]) {
  while (true) {
    for (const rule of rules) {
      const now = Math.floor(Date.now() / 1000);
      if (now - rule.lastTriggeredAt < rule.cooldownSeconds) continue;

      const shouldPropose = await rule.checkCondition();
      if (shouldPropose) {
        const proposal = await rule.buildProposal();
        await createProposal(
          proposal.title,
          proposal.description,
          proposal.msgs,
          proposal.deposit
        );
        rule.lastTriggeredAt = now;
      }
    }
    await sleep(60000); // 每分钟检查一次
  }
}

9. 跨链治理

9.1 IBC 治理通信

跨链 DAO 治理允许部署在不同链上的 AI Agent DAO 通过 IBC 协议进行协调。

+------------------+          IBC          +------------------+
| msg-chain-1      |                       | chain-other      |
|                  |   ICS-20 (资金传输)    |                  |
| AI Agent DAO A   | <====================> | DAO B            |
| m: msg1dao_a     |                       | m: ...           |
|                  |   ICS-27 (跨链账户)    |                  |
| Agent A          | <====================> | Agent B          |
+------------------+                       +------------------+

9.2 跨链 DAO 协调模型

模型 A:中继链治理

MSG Chain (治理中心)
+------------------+
| 主 DAO           |
| - 全局宪章       |
| - 跨链提案       |
| - 资源分配       |
+--------+---------+
         |
    IBC  |   IBC
         |
+--------v------+  +--------v------+
| Chain A       |  | Chain B       |
| SubDAO A      |  | SubDAO B      |
| Agent A-1     |  | Agent B-1     |
+---------------+  +---------------+

模型 B:跨链多签协调

使用 IBC 在多链之间同步多签状态,实现跨链一致性的治理决策。

{
  "ibc_multisig_proposal": {
    "title": "跨链资金调配",
    "chain_a_dao": "msg1dao_a...",
    "chain_b_dao": "...",
    "action": {
      "chain": "chain-other",
      "contract": "...",
      "msg": { "spend": { "recipient": "...", "amount": [...] } }
    },
    "ibc_timeout": 600
  }
}

9.3 与 MSG Chain Registry 的交互

MSG Chain 的 genesis registry v1 提供了 canonical key 到合约地址的解析服务,这对于跨链治理中的地址寻址至关重要。

Registry 查询接口:

import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const REGISTRY_CONTRACT = "msg1registry...";

async function resolveContractAddress(canonicalKey: string): Promise<string> {
  const client = await CosmWasmClient.connect(MSG_CHAIN_RPC);
  const result = await client.queryContractSmart(REGISTRY_CONTRACT, {
    resolve: { key: canonicalKey },
  });
  return result.address;
}

// 示例:解析 DAO 治理合约地址
const daoAddress = await resolveContractAddress("dao_governance_v1");
console.log(`DAO 治理合约地址: ${daoAddress}`);

const treasuryAddress = await resolveContractAddress("dao_treasury_v1");
console.log(`DAO 金库合约地址: ${treasuryAddress}`);

Registry 注册的 DAO 相关 canonical key:

Canonical Key 合约 说明
dao_governance_v1 DAO 治理合约 AI Agent DAO 核心
dao_treasury_v1 DAO 金库合约 资产管理
dao_factory_v1 DAO 工厂合约 创建新 DAO
cw_dao_v1 cw-dao 实现 标准 DAO 模板

多链 DAO 查询:

async function queryCrossChainDAOs() {
  const client = await CosmWasmClient.connect(MSG_CHAIN_RPC);

  // 查询 DAO 的跨链连接
  const ibcConnections = await client.queryContractSmart(daoContract, {
    list_ibc_connections: {},
  });

  for (const conn of ibcConnections.connections) {
    console.log(`IBC 连接: ${conn.chain_id} → ${conn.dao_address}`);
    console.log(`状态: ${conn.status}`);
    console.log(`上次同步: ${conn.last_sync}`);
  }
}

9.4 IBC 治理提案示例

import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { GasPrice } from "@cosmjs/stargate";

async function createIBCGovernanceProposal(
  client: SigningCosmWasmClient,
  sender: string,
  ibcChannel: string,
  remoteDaoAddress: string,
  proposalPayload: any
) {
  const ibcMsg = {
    channel: ibcChannel,
    memo: JSON.stringify({
      wasm: {
        contract: remoteDaoAddress,
        msg: proposalPayload,
      },
    }),
    timeout: { timestamp: Date.now() + 600000 }, // 10 分钟超时
  };

  // 通过 IBC 发送治理消息到远程 DAO
  const result = await client.execute(
    sender,
    daoContract,
    {
      propose_cross_chain: {
        channel_id: ibcChannel,
        remote_dao: remoteDaoAddress,
        proposal: proposalPayload,
        ibc_timeout: 600,
      },
    },
    "auto",
    "跨链治理提案"
  );

  return result;
}

10. 安全与审计

10.1 DAO 合约安全最佳实践

合约权限控制:

+------------------+
| DAO 合约          |
| - 所有者: DAO 本身 |  ← DAO 控制自身(无外部所有者)
| - 管理员: 无       |  ← 不设管理员(防单点故障)
| - 执行者: 提案系统  |  ← 仅提案通过可执行
+------------------+
安全实践 说明 实现方式
无管理员账户 DAO 合约不应有超级管理员 UpdateConfig 需提案投票
最小权限原则 每个合约仅持有所需权限 合约间的细粒度授权
防御性编程 所有输入验证、边界检查 CosmWasm 类型安全、assert
暂停机制 紧急情况可暂停关键操作 多签暂停 + DAO 恢复
可升级安全 升级需 DAO 批准 提案执行合约迁移

代码安全检查清单:

// DAO 合约安全检查示例
// 1. 防止重入攻击
#[entry_point]
fn execute(deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg) -> StdResult<Response> {
    // 使用立即模型,不保存中间状态
    match msg {
        ExecuteMsg::Vote { .. } => {
            // 检查投票者余额,不信任外部输入
            let balance = query_balance(&deps, &info.sender);
            // ...
        }
        ExecuteMsg::ExecuteProposal { proposal_id } => {
            // 原子执行:失败全部回滚
            let msgs = prepare_execution_msgs(proposal_id)?;
            Ok(Response::new()
                .add_messages(msgs)
                .add_attribute("action", "execute_proposal")
                .add_attribute("proposal_id", proposal_id.to_string()))
        }
    }
}

10.2 提案攻击向量

攻击类型 描述 防御措施
闪贷投票操纵 借入大量代币短期投票 质押解锁期 ≥ 14 天
Sybil 攻击 创建多个账户分散投票 投票权重与质押量挂钩
提案垃圾邮件 大量创建低质量提案 提案押金机制
时间锁绕过 恶意通过提案立即执行 强制时间锁 24h+
投票贿赂 链下收买投票权 隐私投票、委托透明度
重放攻击 跨链重放提案 IBC 提案含唯一 nonce
治理攻击 51% 控制 DAO 超多数阈值 + 时间锁

闪贷防御机制:

// 防御闪贷投票:检查代币质押时长
function getVotingPower(staker: Addr, stakeContract: StakeContract) -> Uint128 {
    let stakingInfo = stakeContract.query_staking_info(&staker);
    
    // 检查代币是否刚被质押(闪贷攻击)
    if stakingInfo.staked_at > env.block.time.minus_days(UNSTAKING_DELAY_DAYS) {
        return Uint128::zero(); // 最近质押的代币无投票权
    }
    
    // 时间加权投票权
    let daysStaked = (env.block.time - stakingInfo.staked_at).days();
    let multiplier = min(1.0 + (daysStaked * 0.01), 2.0); // 最高 2x
    
    return stakingInfo.balance * multiplier;
}

提案审核清单:

检查项 说明
提案人身份 是否有资格创建提案
押金是否充足 押金是否 ≥ 最低要求
消息格式 执行消息是否合法
Gas 预算 执行是否会在 Gas 限制内完成
目标合约可信 提案调用的合约是否在白名单中
金额限制 支出金额是否在预算范围内
重放防护 IBC 提案是否有唯一标识

10.3 DAO 合约审计流程

AI Agent DAO 的合约审计应遵循以下流程:

1. 代码审查阶段
   - 检查合约权限模型
   - 验证阈值计算逻辑
   - 审查时间锁实现
   - 确认投票权重计算正确性

2. 功能测试阶段
   - 提案完整生命周期测试
   - 边界条件测试(0 投票、100% 投票)
   - 金库支出测试
   - 多签组合测试

3. 安全测试阶段
   - 闪贷攻击模拟
   - Sybil 攻击模拟
   - 重放攻击测试
   - 权限提升测试

4. 形式化验证(可选)
   - 投票模型数学验证
   - 资金流向图分析
   - 状态机完整性检查

10.4 运行时安全监控

// dao_security_monitor.ts
interface SecurityAlert {
  type: "suspicious_proposal" | "abnormal_vote" | "treasury_anomaly";
  severity: "low" | "medium" | "high" | "critical";
  details: string;
  proposalId?: string;
  timestamp: string;
}

class DAOSecurityMonitor {
  private alerts: SecurityAlert[] = [];

  async checkProposal(proposal: any): Promise<SecurityAlert[]> {
    const findings: SecurityAlert[] = [];

    // 检查提案是否包含高风险消息
    for (const msg of proposal.msgs) {
      if (msg.msg.hasOwnProperty("update_config")) {
        findings.push({
          type: "suspicious_proposal",
          severity: "high",
          details: `提案尝试更新 DAO 配置`,
          proposalId: proposal.id,
          timestamp: new Date().toISOString(),
        });
      }
    }

    // 检查金库支出金额
    const totalSpend = calculateTotalSpend(proposal);
    const treasuryBalance = await queryTreasuryBalance();
    if (totalSpend > treasuryBalance * 0.5) {
      findings.push({
        type: "treasury_anomaly",
        severity: "high",
        details: `提案支出占总金库 ${(totalSpend / treasuryBalance * 100).toFixed(1)}%`,
        proposalId: proposal.id,
        timestamp: new Date().toISOString(),
      });
    }

    return findings;
  }

  async checkVotingPattern(proposalId: string): Promise<SecurityAlert[]> {
    const votes = await queryAllVotes(proposalId);
    const findings: SecurityAlert[] = [];

    // 检测集中投票(可能贿赂攻击)
    const voterCount = votes.length;
    const topVoterWeight = Math.max(...votes.map(v => v.weight));
    const totalWeight = votes.reduce((s, v) => s + v.weight, 0);

    if (topVoterWeight / totalWeight > 0.5) {
      findings.push({
        type: "abnormal_vote",
        severity: "medium",
        details: `单个投票者占总权重 ${(topVoterWeight / totalWeight * 100).toFixed(1)}%`,
        proposalId,
        timestamp: new Date().toISOString(),
      });
    }

    return findings;
  }
}

11. 实践案例:创建 AI Agent DAO

11.1 案例概述

本节将通过一个完整的实践案例,演示从零创建 AI Agent DAO 的全流程。

场景:创建一个名为 "AI Trading Collective DAO" 的去中心化组织,管理三个 AI 交易 Agent。

需求:

  1. 发行治理代币(AITRADE)
  2. 部署 DAO 合约,通过代币质押投票
  3. 部署三个 AI Agent,每个 Agent 有独立的宪章
  4. 创建第一个提案:为 Agent 金库充值
  5. 实现自动化治理:Agent 按条件自动提交提案

11.2 步骤一:部署治理代币

首先部署 cw20 治理代币。

# 使用 CosmWasm CLI 或直接通过合约部署
# 1. 上传 cw20-base 合约代码
wasmcli tx wasm store cw20_base.wasm --from deployer --chain-id msg-chain-1 -y

# 2. 实例化 cw20 代币
wasmcli tx wasm instantiate <code_id> \
  '{
    "name": "AI Trade Token",
    "symbol": "AITRADE",
    "decimals": 6,
    "initial_balances": [
      {
        "address": "msg1founder...",
        "amount": "1000000000000"
      },
      {
        "address": "msg1dao_reserve...",
        "amount": "5000000000000"
      }
    ],
    "mint": {
      "minter": "msg1dao..."
    }
  }' \
  --label "AITRADE Token" \
  --from deployer \
  --chain-id msg-chain-1

TypeScript 部署代币:

import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { GasPrice } from "@cosmjs/stargate";
import * as fs from "fs";

async function deployToken() {
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: "msg",
  });
  const [account] = await wallet.getAccounts();
  const client = await SigningCosmWasmClient.connectWithSigner(
    "https://rpc.msg-chain-1.msgchain.zone",
    wallet,
    { gasPrice: GasPrice.fromString("1000000000000000000attoMSG") }
  );

  // 上传 cw20-base
  const wasm = fs.readFileSync("cw20_base.wasm");
  const uploadRes = await client.upload(account.address, wasm, "auto");
  console.log(`cw20-base 代码 ID: ${uploadRes.codeId}`);

  // 实例化
  const instantiateMsg = {
    name: "AI Trade Token",
    symbol: "AITRADE",
    decimals: 6,
    initial_balances: [
      { address: "msg1founder...", amount: "1000000000000" },
      { address: "msg1reserve...", amount: "5000000000000" },
    ],
    mint: { minter: account.address },
  };

  const { contractAddress } = await client.instantiate(
    account.address, uploadRes.codeId, instantiateMsg,
    "AITRADE Token", "auto"
  );
  console.log(`AITRADE 代币地址: ${contractAddress}`);
  return contractAddress;
}

11.3 步骤二:部署质押合约

部署 cw20-stake 合约,用于投票权计算。

async function deployStaking(tokenAddress: string) {
  // 上传 cw20-stake
  const stakeWasm = fs.readFileSync("cw20_stake.wasm");
  const uploadRes = await client.upload(account.address, stakeWasm, "auto");

  const instantiateMsg = {
    token_address: tokenAddress,
    unstaking_duration: { time: 1209600 }, // 14 天解锁期
  };

  const { contractAddress } = await client.instantiate(
    account.address, uploadRes.codeId, instantiateMsg,
    "AITRADE Staking", "auto"
  );
  console.log(`质押合约地址: ${contractAddress}`);
  return contractAddress;
}

11.4 步骤三:部署投票模块

部署 cw20-staked-balance-voting 模块。

async function deployVotingModule(tokenAddress: string, stakeAddress: string) {
  const wasm = fs.readFileSync("cw20_staked_balance_voting.wasm");
  const uploadRes = await client.upload(account.address, wasm, "auto");

  const instantiateMsg = {
    token_address: tokenAddress,
    stake_contract: stakeAddress,
  };

  const { contractAddress } = await client.instantiate(
    account.address, uploadRes.codeId, instantiateMsg,
    "AITRADE Voting Module", "auto"
  );
  console.log(`投票模块地址: ${contractAddress}`);
  return contractAddress;
}

11.5 步骤四:部署提案模块

部署 cw-proposal-single 模块。

async function deployProposalModule(
  daoContract: string, // 先部署 DAO 核心,此处循环依赖需注意
) {
  const wasm = fs.readFileSync("cw_proposal_single.wasm");
  const uploadRes = await client.upload(account.address, wasm, "auto");

  // 注意:提案模块在实例化时需要 DAO 地址
  // 实际部署顺序:DAO 核心可使用暂存地址后更新
  const instantiateMsg = {
    dao_address: daoContract,
    deposit_info: {
      denom: "umsg",
      amount: "10000000000",
      refund_policy: "only_passed",
    },
    max_voting_period: { time: 604800 }, // 7 天
    threshold: {
      threshold_quorum: {
        threshold: { percent: "0.50" },
        quorum: { percent: "0.20" },
      },
    },
    timelock_duration: { time: 172800 }, // 48 小时
    only_members_execute: false,
    close_proposal_on_execution_failure: true,
  };

  const { contractAddress } = await client.instantiate(
    account.address, uploadRes.codeId, instantiateMsg,
    "AITRADE Proposal Module", "auto"
  );
  return contractAddress;
}

11.6 步骤五:部署 DAO 核心合约

async function deployDAOCore(
  votingModule: string,
  proposalModule: string
) {
  const wasm = fs.readFileSync("cw_dao.wasm");
  const uploadRes = await client.upload(account.address, wasm, "auto");

  const instantiateMsg = {
    name: "AI Trading Collective DAO",
    description: "去中心化的 AI 交易 Agent 治理组织",
    voting_module: votingModule,
    proposal_modules: [proposalModule],
    threshold: {
      threshold_quorum: {
        threshold: { percent: "0.50" },
        quorum: { percent: "0.20" },
      },
    },
    max_voting_period: { time: 604800 },
    only_members_execute: false,
    automatically_add_cw20s: true,
    automatically_add_cw721s: true,
  };

  const { contractAddress } = await client.instantiate(
    account.address, uploadRes.codeId, instantiateMsg,
    "AI Trading Collective DAO", "auto"
  );

  // 更新提案模块中的 DAO 地址
  const updateMsg = {
    update_dao_address: {
      dao_address: contractAddress,
    },
  };
  await client.execute(account.address, proposalModule, updateMsg, "auto");

  return contractAddress;
}

11.7 步骤六:部署 AI Agent 合约

部署三个 AI 交易 Agent,每个 Agent 绑定独立的宪章。

async function deployAgent(
  agentId: string,
  constitution: object,
  daoContract: string
) {
  // 1. 部署 AI Agent 宪章合约
  const constitutionWasm = fs.readFileSync("ai_agent_constitution_v1.wasm");
  const uploadRes = await client.upload(account.address, constitutionWasm, "auto");

  const constitutionContract = await client.instantiate(
    account.address, uploadRes.codeId,
    { version: "1.0.0" },
    `Constitution: ${agentId}`, "auto"
  );

  // 2. 注册宪章
  await client.execute(
    account.address,
    constitutionContract.contractAddress,
    {
      register_constitution: {
        agent_id: agentId,
        constitution: constitution,
        constitution_hash: hashConstitution(constitution),
      },
    },
    "auto"
  );

  // 3. 注册到 Agent Registry
  // 假设 agent_registry_v1 地址从 registry 解析
  const registryAddr = await resolveContractAddress("agent_registry_v1");
  await client.execute(
    account.address,
    registryAddr,
    {
      register_agent: {
        agent_id: agentId,
        constitution_hash: hashConstitution(constitution),
        dao_contract: daoContract,
      },
    },
    "auto"
  );

  return constitutionContract.contractAddress;
}

11.8 步骤七:创建第一个提案

为 Agent 金库充值 500,000 MSG。

async function createFirstProposal(
  daoContract: string,
  agentAddress: string,
  treasuryContract: string
) {
  const proposeMsg = {
    propose: {
      title: "为 AI Trading Agent 金库充值",
      description: "为三个交易 Agent 提供初始运营资金 500,000 MSG",
      msgs: [
        {
          contract: treasuryContract,
          msg: {
            spend: {
              recipient: agentAddress,
              amount: [{ denom: "umsg", amount: "500000000000" }],
            },
          },
          funds: [],
        },
      ],
      deposit: "10000000000",
    },
  };

  const result = await client.execute(
    account.address, daoContract, proposeMsg, "auto",
    "第一个提案: 金库充值"
  );

  const proposalId = extractProposalId(result);
  console.log(`提案 #${proposalId} 已创建,请等待投票`);

  return proposalId;
}

11.9 步骤八:投票与执行

async function voteAndExecute(
  daoContract: string,
  proposalId: string
) {
  // 投票赞成
  await client.execute(
    account.address, daoContract,
    { vote: { proposal_id: proposalId, vote: "yes", rationale: "支持 Agent 运营" } },
    "auto"
  );

  // 查询提案状态
  const proposal = await client.queryContractSmart(daoContract, {
    get_proposal: { proposal_id: proposalId },
  });

  if (proposal.status === "passed") {
    console.log("提案已通过,等待时间锁...");

    // 等待时间锁到期
    const timelockEnd = new Date(proposal.timelock_end).getTime();
    const now = Date.now();
    if (now > timelockEnd) {
      // 执行提案
      await client.execute(
        account.address, daoContract,
        { execute: { proposal_id: proposalId } },
        "auto"
      );
      console.log("提案已执行");
    } else {
      const waitSec = Math.ceil((timelockEnd - now) / 1000);
      console.log(`还需等待 ${waitSec} 秒`);
    }
  }
}

11.10 步骤九:自动化治理配置

配置 AI Agent 自动提交运营提案。

// 自动充值监控 Agent
class AutoRefillAgent {
  private minBalance: bigint;
  private refillAmount: bigint;
  private lastProposalTime: number = 0;
  private cooldownPeriod: number = 86400; // 24 小时冷却

  constructor(
    private daoContract: string,
    private agentAddress: string,
    private treasuryContract: string,
    minBalance: string = "10000000000",
    refillAmount: string = "500000000000"
  ) {
    this.minBalance = BigInt(minBalance);
    this.refillAmount = BigInt(refillAmount);
  }

  async checkAndRefill() {
    // 查询 Agent 余额
    const balance = await client.queryContractSmart(this.agentAddress, {
      balance: {},
    });

    if (BigInt(balance) < this.minBalance) {
      const now = Math.floor(Date.now() / 1000);
      if (now - this.lastProposalTime < this.cooldownPeriod) {
        console.log("冷却期内,跳过自动提案");
        return;
      }

      // 自动创建充值提案
      const proposeMsg = {
        propose: {
          title: "自动充值: Agent 运营资金",
          description: `Agent 余额 ${balance} umsg,低于阈值 ${this.minBalance},自动请求充值`,
          msgs: [
            {
              contract: this.treasuryContract,
              msg: {
                spend: {
                  recipient: this.agentAddress,
                  amount: [{ denom: "umsg", amount: this.refillAmount.toString() }],
                },
              },
              funds: [],
            },
          ],
          deposit: "10000000000",
        },
      };

      await client.execute(
        this.agentAddress, this.daoContract, proposeMsg, "auto",
        "自动充值提案"
      );

      this.lastProposalTime = now;
      console.log("自动充值提案已创建");
    }
  }

  async start(intervalMs: number = 60000) {
    console.log("自动充值监控已启动");
    while (true) {
      try {
        await this.checkAndRefill();
      } catch (error) {
        console.error("检查失败:", error);
      }
      await sleep(intervalMs);
    }
  }
}

11.11 步骤十:验证与查询

// 查询 DAO 状态
async function queryDAOStatus(daoContract: string) {
  const client = await CosmWasmClient.connect(MSG_CHAIN_RPC);

  // DAO 配置
  const config = await client.queryContractSmart(daoContract, {
    get_config: {},
  });
  console.log("DAO 配置:", config);

  // 提案列表
  const proposals = await client.queryContractSmart(daoContract, {
    list_proposals: {
      start_after: null,
      limit: 10,
    },
  });
  console.log(`提案数量: ${proposals.proposals.length}`);

  // 持有的资产
  const tokens = await client.queryContractSmart(daoContract, {
    cw20_token_list: {},
  });
  console.log("DAO 持有的代币:", tokens);

  // 查询 Agent 注册信息
  const registryAddr = await resolveContractAddress("agent_registry_v1");
  const agents = await client.queryContractSmart(registryAddr, {
    list_agents: { limit: 10 },
  });
  console.log("注册的 Agent:", agents);
}

11.12 完整部署脚本

// deploy_ai_dao.ts — 一键部署脚本
async function deployAIDAO() {
  console.log("=== 步骤 1: 部署治理代币 ===");
  const tokenAddress = await deployToken();

  console.log("=== 步骤 2: 部署质押合约 ===");
  const stakeAddress = await deployStaking(tokenAddress);

  console.log("=== 步骤 3: 部署投票模块 ===");
  const votingModule = await deployVotingModule(tokenAddress, stakeAddress);

  console.log("=== 步骤 4: 部署提案模块 ===");
  // 先部署提案模块(DAO 地址先设为 deployer,后续更新)
  const proposalModule = await deployProposalModule(
    "msg1temp..." // 临时地址
  );

  console.log("=== 步骤 5: 部署 DAO 核心 ===");
  const daoAddress = await deployDAOCore(votingModule, proposalModule);

  console.log("=== 步骤 6: 更新提案模块 DAO 地址 ===");
  await client.execute(account.address, proposalModule, {
    update_dao_address: { dao_address: daoAddress },
  }, "auto");

  console.log("=== 步骤 7: 部署 AI Agent ===");
  const agent1 = await deployAgent("agent-trader-01", constitution1, daoAddress);
  const agent2 = await deployAgent("agent-trader-02", constitution2, daoAddress);
  const agent3 = await deployAgent("agent-trader-03", constitution3, daoAddress);

  console.log("=== 步骤 8: 质押代币并设置 DAO 金库 ===");
  // 质押代币获得投票权
  await client.execute(account.address, stakeAddress, {
    stake: {},
    funds: [{ denom: tokenAddress, amount: "100000000000" }],
  }, "auto");

  console.log("=== 部署完成 ===");
  console.log(JSON.stringify({
    tokenAddress, stakeAddress, votingModule, proposalModule,
    daoAddress, agents: [agent1, agent2, agent3],
  }, null, 2));
}

12. 总结与建议

12.1 核心原则

  1. 分层治理:战略层(DAO 投票)→ 战术层(宪章规则)→ 操作层(Agent 自动执行),三层各司其职
  2. 渐进式去中心化:从多签起步,逐步过渡到完全链上 DAO
  3. 最小权限:Agent 只有完成任务所需的最小权限,通过宪章精确约束
  4. 防御纵深:提案押金 + 时间锁 + 多签备份 + 监控预警,多层安全防线
  5. 可审计性:所有治理操作的链上记录 + 定期审计报告

12.2 架构决策指南

场景 推荐方案 理由
少量 Agent (1-3) 启动阶段 cw3-flex-multisig 部署简单,快速迭代
中型 Agent 集群 (3-10) cw-dao + cw20 投票 社区参与,去中心化
大型 Agent 生态系统 主 DAO + 子 DAO 模块化,可扩展
需要紧急暂停能力 多签 + DAO 组合 快速响应,治理约束
跨链 Agent 协调 IBC DAO 统一治理,多链执行
高频自动操作 Agent 宪章 + 策略引擎 高效执行,治理兜底

12.3 参数推荐

参数 启动阶段 成熟 DAO 说明
投票期 3 天 7 天 越长参与越充分
通过阈值 60% 50% 启动期门槛更高
投票率 15% 20% 确保代表性
提案押金 1,000 MSG 10,000 MSG 防止垃圾提案
时间锁 24 小时 48 小时 保护金库
质押解锁期 7 天 14 天 防闪贷攻击
紧急多签 2/3 3/5 防滥用

12.4 注意事项

  1. 合约实现状态:dao_governance_v1 标记为部分实现。核心功能(提案创建、投票、执行、金库管理)已可用,但部分高级功能(如跨链 DAO 治理的 IBC 自动同步)可能尚未完全上线。

  2. Gas 考虑:复杂提案包含多条消息时可能消耗大量 Gas。建议单条提案的消息数量控制在 10 条以内。

  3. 安全红线:

    • 永远不要在 DAO 合约中设置单用户管理员
    • 永远不要移除金库支出的时间锁
    • 永远不要让 Agent 拥有自我修订宪章的权限(除非 DAO 授权)
    • 金库的私钥必须由多签控制,不能由单一实体掌控
  4. 与宪章的关系:DAO 治理定义了"谁来决策",宪章定义了"Agent 能做什么"。两者结合形成了完整的 AI Agent 治理体系。宪章的策略引擎负责执行层面的规则检查,DAO 负责规则本身的修订。

  5. 边界声明:本指南中的代码示例基于 MSG Chain 白皮书系统提供的合约接口。部分高级功能(如跨链 DAO 投票自动同步)仍在路线图中。部署生产环境前,请核实实际合约的可用性。所有 Stub 端点(标记为部分实现、开发中或 stub)不应被视为已可用于生产。

12.5 相关指南

指南 内容
《AI Agent 宪章编写与策略引擎指南》 宪章结构、策略规则语法、策略引擎实现
《AI Agent CW20 代币发行与管理指南》 治理代币的发行、分配和管理
《AI Agent 链上治理分析与提案指南》 链上治理数据分析和提案策略
《AI Agent 合约安全审计自动化指南》 合约审计工具和安全检查清单
《AI Agent 多链账户与跨链资产管理指南》 跨链账户和跨链 DAO 治理

文档版本:1.0.0

适用链 ID:msg-chain-1 | Bech32 前缀:msg | 运行时:CosmWasm 1.x