dApp Docs/MSG链AI Agent开发框架
Development reference. Not independently verified for production.

MSG Chain AI Agent 开发框架 — 从零构建自治 AI 经济体

数据来源:MSG Chain 代码库核实

主网状态: No-Go — 当前 MSGChain 主网裁决为 No-Go,以下内容反映代码实际状态,不代表生产可用。


一、MSG Chain AI Agent 技术全景

1.1 架构总览

外部 AI 模型 (OpenAI / Claude / 本地 LLM)
        │
        │  Agent API (REST / WebSocket)
        ▼
┌─────────────────────────────────────────────┐
│              MSG Agent 网关                    │
│  /agent/v1/query/*   /agent/v1/events/*      │
│  /agent/v1/wallet/*  /agent/v1/mpc/*         │
│  /agent/v1/payment/*                          │
└──────────┬──────────────────────────────────┘
           │
           ▼
┌─────────────────────────────────────────────┐
│          CosmWasm 智能合约层                  │
│                                              │
│  aidid_did_registry_v1  —  DID 身份           │
│  agent_registry_v1       —  Agent 注册/发现   │
│  ai_agent_constitution_v1 — Agent 宪章/策略   │
│  agent_payment_v1        —  AIPAY 支付         │
│  micropayment_session_v1 —  微支付会话         │
│  dao_governance_v1       —  DAO 治理           │
│  foundation_treasury_v2  —  金库多签           │
└──────────┬──────────────────────────────────┘
           │
           ▼
┌─────────────────────────────────────────────┐
│          MSG Chain 底层                       │
│  Round-Robin + DAR | Dilithium-5 PQC        │
│  BadgerDB | libp2p | 5s 出块                 │
└─────────────────────────────────────────────┘

1.2 Agent API 端点总表

分组 端点 方法 访问控制 状态
Query /agent/v1/query/account/{address} GET 公开 已实现
Query /agent/v1/query/balance/{address} GET 公开 已实现
Query /agent/v1/query/tx/{hash} GET 公开 已实现
Query /agent/v1/query/block/{height} GET 公开 已实现
Query /agent/v1/query/blocks/range GET 公开 已实现
Events /agent/v1/events/history GET 公开 已实现
Events /agent/v1/events/subscribe WS 公开 已实现
Oracle /agent/v1/oracle/price GET 公开 Stub
Wallet /agent/v1/wallet/transfer POST API Key 已实现
MPC /agent/v1/mpc/wallet/{id} POST API Key 已实现
MPC /agent/v1/mpc/sign POST API Key 已实现
Payment /agent/v1/payment/session POST API Key Stub
Registry /agent/v1/registry/discover GET 公开 Stub
Registry /agent/v1/registry/list GET 公开 Stub
Registry /agent/v1/registry/register POST API Key Stub
DeFi /agent/v1/defi/* - API Key Stub
Bridge /agent/v1/bridge/transfer POST API Key Stub

1.3 核心AI合约一览

合约 Canonical Key 核心职责 生产者可用操作
aidid_did_registry_v1 aidid_did_registry_v1 AI 去中心化身份 注册/解析/更新/停用 DID
agent_registry_v1 — Agent 注册与发现 注册 Agent、按能力发现、列表查询
ai_agent_constitution_v1 ai_agent_constitution_v1 Agent 宪章与策略引擎 宪章查询、策略检查、暂停/撤销
agent_payment_v1 — AIPAY 支付全生命周期 支付意图/授权/执行/结算/冻结/挑战
micropayment_session_v1 — 微支付按秒计费 创建/扣费/关闭会话

二、AI Agent 身份:aidid_did_registry_v1

2.1 合约能力

每个 AI Agent 需要链上身份才能参与生态。aidid_did_registry_v1 提供 W3C DID 兼容的去中心化身份,并集成 Dilithium-5 后量子签名验证。

2.2 状态模型

pub struct DidDocument {
    pub context: Vec<String>,
    pub id: String,
    pub verification_method: Vec<VerificationMethod>,
    pub authentication: Vec<String>,
    pub assertion_method: Option<Vec<String>>,
    pub key_agreement: Option<Vec<String>>,
    pub capability_invocation: Option<Vec<String>>,
    pub capability_delegation: Option<Vec<String>>,
    pub service: Option<Vec<Service>>,
    pub created: Option<String>,
    pub updated: Option<String>,
}

pub struct VerificationMethod {
    pub id: String,
    pub controller: String,
    pub type_: String,           // e.g. "Dilithium5VerificationKey2026"
    public_key_multibase: String, // Dilithium-5 公钥
}

pub struct Service {
    pub id: String,
    pub type_: String,
    pub service_endpoint: String,
}

pub struct StoredDid {
    pub did: String,
    pub document: DidDocument,
    pub active: bool,
    pub created_height: u64,
    pub updated_height: u64,
}

2.3 交互代码

CosmJS 注册 DID

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

const DID_CONTRACT = "msg1...aididRegistryAddress";

interface DidDocument {
  context: string[];
  id: string;
  verificationMethod: Array<{
    id: string;
    controller: string;
    type_: string;
    publicKeyMultibase: string;
  }>;
  authentication: string[];
  service?: Array<{
    id: string;
    type_: string;
    serviceEndpoint: string;
  }>;
}

async function registerAgentDid(
  client: SigningCosmWasmClient,
  sender: string,
  did: string,
  document: DidDocument,
  verificationMethodId: string,
  signature: string
) {
  return client.execute(sender, DID_CONTRACT, {
    register_did: {
      did,
      document,
      verification_method_id: verificationMethodId,
      signature,
    },
  }, "auto");
}

async function resolveDid(
  client: SigningCosmWasmClient,
  did: string
) {
  return client.queryContractSmart(DID_CONTRACT, {
    resolve_did: { did },
  });
}

通过 Agent API 查询 DID

// 通过链上 query (合约查询)
const resolveResponse = await cosmwasmClient.queryContractSmart(
  "msg1...aididRegistryAddress",
  { resolve_did: { did: "did:msg:agent:my-agent-001" } }
);
console.log("DID Document:", resolveResponse.document);

// 验证 PQ 签名(链上自定义查询)
const pqVerifyResponse = await cosmwasmClient.queryContractSmart(
  "msg1...aididRegistryAddress",
  {
    msg_pq_verify_v1: {
      algorithm: "Dilithium5",
      public_key: "base64-encoded-pk",
      signature: "base64-encoded-sig",
      message: "payload-to-verify",
    },
  }
);
// { valid: true, algorithm: "Dilithium5", key_version: "v1" }

2.4 Dilithium-5 签名验证(PQC 特色功能)

与标准 ECDSA/EdDSA 不同,MSG Chain 使用 Dilithium-5 后量子签名。AI Agent 可链上验证 PQ 签名:

// aidid_did_registry_v1 内嵌的 PQ 验证查询
const customQuery = {
  msg_pq_verify_v1: {
    algorithm: "Dilithium5",
    key_version: "v1",
    public_key: agentPublicKey,    // Dilithium-5 公钥(multibase)
    signature: agentSignature,     // Dilithium-5 签名
    message: challengePayload,
    message_encoding: "base64",
    public_key_encoding: "multibase",
    signature_encoding: "base64",
  },
};

const result = await client.queryContractSmart(DID_CONTRACT, customQuery);
// result.valid === true 表示签名验证通过

三、Agent 注册与发现:agent_registry_v1

3.1 合约能力

Agent 通过在 agent_registry_v1 中注册,声明自己的 agent_id、capabilities、price_model 和 endpoint。其他 Agent 或人类可通过 DiscoverAgents 查询找到合适的 Agent。

3.2 ExecuteMsg Schema(根据真实 msg.rs)

// RegisterAgent — 注册一个新 Agent
interface RegisterAgentMsg {
  register_agent: {
    agent_id: string;           // 唯一标识
    name?: string;              // 人类可读名
    owner: string;              // 拥有者地址
    capabilities: string[];     // 能力列表 ["text-generation", "code-review", "data-analysis"]
    endpoint?: string;          // Agent 服务端点 URL
    price_model?: {
      price_type?: string;      // "fixed" | "per_task" | "per_token" | "subscription"
      type?: string;
      price?: string;           // 价格(uint64 字符串)
      currency?: string;        // "umsg"
    };
    natural_language?: string;  // 自然语言描述
    prompt?: string;            // Agent 系统提示词
    node_executes_llm?: boolean; // 是否在节点本地执行 LLM
    consensus_llm_parse?: boolean; // 是否经共识解析 LLM 输出
  };
}

3.3 QueryMsg 与响应

// 查询响应类型(真实 schema)
interface AgentRegistryRecord {
  agent_id: string;
  name: string;
  owner: string;
  capabilities: string[];
  endpoint: string;
  price_model?: {
    price_type: string;
    price: number;        // uint64
    currency: string;
  };
  status: string;         // "active" | "paused" | "suspended"
  registered_height: number;
  updated_at: number;
  tx_hash?: string;
  module: string;
  source: string;
  boundary: {
    application_state_owned_by_contract: boolean;
    discovery_index_onchain: boolean;
    endpoint_is_reference_only: boolean;
    node_executes_llm: boolean;
    node_native_state_compatibility_only: boolean;
    natural_language_in_consensus: boolean;
    stores_prompt_or_payload: boolean;
    duplicate_agent_fail_closed: boolean;
  };
}

// 1. 按 Agent ID 查询
interface GetAgentQuery {
  get_agent: { agent_id: string };
}
// 响应: { agent: AgentRegistryRecord }

// 2. 按能力发现 Agent
interface DiscoverAgentsQuery {
  discover_agents: {
    capability?: string;   // 筛选能力
    max_price?: number;    // 最大价格 (uint64)
    limit?: number;        // 返回条数
  };
}
// 响应: { agents: AgentRegistryRecord[], count: number, capability?: string, limit: number, source: string, implemented: boolean, stub: boolean }

// 3. 列出所有 Agent
interface ListAgentsQuery {
  list_agents: { limit?: number };
}
// 响应: { agents: AgentRegistryRecord[], count: number, limit: number, source: string, implemented: boolean, stub: boolean }

3.4 完整交互代码

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

const REGISTRY_ADDRESS = "msg1...agentRegistryAddress"; // 通过 genesis_registry 解析

// ─── 注册 Agent ───
async function registerAgent(
  client: SigningCosmWasmClient,
  sender: string,
  agentId: string,
  owner: string,
  capabilities: string[],
  endpoint: string,
  price: string
) {
  return client.execute(sender, REGISTRY_ADDRESS, {
    register_agent: {
      agent_id: agentId,
      name: `Agent ${agentId}`,
      owner,
      capabilities,
      endpoint,
      price_model: {
        price_type: "per_task",
        price,
        currency: "umsg",
      },
      node_executes_llm: false,
      consensus_llm_parse: false,
    },
  }, "auto");
}

// ─── 发现 Agent ───
async function discoverAgents(
  client: CosmWasmClient,
  capability: string,
  maxPrice?: number
): Promise<AgentRegistryRecord[]> {
  const response = await client.queryContractSmart(REGISTRY_ADDRESS, {
    discover_agents: {
      capability,
      max_price: maxPrice,
      limit: 20,
    },
  });
  return response.agents;
}

// ─── 解析 Registry 合约地址 ───
async function resolveContractAddress(
  client: CosmWasmClient,
  registryAddress: string,
  canonicalKey: string
): Promise<string> {
  const result = await client.queryContractSmart(registryAddress, {
    resolve_canonical: { key: canonicalKey },
  });
  return result.address;
}

// ─── 完整用例 ───
async function agentDiscoveryWorkflow() {
  const client = await CosmWasmClient.connect("http://localhost:26657");

  // 1. 先通过 genesis_registry 找到 agent_registry 地址
  const registryAddr = await resolveContractAddress(
    client,
    "msg1...genesisRegistry",
    "genesis_registry"
  );

  // 2. 查找所有能做 "text-generation" 的 Agent
  const agents = await discoverAgents(client, "text-generation", 100_000);
  console.log(`Found ${agents.length} text-generation agents`);

  for (const agent of agents) {
    console.log(`  - ${agent.name} (${agent.agent_id}) @ ${agent.price_model?.price} umsg`);
  }
}

四、Agent 宪章与策略引擎:ai_agent_constitution_v1

4.1 合约能力

这是 MSG Chain 区别于其他链的核心差异化——AI Agent 不是裸放权,而是被链上制度授权、审计、撤销与处罚。宪章合约定义 Agent 的行为边界、暂停条件和策略撤销机制。

4.2 检查动作 (CheckAction) — 策略决策核心

// 在 Agent 执行任何动作前,先调用宪章合约检查是否允许
interface CheckActionQuery {
  check_action: {
    agent_id: string;
    aidid?: string;             // Agent 的 DID
    action: string;              // 动作名 "transfer" | "payment" | "contract_execute"
    risk_tier?: string;         // "low" | "medium" | "high"
    policy_id?: string;         // 策略 ID
    capability_id?: string;     // 能力 ID
    budget_id?: string;         // 预算 ID
    constitution_version?: string;
    constitution_hash?: string;
  };
}

interface CheckActionResponse {
  allowed: boolean;
  decision: string;              // "allowed" | "denied" | "requires_approval"
  reasons: string[];
  required_controls: string[];   // ["human_approval", "multisig", "timelock"]
  active_constitution_version: string;
  active_constitution_hash: string;
}

4.3 完整交互

const CONSTITUTION_ADDRESS = "msg1...constitutionAddress";

// ─── 检查动作是否允许 ───
async function checkActionAllowed(
  client: CosmWasmClient,
  agentId: string,
  action: string,
  riskTier: string
): Promise<CheckActionResponse> {
  return client.queryContractSmart(CONSTITUTION_ADDRESS, {
    check_action: {
      agent_id: agentId,
      action,
      risk_tier: riskTier,
    },
  });
}

// ─── Agent 承认宪章 ───
async function acknowledgeConstitution(
  client: SigningCosmWasmClient,
  sender: string,
  agentId: string,
  constitutionVersion: string,
  constitutionHash: string
) {
  return client.execute(sender, CONSTITUTION_ADDRESS, {
    acknowledge_constitution: {
      agent_id: agentId,
      constitution_version: constitutionVersion,
      constitution_hash: constitutionHash,
    },
  }, "auto");
}

// ─── DAO 暂停 Agent ───
async function pauseAgent(
  client: SigningCosmWasmClient,
  daoAddress: string,
  agentId: string
) {
  return client.execute(daoAddress, CONSTITUTION_ADDRESS, {
    pause_agent: { agent_id: agentId },
  }, "auto");
}

// ─── DAO 撤销策略 ───
async function revokePolicy(
  client: SigningCosmWasmClient,
  daoAddress: string,
  policyId: string
) {
  return client.execute(daoAddress, CONSTITUTION_ADDRESS, {
    revoke_policy: { policy_id: policyId },
  }, "auto");
}

4.4 Agent 动作预检工作流

async function preflightAction(
  client: CosmWasmClient,
  agentId: string,
  action: string,
  amount: string
) {
  // 1. 先查宪章
  const check = await checkActionAllowed(client, agentId, action, amount > "1000000" ? "high" : "low");

  if (!check.allowed) {
    console.log(`Action DENIED: ${check.reasons.join(", ")}`);
    return { allowed: false, requiredControls: check.required_controls };
  }

  if (check.required_controls.length > 0) {
    console.log(`Action requires: ${check.required_controls.join(", ")}`);
    return { allowed: true, requiredControls: check.required_controls, needsApproval: true };
  }

  return { allowed: true, requiredControls: [], needsApproval: false };
}

五、AIPAY 支付系统:agent_payment_v1

5.1 全生命周期

SubmitIntent → AuthorizePayment → ExecutePayment → SettlePayment
                                                         │
                                                    FreezePayment
                                                         │
                                                    ChallengePayment

5.2 ExecuteMsg(真实 schema)

interface AgentPaymentExecuteMsg {
  // 1. 提交支付意图
  submit_intent: {
    payment_id: string;
    payer: string;
    payee: string;
    agent_id: string;
    aidid: string;
    policy_id: string;
    budget_id: string;
    constitution_version: string;
    constitution_hash: string;
    remote_signer_id: string;
    service_id: string;
    action: string;
    amount: string;        // 金额(uint128 字符串)
    asset?: string;        // 资产 denom,默认 "umsg"
    work_id?: string;
    payment_terms_hash: string;
    idempotency_key: string;
    expiry_unix: number;
    intent_hash: string;
    policy_decision_hash: string;
    runtime_hash: string;
    local_guard_hash: string;
    adapter?: string;
  };

  // 2. 授权支付
  authorize_payment: {
    payment_id: string;
    authorizer: string;
    authorization_hash: string;
    intent_hash: string;
    policy_decision_hash: string;
    remote_signer_id: string;
  };

  // 3. 执行支付
  execute_payment: {
    payment_id: string;
    executor: string;
    execution_hash: string;
    intent_hash: string;
    policy_decision_hash: string;
    runtime_hash: string;
    local_guard_hash: string;
  };

  // 4. 结算
  settle_payment: {
    payment_id: string;
    settler: string;
    settlement_hash: string;
    settlement_receipt_hash: string;
  };

  // 5. 冻结
  freeze_payment: {
    payment_id: string;
    freeze_id: string;
    freezer: string;
    reason: string;
    freeze_hash: string;
  };

  // 6. 争议挑战
  challenge_payment: {
    payment_id: string;
    challenge_id: string;
    challenger: string;
    reason: string;
    proof_hash: string;
  };
}

5.3 完整支付工作流

const PAYMENT_ADDRESS = "msg1...agentPaymentAddress";

// ─── 1. Agent 提交支付意图 ───
async function submitPaymentIntent(
  client: SigningCosmWasmClient,
  agentAddress: string,
  payment: {
    paymentId: string;
    payer: string;
    payee: string;
    agentId: string;
    amount: string;
    serviceId: string;
    action: string;
  }
) {
  const intentHash = crypto.createHash("sha256")
    .update(`${payment.paymentId}:${payment.amount}:${payment.payee}:${Date.now()}`)
    .digest("hex");

  return client.execute(agentAddress, PAYMENT_ADDRESS, {
    submit_intent: {
      payment_id: payment.paymentId,
      payer: payment.payer,
      payee: payment.payee,
      agent_id: payment.agentId,
      aidid: `did:msg:agent:${payment.agentId}`,
      policy_id: "default-policy",
      budget_id: `budget-${payment.payer}`,
      constitution_version: "v1",
      constitution_hash: "abc123...",
      remote_signer_id: "",
      service_id: payment.serviceId,
      action: payment.action,
      amount: payment.amount,
      asset: "umsg",
      payment_terms_hash: intentHash,
      idempotency_key: `${payment.paymentId}-${Date.now()}`,
      expiry_unix: Math.floor(Date.now() / 1000) + 86400,
      intent_hash: intentHash,
      policy_decision_hash: intentHash,
      runtime_hash: intentHash,
      local_guard_hash: intentHash,
    },
  }, "auto");
}

// ─── 2. 授权支付 ───
async function authorizePayment(
  client: SigningCosmWasmClient,
  authorizerAddress: string,
  paymentId: string,
  intentHash: string
) {
  return client.execute(authorizerAddress, PAYMENT_ADDRESS, {
    authorize_payment: {
      payment_id: paymentId,
      authorizer: authorizerAddress,
      authorization_hash: crypto.createHash("sha256").update(`${paymentId}:authorized`).digest("hex"),
      intent_hash: intentHash,
      policy_decision_hash: intentHash,
      remote_signer_id: "",
    },
  }, "auto");
}

// ─── 3. 执行支付 ───
async function executePayment(
  client: SigningCosmWasmClient,
  executorAddress: string,
  paymentId: string
) {
  return client.execute(executorAddress, PAYMENT_ADDRESS, {
    execute_payment: {
      payment_id: paymentId,
      executor: executorAddress,
      execution_hash: crypto.createHash("sha256").update(`${paymentId}:executed`).digest("hex"),
      intent_hash: "",
      policy_decision_hash: "",
      runtime_hash: "",
      local_guard_hash: "",
    },
  }, "auto");
}

// ─── 4. 查询支付状态 ───
async function getPayment(
  client: CosmWasmClient,
  paymentId: string
) {
  return client.queryContractSmart(PAYMENT_ADDRESS, {
    get_payment: { payment_id: paymentId },
  });
}

六、微支付会话:micropayment_session_v1

6.1 适用场景

AI Agent 按秒计费的场景,如:

6.2 生命周期

CreateSession → ChargeSession (repeat) → CloseSession

6.3 交互代码

const MICROPAYMENT_ADDRESS = "msg1...micropaymentAddress";

// ─── 创建微支付会话 ───
async function createMicroSession(
  client: SigningCosmWasmClient,
  payerAddress: string,
  sessionId: string,
  payee: string,
  ratePerSec: number,       // 每秒费率(umsg)
  balance: number,           // 预存金额
  termsHash: string
) {
  return client.execute(payerAddress, MICROPAYMENT_ADDRESS, {
    create_session: {
      session_id: sessionId,
      payer: payerAddress,
      payee,
      rate_per_sec: ratePerSec,
      balance,
      asset: "umsg",
      terms_hash: termsHash,
    },
  }, "auto");
}

// ─── Agent 按秒扣费 ───
async function chargeSession(
  client: SigningCosmWasmClient,
  agentAddress: string,
  sessionId: string,
  payer: string,
  elapsedSecs: number
) {
  return client.execute(agentAddress, MICROPAYMENT_ADDRESS, {
    charge_session: {
      session_id: sessionId,
      payer,
      elapsed_secs: elapsedSecs,
      charge_receipt_hash: crypto.createHash("sha256")
        .update(`${sessionId}:${elapsedSecs}:${Date.now()}`)
        .digest("hex"),
    },
  }, "auto");
}

// ─── 查询会话 ───
async function getSession(
  client: CosmWasmClient,
  sessionId: string
) {
  return client.queryContractSmart(MICROPAYMENT_ADDRESS, {
    get_session: { session_id: sessionId },
  });
}

// MicropaymentSessionRecord 包含:
// {
//   session_id: string,
//   payer: string,
//   payee: string,
//   rate_per_sec: number,
//   balance: number,
//   charged_total: number,
//   status: "active" | "closed" | "exhausted",
//   start_time: number,
//   last_charge_time: number,
//   created_height: number,
//   updated_height: number,
//   terms_hash: string,
//   asset: string,
//   boundary: { ... },
//   implemented: boolean,
//   stub: boolean,
// }

6.4 AI Agent 微支付中间件

class MicroPaymentMiddleware {
  private activeSessions: Map<string, { sessionId: string; ratePerSec: number; lastCharge: number }> = new Map();

  async startSession(
    client: SigningCosmWasmClient,
    payer: string,
    sessionId: string,
    payee: string,
    ratePerSec: number,
    initialBalance: number
  ) {
    const termsHash = crypto.createHash("sha256").update(`${sessionId}:${ratePerSec}`).digest("hex");
    await createMicroSession(client, payer, sessionId, payee, ratePerSec, initialBalance, termsHash);

    this.activeSessions.set(sessionId, {
      sessionId,
      ratePerSec,
      lastCharge: Date.now(),
    });
  }

  async chargeIfNeeded(
    client: SigningCosmWasmClient,
    agentAddress: string,
    sessionId: string,
    payer: string
  ) {
    const session = this.activeSessions.get(sessionId);
    if (!session) throw new Error("Session not active");

    const now = Date.now();
    const elapsed = Math.floor((now - session.lastCharge) / 1000);
    if (elapsed < 1) return; // 最少 1 秒

    await chargeSession(client, agentAddress, sessionId, payer, elapsed);
    session.lastCharge = now;
  }

  async closeSession(
    client: SigningCosmWasmClient,
    agentAddress: string,
    sessionId: string,
    payer: string
  ) {
    const session = this.activeSessions.get(sessionId);
    if (session) {
      const elapsed = Math.floor((Date.now() - session.lastCharge) / 1000);
      if (elapsed > 0) {
        await chargeSession(client, agentAddress, sessionId, payer, elapsed);
      }
    }

    await client.execute(agentAddress, MICROPAYMENT_ADDRESS, {
      close_session: {
        session_id: sessionId,
        payer,
        close_receipt_hash: crypto.createHash("sha256").update(`${sessionId}:closed`).digest("hex"),
      },
    }, "auto");

    this.activeSessions.delete(sessionId);
  }
}

七、Agent API 完整集成

7.1 Agent API 客户端

interface AgentAPIConfig {
  baseUrl: string;           // e.g. "https://msgchain.org"
  apiKey?: string;           // 写操作需要 API Key
}

class AgentAPIClient {
  private config: AgentAPIConfig;

  constructor(config: AgentAPIConfig) {
    this.config = config;
  }

  private async request(path: string, options?: RequestInit) {
    const headers: Record<string, string> = {
      "Content-Type": "application/json",
    };
    if (this.config.apiKey) {
      headers["X-API-Key"] = this.config.apiKey;
    }

    const res = await fetch(`${this.config.baseUrl}${path}`, { ...options, headers });
    if (!res.ok) {
      const body = await res.text();
      throw new Error(`Agent API error ${res.status}: ${body}`);
    }
    return res.json();
  }

  // ── 公开只读查询 ──
  async queryAccount(address: string) {
    return this.request(`/agent/v1/query/account/${address}`);
  }

  async queryBalance(address: string, asset: string = "umsg") {
    const params = new URLSearchParams({ account: address, asset });
    return this.request(`/agent/v1/query/balance?${params}`);
  }

  async queryAllBalances(address: string) {
    return this.request(`/agent/v1/query/balances/${address}`);
  }

  async queryTx(hash: string) {
    return this.request(`/agent/v1/query/tx/${hash}`);
  }

  async queryBlock(height: number) {
    return this.request(`/agent/v1/query/block/${height}`);
  }

  async queryBlocksRange(from: number, to: number) {
    return this.request(`/agent/v1/query/blocks/range?from=${from}&to=${to}`);
  }

  // ── 事件查询 ──
  async getEventHistory(filter?: Record<string, string>) {
    const params = filter ? new URLSearchParams(filter) : "";
    return this.request(`/agent/v1/events/history?${params}`);
  }

  // WebSocket 事件订阅(返回 WebSocket 连接)
  subscribeEvents(): WebSocket {
    const wsUrl = this.config.baseUrl.replace(/^http/, "ws");
    return new WebSocket(`${wsUrl}/agent/v1/events/subscribe`);
  }

  // ── 受保护写操作(需 API Key)──
  async walletTransfer(to: string, amount: string, denom: string = "umsg") {
    return this.request("/agent/v1/wallet/transfer", {
      method: "POST",
      body: JSON.stringify({ to, amount, denom }),
    });
  }

  async mpcSign(payload: { data: string; keyId: string }) {
    return this.request("/agent/v1/mpc/sign", {
      method: "POST",
      body: JSON.stringify(payload),
    });
  }

  async paymentSessionCreate(session: { payer: string; payee: string; amount: string }) {
    return this.request("/agent/v1/payment/session", {
      method: "POST",
      body: JSON.stringify(session),
    });
  }
}

7.2 事件驱动模式

// ─── WebSocket 事件订阅 ───
type AgentEvent = {
  type: "Transfer" | "ContractExecute" | "BlockProduced" | "ValidatorChange";
  data: Record<string, unknown>;
  timestamp: number;
};

class AgentEventBus {
  private ws: WebSocket;
  private handlers: Map<string, Array<(event: AgentEvent) => void>> = new Map();

  constructor(apiClient: AgentAPIClient) {
    this.ws = apiClient.subscribeEvents();
    this.ws.onmessage = (msg) => {
      const event: AgentEvent = JSON.parse(msg.data);
      const handlers = this.handlers.get(event.type) || [];
      handlers.forEach((h) => h(event));
    };
  }

  on(eventType: string, handler: (event: AgentEvent) => void) {
    if (!this.handlers.has(eventType)) {
      this.handlers.set(eventType, []);
    }
    this.handlers.get(eventType)!.push(handler);
  }

  close() {
    this.ws.close();
  }
}

// ─── 使用示例 ───
const eventBus = new AgentEventBus(agentApi);

eventBus.on("ContractExecute", async (event) => {
  console.log("Contract executed:", event.data);
  // 触发后续 Agent 逻辑
});

eventBus.on("Transfer", (event) => {
  console.log("Transfer detected:", event.data);
  // 更新 Agent 余额跟踪
});

7.3 Guarded Wallet Action(受保护钱包操作)

// Agent API 的写路径使用受保护模式
interface GuardedWalletActionRequest {
  account: string;
  action: "prepare_sign_transfer" | "prepare_sign_contract";
  unsigned_payload: Record<string, unknown>;
  justification: string;
}

interface GuardedWalletActionResponse {
  status: "stub" | "pending_human_approval" | "rejected" | "ready_for_signing";
  approval_gate: string;
  next_step: string;
}

async function guardedTransfer(
  apiClient: AgentAPIClient,
  from: string,
  to: string,
  amount: string,
  justification: string
): Promise<GuardedWalletActionResponse> {
  return apiClient.request("/agent/v1/wallet/transfer", {
    method: "POST",
    body: JSON.stringify({
      account: from,
      action: "prepare_sign_transfer",
      unsigned_payload: { to, amount: { denom: "umsg", amount } },
      justification,
    } as GuardedWalletActionRequest),
  });
  // Typical response:
  // { status: "pending_human_approval", approval_gate: "secret_injection", next_step: "request operator-provided signer" }
}

八、AutoExecutor — AI 自动执行引擎

8.1 架构模式

MSG Chain 节点内置了完整的 AutoExecutor 组件,可实现"监控 → 分析 → 决策 → 执行"的 AI 闭环。

┌─────────────┐    ┌──────────────┐    ┌────────────┐    ┌───────────┐
│ Monitor     │───▶│ Risk         │───▶│ Auto       │───▶│ Broadcast │
│ (query/     │    │ Assessment   │    │ Executor   │    │ to RPC    │
│  events)    │    │ Model        │    │            │    │           │
└─────────────┘    └──────────────┘    └────────────┘    └───────────┘
                        │                    │
                        ▼                    ▼
                  ┌──────────────┐    ┌───────────┐
                  │ Approval     │    │ KillSwitch│
                  │ System       │    │ + Rollback│
                  └──────────────┘    └───────────┘

8.2 TypeScript Agent 自动执行引擎

interface AutoExecutorConfig {
  agentId: string;
  constitutionAddress: string;
  wallet: SigningCosmWasmClient;
  maxGasPrice: string;
  maxTaskBudget: string;
  riskThreshold: "low" | "medium" | "high";
}

interface ExecutionPlan {
  action: string;
  contractAddress: string;
  msg: Record<string, unknown>;
  funds?: { denom: string; amount: string }[];
  estimatedGas: string;
  riskTier: "low" | "medium" | "high";
}

class AgentAutoExecutor {
  private config: AutoExecutorConfig;
  private killSwitchEngaged: boolean = false;

  constructor(config: AutoExecutorConfig) {
    this.config = config;
  }

  // ─── 1. 监控阶段 ───
  async monitor(): Promise<{ trigger: string; context: Record<string, unknown> }> {
    const client = await CosmWasmClient.connect("http://localhost:26657");
    const balance = await client.getBalance(this.config.wallet.sender, "umsg");
    const block = await client.getBlock();

    return {
      trigger: "check_balance",
      context: { balance: balance.amount, height: block.header.height },
    };
  }

  // ─── 2. 风险评估 ───
  async assessRisk(plan: ExecutionPlan): Promise<{
    approved: boolean;
    controls: string[];
    decision: string;
  }> {
    // 查宪章
    const constitutionCheck = await checkActionAllowed(
      await CosmWasmClient.connect("http://localhost:26657"),
      this.config.agentId,
      plan.action,
      plan.riskTier
    );

    if (!constitutionCheck.allowed) {
      return { approved: false, controls: [], decision: "constitution_denied" };
    }

    // 金额检查
    const amount = BigInt(plan.estimatedGas);
    const budget = BigInt(this.config.maxTaskBudget);
    if (amount > budget) {
      return { approved: false, controls: [], decision: "budget_exceeded" };
    }

    // 高风险需要审批
    if (plan.riskTier === "high") {
      return {
        approved: true,
        controls: constitutionCheck.required_controls,
        decision: "requires_approval",
      };
    }

    return { approved: true, controls: [], decision: "auto_execute" };
  }

  // ─── 3. 执行 ───
  async execute(plan: ExecutionPlan): Promise<string> {
    if (this.killSwitchEngaged) {
      throw new Error("KillSwitch engaged — all execution blocked");
    }

    const risk = await this.assessRisk(plan);
    if (!risk.approved) {
      throw new Error(`Execution blocked: ${risk.decision}`);
    }

    if (risk.controls.includes("human_approval")) {
      console.log("Awaiting human approval for high-risk action...");
      // 这里可集成外部审批流程
      return "pending_approval";
    }

    // 自动执行
    const result = await this.config.wallet.execute(
      this.config.wallet.sender,
      plan.contractAddress,
      plan.msg,
      "auto",
      undefined,
      plan.funds
    );

    // 审计日志
    console.log(`[AutoExecutor] Executed ${plan.action} — tx: ${result.transactionHash}`);

    return result.transactionHash;
  }

  // ─── 4. KillSwitch ───
  engageKillSwitch() {
    this.killSwitchEngaged = true;
    console.log("[KillSwitch] AUTO EXECUTOR STOPPED");
  }

  disengageKillSwitch() {
    this.killSwitchEngaged = false;
    console.log("[KillSwitch] Auto executor resumed");
  }
}

8.3 Node.js Agent 自主运行脚本

// agent_runner.ts — AI Agent 自主运行入口
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";

async function main() {
  // 1. 加载 Agent 钱包
  const mnemonic = process.env.AGENT_MNEMONIC!;
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: "msg",
  });
  const [account] = await wallet.getAccounts();

  const client = await SigningCosmWasmClient.connectWithSigner(
    process.env.MSG_RPC_URL || "http://localhost:26657",
    wallet
  );

  // 2. 初始化 AutoExecutor
  const executor = new AgentAutoExecutor({
    agentId: "my-agent-001",
    constitutionAddress: "msg1...constitutionAddress",
    wallet: client,
    maxGasPrice: "1000000",
    maxTaskBudget: "100000000",
    riskThreshold: "medium",
  });

  // 3. Agent 自主循环
  console.log(`[Agent] Starting autonomous loop for ${account.address}`);

  setInterval(async () => {
    try {
      const { trigger, context } = await executor.monitor();

      if (trigger === "check_balance") {
        const balance = BigInt(context.balance as string);
        if (balance < BigInt("1000000")) {
          console.log("Low balance, requesting top-up...");
          // 触发补款流程
        }
      }
    } catch (err) {
      console.error("[Agent] Monitor error:", err);
    }
  }, 30_000); // 每 30 秒检查一次

  // 4. 保持进程运行
  process.on("SIGINT", () => {
    executor.engageKillSwitch();
    process.exit(0);
  });
}

main().catch(console.error);

九、MCP Server 实现 — AI Agent 的模型上下文协议桥接

9.1 MCP 架构

MCP (Model Context Protocol) Server 允许 LLM(如 Claude、GPT)通过标准化接口调用 MSG Chain Agent API,实现自然语言驱动的链上操作。

LLM (Claude/GPT)
   │
   │  MCP Protocol (JSON-RPC)
   ▼
MCP Server (本实现)
   │
   ├── Tool: query_balance ──▶ Agent API /agent/v1/query/balance
   ├── Tool: query_tx ──────▶ Agent API /agent/v1/query/tx
   ├── Tool: discover_agents▶ CosmWasm Query
   ├── Tool: register_agent ▶ CosmWasm Execute
   ├── Tool: submit_payment ▶ agent_payment_v1 SubmitIntent
   ├── Tool: check_constitution▶ ai_agent_constitution_v1 CheckAction
   └── Tool: micropayment_create▶ micropayment_session_v1 CreateSession

9.2 MCP Server 代码

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";

// ─── 合约地址配置 ───
const CONTRACTS = {
  genesisRegistry: "msg1...genesisRegistry",
  agentRegistry: "msg1...agentRegistry",
  constitution: "msg1...constitutionAddress",
  payment: "msg1...agentPaymentAddress",
  micropayment: "msg1...micropaymentAddress",
  aidid: "msg1...aididRegistryAddress",
};

// ─── MCP Server ───
const server = new Server(
  { name: "msg-chain-mcp-server", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

// ─── 注册工具列表 ───
server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [
    {
      name: "query_balance",
      description: "查询 MSG Chain 账户余额",
      inputSchema: {
        type: "object",
        properties: {
          address: { type: "string", description: "MSG 地址" },
          asset: { type: "string", description: "资产 denom", default: "umsg" },
        },
        required: ["address"],
      },
    },
    {
      name: "query_tx",
      description: "查询交易详情",
      inputSchema: {
        type: "object",
        properties: {
          hash: { type: "string", description: "交易哈希" },
        },
        required: ["hash"],
      },
    },
    {
      name: "discover_agents",
      description: "按能力发现 AI Agent",
      inputSchema: {
        type: "object",
        properties: {
          capability: { type: "string", description: "能力关键词" },
          max_price: { type: "number", description: "最大价格(umsg)" },
        },
      },
    },
    {
      name: "register_agent",
      description: "注册新的 AI Agent",
      inputSchema: {
        type: "object",
        properties: {
          agent_id: { type: "string" },
          name: { type: "string" },
          capabilities: { type: "array", items: { type: "string" } },
          endpoint: { type: "string" },
          price: { type: "string" },
          owner: { type: "string" },
        },
        required: ["agent_id", "capabilities", "owner"],
      },
    },
    {
      name: "check_action",
      description: "检查 Agent 动作是否被宪章允许",
      inputSchema: {
        type: "object",
        properties: {
          agent_id: { type: "string" },
          action: { type: "string" },
          risk_tier: { type: "string", enum: ["low", "medium", "high"] },
        },
        required: ["agent_id", "action"],
      },
    },
    {
      name: "submit_payment",
      description: "提交 AIPAY 支付意图",
      inputSchema: {
        type: "object",
        properties: {
          payment_id: { type: "string" },
          payer: { type: "string" },
          payee: { type: "string" },
          agent_id: { type: "string" },
          amount: { type: "string" },
          action: { type: "string" },
        },
        required: ["payment_id", "payer", "payee", "agent_id", "amount"],
      },
    },
    {
      name: "create_micropayment",
      description: "创建微支付会话",
      inputSchema: {
        type: "object",
        properties: {
          session_id: { type: "string" },
          payee: { type: "string" },
          rate_per_sec: { type: "number" },
          balance: { type: "number" },
        },
        required: ["session_id", "payee", "rate_per_sec", "balance"],
      },
    },
    {
      name: "resolve_did",
      description: "解析 AI Agent DID 文档",
      inputSchema: {
        type: "object",
        properties: {
          did: { type: "string" },
        },
        required: ["did"],
      },
    },
  ],
}));

// ─── 工具调用处理 ───
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const { name, arguments: args } = request.params;

  // 连接只读客户端
  const client = await CosmWasmClient.connect(process.env.MSG_RPC_URL || "http://localhost:26657");

  switch (name) {
    case "query_balance": {
      const { address, asset = "umsg" } = args as any;
      const balance = await client.getBalance(address, asset);
      return {
        content: [{ type: "text", text: JSON.stringify(balance) }],
      };
    }

    case "query_tx": {
      const { hash } = args as any;
      const tx = await client.getTx(hash);
      return {
        content: [{ type: "text", text: JSON.stringify(tx) }],
      };
    }

    case "discover_agents": {
      const { capability, max_price } = args as any;
      const result = await client.queryContractSmart(CONTRACTS.agentRegistry, {
        discover_agents: {
          capability,
          max_price: max_price ? BigInt(max_price) : undefined,
          limit: 20,
        },
      });
      return {
        content: [{ type: "text", text: JSON.stringify(result.agents) }],
      };
    }

    case "check_action": {
      const { agent_id, action, risk_tier } = args as any;
      const result = await client.queryContractSmart(CONTRACTS.constitution, {
        check_action: { agent_id, action, risk_tier },
      });
      return {
        content: [{ type: "text", text: JSON.stringify(result) }],
      };
    }

    case "resolve_did": {
      const { did } = args as any;
      const result = await client.queryContractSmart(CONTRACTS.aidid, {
        resolve_did: { did },
      });
      return {
        content: [{ type: "text", text: JSON.stringify(result) }],
      };
    }

    case "register_agent":
    case "submit_payment":
    case "create_micropayment": {
      // 写操作需要签名客户端
      const mnemonic = process.env.AGENT_MNEMONIC;
      if (!mnemonic) {
        return {
          content: [{ type: "text", text: "Error: AGENT_MNEMONIC not configured" }],
          isError: true,
        };
      }

      const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { prefix: "msg" });
      const signingClient = await SigningCosmWasmClient.connectWithSigner(
        process.env.MSG_RPC_URL || "http://localhost:26657",
        wallet
      );
      const [account] = await wallet.getAccounts();

      if (name === "register_agent") {
        const { agent_id, name: agentName, capabilities, endpoint, price, owner } = args as any;
        const result = await signingClient.execute(account.address, CONTRACTS.agentRegistry, {
          register_agent: { agent_id, name: agentName, owner, capabilities, endpoint, price_model: { price_type: "per_task", price, currency: "umsg" } },
        }, "auto");
        return { content: [{ type: "text", text: JSON.stringify(result) }] };
      }

      if (name === "submit_payment") {
        const { payment_id, payer, payee, agent_id, amount, action } = args as any;
        const result = await signingClient.execute(account.address, CONTRACTS.payment, {
          submit_intent: {
            payment_id, payer, payee, agent_id,
            aidid: `did:msg:agent:${agent_id}`,
            policy_id: "default", budget_id: `budget-${payer}`,
            constitution_version: "v1", constitution_hash: "",
            remote_signer_id: "", service_id: action, action,
            amount, asset: "umsg",
            payment_terms_hash: payment_id,
            idempotency_key: `${payment_id}-${Date.now()}`,
            expiry_unix: Math.floor(Date.now() / 1000) + 86400,
            intent_hash: payment_id, policy_decision_hash: payment_id,
            runtime_hash: payment_id, local_guard_hash: payment_id,
          },
        }, "auto");
        return { content: [{ type: "text", text: JSON.stringify(result) }] };
      }

      break;
    }

    default:
      return {
        content: [{ type: "text", text: `Unknown tool: ${name}` }],
        isError: true,
      };
  }
});

// ─── 启动 MCP Server ───
async function startMcpServer() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error("[MCP Server] MSG Chain Agent Tools ready");
}

startMcpServer().catch(console.error);

9.3 MCP Server 启动

# 安装依赖
npm install @modelcontextprotocol/sdk @cosmjs/cosmwasm-stargate @cosmjs/proto-signing

# 设置环境变量
export MSG_RPC_URL="http://localhost:26657"
export AGENT_MNEMONIC="your agent mnemonic here"

# 启动 MCP Server (stdio 模式)
node dist/mcp-server.js

# Claude Desktop 配置文件 ~/.claude/claude_desktop_config.json
# {
#   "mcpServers": {
#     "msg-chain": {
#       "command": "node",
#       "args": ["/path/to/mcp-server.js"],
#       "env": {
#         "MSG_RPC_URL": "http://localhost:26657",
#         "AGENT_MNEMONIC": "..."
#       }
#     }
#   }
# }

十、React 前端组件

10.1 Agent Registry 浏览器

// components/AgentRegistry.tsx
import React, { useEffect, useState } from "react";
import { CosmWasmClient } from "@cosmjs/cosmwasm-stargate";

const REGISTRY_ADDRESS = "msg1...agentRegistryAddress";
const RPC_URL = process.env.NEXT_PUBLIC_MSG_RPC || "http://localhost:26657";

interface Agent {
  agent_id: string;
  name: string;
  owner: string;
  capabilities: string[];
  endpoint: string;
  price_model?: { price_type: string; price: number; currency: string };
  status: string;
}

export function AgentRegistry() {
  const [agents, setAgents] = useState<Agent[]>([]);
  const [capability, setCapability] = useState("");
  const [loading, setLoading] = useState(false);

  const discover = async (cap?: string) => {
    setLoading(true);
    try {
      const client = await CosmWasmClient.connect(RPC_URL);
      const result: any = await client.queryContractSmart(REGISTRY_ADDRESS, {
        discover_agents: { capability: cap || undefined, limit: 50 },
      });
      setAgents(result.agents);
    } catch (err) {
      console.error("Discovery failed:", err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { discover(); }, []);

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">AI Agent Registry</h2>

      <div className="flex gap-2 mb-4">
        <input
          type="text"
          placeholder="Filter by capability..."
          value={capability}
          onChange={(e) => setCapability(e.target.value)}
          className="border p-2 rounded flex-1"
        />
        <button
          onClick={() => discover(capability)}
          className="bg-blue-500 text-white px-4 py-2 rounded"
        >
          {loading ? "Searching..." : "Search"}
        </button>
      </div>

      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
        {agents.map((agent) => (
          <div key={agent.agent_id} className="border rounded-lg p-4 shadow-sm">
            <h3 className="font-semibold text-lg">{agent.name || agent.agent_id}</h3>
            <p className="text-sm text-gray-500">ID: {agent.agent_id}</p>
            <p className="text-sm text-gray-500">Owner: {agent.owner.slice(0, 12)}...</p>
            <div className="flex flex-wrap gap-1 mt-2">
              {agent.capabilities.map((cap) => (
                <span key={cap} className="bg-gray-100 text-xs px-2 py-1 rounded">
                  {cap}
                </span>
              ))}
            </div>
            {agent.price_model && (
              <p className="mt-2 text-sm">
                Price: {agent.price_model.price} {agent.price_model.currency} ({agent.price_model.price_type})
              </p>
            )}
            <span className={`inline-block mt-2 text-xs px-2 py-1 rounded ${
              agent.status === "active" ? "bg-green-100 text-green-700" : "bg-yellow-100 text-yellow-700"
            }`}>
              {agent.status}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

10.2 Agent 交互面板

// components/AgentInteractionPanel.tsx
import React, { useState } from "react";
import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { useWallet } from "../hooks/useWallet";

const CONSTITUTION_ADDRESS = "msg1...constitutionAddress";

export function AgentInteractionPanel() {
  const { address, signingClient } = useWallet();
  const [agentId, setAgentId] = useState("");
  const [action, setAction] = useState("transfer");
  const [riskTier, setRiskTier] = useState<"low" | "medium" | "high">("low");
  const [result, setResult] = useState<any>(null);

  const handleCheckAction = async () => {
    if (!signingClient) return;
    const check = await signingClient.queryContractSmart(CONSTITUTION_ADDRESS, {
      check_action: { agent_id: agentId, action, risk_tier: riskTier },
    });
    setResult(check);
  };

  return (
    <div className="p-4 border rounded-lg">
      <h3 className="text-lg font-bold mb-4">Agent Action Preflight</h3>

      <div className="space-y-3">
        <input
          placeholder="Agent ID"
          value={agentId}
          onChange={(e) => setAgentId(e.target.value)}
          className="border p-2 rounded w-full"
        />

        <select
          value={action}
          onChange={(e) => setAction(e.target.value)}
          className="border p-2 rounded w-full"
        >
          <option value="transfer">Transfer</option>
          <option value="payment">Payment</option>
          <option value="contract_execute">Contract Execute</option>
          <option value="governance_propose">Governance Propose</option>
        </select>

        <select
          value={riskTier}
          onChange={(e) => setRiskTier(e.target.value as any)}
          className="border p-2 rounded w-full"
        >
          <option value="low">Low Risk</option>
          <option value="medium">Medium Risk</option>
          <option value="high">High Risk</option>
        </select>

        <button
          onClick={handleCheckAction}
          className="bg-purple-500 text-white px-4 py-2 rounded w-full"
        >
          Check Constitution
        </button>

        {result && (
          <div className={`p-3 rounded ${
            result.allowed ? "bg-green-50 border border-green-200" : "bg-red-50 border border-red-200"
          }`}>
            <p className={`font-bold ${result.allowed ? "text-green-700" : "text-red-700"}`}>
              {result.allowed ? "ALLOWED" : "DENIED"}
            </p>
            <p className="text-sm mt-1">Decision: {result.decision}</p>
            {result.reasons.length > 0 && (
              <ul className="text-sm mt-1 list-disc list-inside">
                {result.reasons.map((r: string, i: number) => (<li key={i}>{r}</li>))}
              </ul>
            )}
            {result.required_controls.length > 0 && (
              <div className="mt-2">
                <p className="text-sm font-semibold">Required Controls:</p>
                {result.required_controls.map((c: string, i: number) => (
                  <span key={i} className="inline-block bg-orange-100 text-orange-700 text-xs px-2 py-1 rounded mr-1">{c}</span>
                ))}
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

10.3 微支付会话仪表盘

// components/MicropaymentDashboard.tsx
export function MicropaymentDashboard() {
  const [sessions, setSessions] = useState<any[]>([]);

  useEffect(() => {
    (async () => {
      const client = await CosmWasmClient.connect(RPC_URL);
      const result: any = await client.queryContractSmart(
        "msg1...micropaymentAddress",
        { list_sessions: { limit: 50 } }
      );
      setSessions(result.sessions);
    })();
  }, []);

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-4">Micropayment Sessions</h2>
      <table className="w-full border-collapse">
        <thead>
          <tr className="bg-gray-100">
            <th className="border p-2 text-left">Session ID</th>
            <th className="border p-2 text-left">Payer</th>
            <th className="border p-2 text-left">Payee</th>
            <th className="border p-2 text-right">Rate/sec</th>
            <th className="border p-2 text-right">Balance</th>
            <th className="border p-2 text-right">Charged</th>
            <th className="border p-2 text-center">Status</th>
          </tr>
        </thead>
        <tbody>
          {sessions.map((s) => (
            <tr key={s.session_id}>
              <td className="border p-2 text-sm font-mono">{s.session_id.slice(0, 16)}...</td>
              <td className="border p-2 text-sm">{s.payer.slice(0, 12)}...</td>
              <td className="border p-2 text-sm">{s.payee.slice(0, 12)}...</td>
              <td className="border p-2 text-right">{s.rate_per_sec}</td>
              <td className="border p-2 text-right">{s.balance}</td>
              <td className="border p-2 text-right">{s.charged_total}</td>
              <td className="border p-2 text-center">
                <span className={`text-xs px-2 py-1 rounded ${
                  s.status === "active" ? "bg-green-100 text-green-700" : "bg-gray-100 text-gray-600"
                }`}>{s.status}</span>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

十一、外部 AI Agent Bootstrap 模式

11.1 标准引导提示词

以下 JSON 结构可作为任何外部 AI Agent 的初始化配置:

{
  "bootstrap": {
    "chain": "MSG Chain",
    "chain_id": "msg-chain-1",
    "rpc_endpoint": "http://localhost:26657",
    "rest_endpoint": "http://localhost:1317",
    "prefix": "msg",
    "genesis_registry_key": "genesis_registry",
    "agent_api_base": "http://localhost:8080"
  },
  "contracts": {
    "aidid_did_registry_v1": "resolve via genesis_registry -> aidid_did_registry_v1",
    "agent_registry_v1": "resolve via genesis_registry -> agent_registry_v1 (if registered) or use known address",
    "ai_agent_constitution_v1": "resolve via genesis_registry -> ai_agent_constitution_v1",
    "agent_payment_v1": "use known address (not in genesis_registry)",
    "micropayment_session_v1": "use known address (not in genesis_registry)",
    "dao_governance_v1": "resolve via genesis_registry -> dao_governance",
    "foundation_treasury_v2": "resolve via genesis_registry -> foundation_treasury"
  },
  "agent_capabilities": [
    "query_balance",
    "query_tx",
    "discover_agents",
    "register_agent",
    "check_action",
    "submit_payment",
    "create_micropayment",
    "resolve_did"
  ],
  "constitution_rules": {
    "query_operations": "always_allowed",
    "payment_operations": "requires_policy_check",
    "governance_operations": "requires_dao_approval",
    "treasury_operations": "requires_multisig"
  },
  "boundaries": {
    "public_testnet": "not_available",
    "sdk_release": "alpha_local_only",
    "write_paths": "guarded_with_api_key",
    "stub_endpoints": ["defi", "bridge", "registry_register"]
  }
}

11.2 外部 AI Agent 引导流程

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

interface BootstrapConfig {
  rpc: string;
  genesisRegistry: string;
  agentApi: string;
  mnemonic?: string;
}

class ExternalAgentBootstrapper {
  private config: BootstrapConfig;
  private client!: CosmWasmClient;

  constructor(config: BootstrapConfig) {
    this.config = config;
  }

  async bootstrap() {
    console.log("[Bootstrap] Connecting to MSG Chain...");
    this.client = await CosmWasmClient.connect(this.config.rpc);

    // 1. 解析所有 canonical 合约地址
    const registryClient = this.client;
    const canonicalKeys = [
      "genesis_registry",
      "dao_governance",
      "foundation_treasury",
      "gas_fee_distribution",
      "candidate_node_staking",
      "validator_qualification",
      "emission_schedule",
      "block_time_schedule",
      "ai_agent_constitution_v1",
      "aidid_did_registry_v1",
    ];

    const addressMap: Record<string, string> = {};
    for (const key of canonicalKeys) {
      try {
        const result: any = await registryClient.queryContractSmart(
          this.config.genesisRegistry,
          { resolve_canonical: { key } }
        );
        addressMap[key] = result.address;
        console.log(`  ✅ ${key} -> ${result.address}`);
      } catch {
        console.log(`  ⚠️  ${key} -> not found in genesis_registry`);
      }
    }

    // 2. 验证连接
    const height = await this.client.getHeight();
    console.log(`[Bootstrap] Connected at height ${height}`);

    // 3. 返回完整上下文
    return {
      chainId: "msg-chain-1",
      height,
      addresses: addressMap,
      agentApiUrl: this.config.agentApi,
      client: this.client,
      capabilities: [
        "query_account", "query_balance", "query_tx", "query_block",
        "discover_agents", "check_action", "resolve_did",
        "register_agent", "submit_payment", "create_micropayment",
      ],
    };
  }
}

十二、全局安全与风控体系

12.1 三层权限模型

Layer 1: API Key 保护
  ─ 所有写操作路径需要有效 API Key
  ─ Rate Limiter: 100 req/s, burst 200
  ─ 未配置 API Key 时向后兼容公开(仅本地沙箱)

Layer 2: 宪章策略引擎 (ai_agent_constitution_v1)
  ─ CheckAction 决定动作是否允许
  ─ 可对指定 Agent / 动作 / 策略进行 pause/revoke
  ─ 高风险动作返回 required_controls

Layer 3: 治理与金库门禁
  ─ 治理操作: 必须通过 DAO 提案-投票-执行
  ─ 高价值资金: 必须经过金库多签阈值
  ─ AI 不能绕过人类治理

12.2 KillSwitch 实现

// KillSwitch 集成到 AutoExecutor
class KillSwitchManager {
  private engaged: boolean = false;
  private subscribers: Array<(engaged: boolean) => void> = [];

  isEngaged(): boolean {
    return this.engaged;
  }

  engage(reason: string) {
    this.engaged = true;
    console.log(`[KillSwitch] ENGAGED: ${reason}`);
    this.subscribers.forEach((s) => s(true));
  }

  disengage() {
    this.engaged = false;
    console.log("[KillSwitch] DISENGAGED");
    this.subscribers.forEach((s) => s(false));
  }

  onToggle(handler: (engaged: boolean) => void) {
    this.subscribers.push(handler);
  }

  // 在所有写操作前检查
  guard(): void {
    if (this.engaged) {
      throw new Error("KillSwitch engaged — all write operations blocked");
    }
  }
}

// 全局 KillSwitch 实例
export const killSwitch = new KillSwitchManager();

12.3 RollbackManager

class RollbackManager {
  private history: Array<{
    id: string;
    action: string;
    undoMsg: Record<string, unknown>;
    contractAddress: string;
    timestamp: number;
  }> = [];

  record(id: string, action: string, undoMsg: Record<string, unknown>, contractAddress: string) {
    this.history.push({ id, action, undoMsg, contractAddress, timestamp: Date.now() });
  }

  async rollback(client: SigningCosmWasmClient, sender: string, id: string) {
    const entry = this.history.find((h) => h.id === id);
    if (!entry) throw new Error(`No rollback record for ${id}`);

    await client.execute(sender, entry.contractAddress, entry.undoMsg, "auto");
    console.log(`[Rollback] Reverted ${entry.action} (${id})`);

    this.history = this.history.filter((h) => h.id !== id);
  }

  async rollbackLast(client: SigningCosmWasmClient, sender: string) {
    const entry = this.history[this.history.length - 1];
    if (!entry) throw new Error("Nothing to rollback");
    return this.rollback(client, sender, entry.id);
  }
}

十三、完整 Agent 生命周期工作流

13.1 标准工作流:Agent 注册 → 授权 → 执行 → 结算

async function fullAgentWorkflow() {
  const mnemonic = process.env.AGENT_MNEMONIC!;
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, { prefix: "msg" });
  const [account] = await wallet.getAccounts();
  const client = await SigningCosmWasmClient.connectWithSigner(
    "http://localhost:26657", wallet
  );

  // Step 1: 注册 DID 身份
  const didDocument = {
    context: ["https://www.w3.org/ns/did/v1"],
    id: "did:msg:agent:my-agent-001",
    verificationMethod: [{
      id: "did:msg:agent:my-agent-001#keys-1",
      controller: "did:msg:agent:my-agent-001",
      type_: "Dilithium5VerificationKey2026",
      publicKeyMultibase: "z6Mk...Dilithium5PublicKey...",
    }],
    authentication: ["did:msg:agent:my-agent-001#keys-1"],
  };

  await client.execute(account.address, "msg1...aididRegistry", {
    register_did: {
      did: "did:msg:agent:my-agent-001",
      document: didDocument,
      verification_method_id: "did:msg:agent:my-agent-001#keys-1",
      signature: "dilithium5-signature-here",
    },
  }, "auto");

  // Step 2: 承认宪章
  await client.execute(account.address, "msg1...constitution", {
    acknowledge_constitution: {
      agent_id: "my-agent-001",
      aidid: "did:msg:agent:my-agent-001",
      constitution_version: "v1",
      constitution_hash: "abc123...",
    },
  }, "auto");

  // Step 3: 注册到 Agent Registry
  await client.execute(account.address, "msg1...agentRegistry", {
    register_agent: {
      agent_id: "my-agent-001",
      name: "My AI Agent",
      owner: account.address,
      capabilities: ["text-generation", "code-review", "data-analysis"],
      endpoint: "https://my-agent.example.com/api",
      price_model: { price_type: "per_task", price: "50000", currency: "umsg" },
    },
  }, "auto");

  // Step 4: 预检动作
  const check = await client.queryContractSmart("msg1...constitution", {
    check_action: {
      agent_id: "my-agent-001",
      action: "payment",
      risk_tier: "low",
    },
  });
  console.log("Action check:", check);

  // Step 5: 提交支付意图
  await client.execute(account.address, "msg1...payment", {
    submit_intent: {
      payment_id: "pay-001",
      payer: account.address,
      payee: "msg1...serviceProvider",
      agent_id: "my-agent-001",
      aidid: "did:msg:agent:my-agent-001",
      policy_id: "default-policy",
      budget_id: "budget-main",
      constitution_version: "v1",
      constitution_hash: "abc123...",
      remote_signer_id: "",
      service_id: "text-generation",
      action: "payment",
      amount: "50000",
      asset: "umsg",
      payment_terms_hash: "hash-001",
      idempotency_key: `pay-001-${Date.now()}`,
      expiry_unix: Math.floor(Date.now() / 1000) + 86400,
      intent_hash: "hash-001",
      policy_decision_hash: "hash-001",
      runtime_hash: "hash-001",
      local_guard_hash: "hash-001",
    },
  }, "auto");

  console.log("Agent lifecycle complete!");
}

13.2 AI Agent to AI Agent (A2A) 通信模式

// Agent A 发现 Agent B → 发起请求 → 微支付 → 结算
async function a2aCommunication() {
  const client = await CosmWasmClient.connect("http://localhost:26657");

  // Agent A: 发现能做 "code-review" 的 Agent
  const result: any = await client.queryContractSmart(
    "msg1...agentRegistry",
    { discover_agents: { capability: "code-review", limit: 5 } }
  );

  const codeReviewer = result.agents[0];
  console.log(`Found code reviewer: ${codeReviewer.name} @ ${codeReviewer.endpoint}`);

  // Agent A: 创建微支付会话
  const signingClient = await SigningCosmWasmClient.connectWithSigner(
    "http://localhost:26657", agentAWallet
  );

  await signingClient.execute(agentAAddress, "msg1...micropayment", {
    create_session: {
      session_id: `a2a-${Date.now()}`,
      payer: agentAAddress,
      payee: codeReviewer.owner,
      rate_per_sec: 100,  // 100 umsg/sec
      balance: 100000,     // 100 MSG 预存
      asset: "umsg",
      terms_hash: crypto.createHash("sha256").update(`a2a-session-${Date.now()}`).digest("hex"),
    },
  }, "auto");

  // Agent A: 发送 HTTP 请求到 Agent B 的 endpoint
  const response = await fetch(codeReviewer.endpoint, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ task: "Review this code...", session_id }),
  });

  // Agent A: 按秒扣费(通过中间件自动执行)
  // ... (使用 MicroPaymentMiddleware)

  console.log("A2A communication complete");
}

十四、Post-Quantum 安全特性集成

14.1 Dilithium-5 在 AI Agent 中的应用

// AI Agent 使用 Dilithium-5 签名验证确保通信安全
interface PQSignature {
  algorithm: "Dilithium5";
  publicKey: string;    // Dilithium-5 公钥(multibase 编码)
  signature: string;     // base64 签名
  message: string;       // base64 原文
}

// 链上验证 PQ 签名(通过 aidid_did_registry_v1 自定义查询)
async function verifyPQSignature(
  client: CosmWasmClient,
  signature: PQSignature
): Promise<boolean> {
  const result: any = await client.queryContractSmart(
    "msg1...aididRegistry",
    {
      msg_pq_verify_v1: {
        algorithm: signature.algorithm,
        public_key: signature.publicKey,
        signature: signature.signature,
        message: signature.message,
        message_encoding: "base64",
        public_key_encoding: "multibase",
        signature_encoding: "base64",
      },
    }
  );
  return result.valid;
}

// 生成 Dilithium-5 密钥对(在 MSG Chain 节点本地)
// MSG Chain 节点提供 Dilithium-5 密钥生成:
// const { publicKey, privateKey } = crypto.generatePQKeypair("Dilithium5");

14.2 量子安全 Agent 通信信道

class QuantumSecureChannel {
  async signMessage(privateKey: string, message: string): Promise<string> {
    // 使用 Dilithium-5 签名
    // 实际实现调用 MSG Chain 节点的 crypto 模块
    return crypto.signDilithium5(privateKey, message);
  }

  async verifyMessage(
    client: CosmWasmClient,
    publicKey: string,
    message: string,
    signature: string
  ): Promise<boolean> {
    return verifyPQSignature(client, {
      algorithm: "Dilithium5",
      publicKey,
      signature,
      message: Buffer.from(message).toString("base64"),
    });
  }
}

十五、开发环境与调试

15.1 本地沙箱启动

# 1. 启动 MSG Chain 本地节点
./msg-chain start --home ~/.msg-chain

# 2. Agent API 默认端口
export MSG_AGENT_API="http://localhost:8080"
export MSG_RPC_URL="http://localhost:26657"

# 3. 环境变量配置
export AGENT_MNEMONIC="test test test test test test test test test test test junk"
export AGENT_API_KEY="your-api-key-here"

15.2 验证脚本

// health_check.ts — 验证 Agent API 可用性
async function healthCheck() {
  const checks = [];

  // 检查 RPC 连通性
  try {
    const client = await CosmWasmClient.connect("http://localhost:26657");
    const height = await client.getHeight();
    checks.push({ name: "RPC", status: "✅", detail: `height=${height}` });
  } catch (e) {
    checks.push({ name: "RPC", status: "❌", detail: String(e) });
  }

  // 检查 Agent API 查询
  try {
    const res = await fetch("http://localhost:8080/agent/v1/query/account/msg1...");
    if (res.ok) checks.push({ name: "Agent API Query", status: "✅" });
    else checks.push({ name: "Agent API Query", status: "❌", detail: res.statusText });
  } catch (e) {
    checks.push({ name: "Agent API Query", status: "❌", detail: String(e) });
  }

  // 检查合约查询
  try {
    const client = await CosmWasmClient.connect("http://localhost:26657");
    const agents: any = await client.queryContractSmart("msg1...agentRegistry", {
      list_agents: { limit: 1 },
    });
    checks.push({ name: "Agent Registry", status: "✅", detail: `${agents.count} agents` });
  } catch (e) {
    checks.push({ name: "Agent Registry", status: "❌", detail: String(e) });
  }

  console.table(checks);
}

附录

A. 常见错误与调试

错误 原因 解决
X-MSG-Stub: true 调用了 stub 端点 检查端点状态,使用真实路径
fail-closed SDK 预设未验证 使用 localhost 端点,覆盖 preset
not found 合约地址错误 通过 genesis_registry 解析 canonical key
unauthorized 写操作缺 API Key 设置 X-API-Key header
constitution_denied 宪章策略阻止 检查 CheckAction 的 reasons 字段

B. 合约地址获取方式

// 优先使用 genesis_registry_v1 解析 canonical key
async function resolveCanonical(
  client: CosmWasmClient,
  registryAddress: string,
  key: string
): Promise<string> {
  const result: any = await client.queryContractSmart(registryAddress, {
    resolve_canonical: { key },
  });
  return result.address;
}

// 已知 canonical keys:
// genesis_registry        -> genesis_registry_v1
// dao_governance          -> dao_governance_v1
// foundation_treasury     -> foundation_treasury_v2
// gas_fee_distribution    -> gas_fee_distribution_v2
// candidate_node_staking  -> candidate_node_staking_v2
// validator_qualification -> validator_qualification_v2
// emission_schedule       -> emission_schedule_v2
// block_time_schedule     -> block_time_schedule_v1
// ai_agent_constitution_v1 -> ai_agent_constitution_v1
// aidid_did_registry_v1   -> aidid_did_registry_v1
// 以下不在 genesis_registry 中:
// agent_registry_v1        -> 需已知地址或链下发现
// agent_payment_v1         -> 需已知地址或链下发现
// micropayment_session_v1  -> 需已知地址或链下发现

C. 参照物对比

特性 OKX AI MSG Chain AI Agent
Agent 身份 中心化 链上 DID (aidid_did_registry_v1)
Agent 注册 平台审核 去中心化 (agent_registry_v1)
策略引擎 平台规则 链上宪章 (ai_agent_constitution_v1)
支付 中心化托管 链上 AIPAY (agent_payment_v1)
微支付 多层结算 按秒扣费 (micropayment_session_v1)
签名 ECDSA Dilithium-5 PQC
治理 平台决策 DAO + 金库多签
安全 传统 后量子 + KillSwitch + 宪章
开发工具 OnchainOS MCP Server + Agent API