dApp Docs/API接口大全
Development reference. Not independently verified for production.

MSG Chain API 接口大全 — API 参考文档(含 Stub 端点标注)

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

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

目标:本文档作为 MSG Chain 的 API 参考指南,涵盖 RPC、REST、合约、Agent 四大接口体系。部分端点标记为 Stub(未完全实现),开发者应以源码和实际测试为准。


目录

  1. 概述
  2. RPC 接口
  3. REST API
  4. 合约 API
  5. Agent API
  6. 错误码大全
  7. CosmJS 集成示例
  8. curl 使用示例
  9. WebSocket 事件订阅
  10. 限流与安全

一、概述

1.1 网络架构

MSG Chain 提供四层 API 访问体系,分别对应不同的交互场景:

┌──────────────────────────────────────────────────────────┐
│                    Agent API (端口 8080)                   │
│  REST / WebSocket / MPC / Payment                        │
│  18 个端点,5 个分组                                      │
├──────────────────────────────────────────────────────────┤
│                    RPC (端口 26657)                        │
│  JSON-RPC 2.0 over HTTP/TCP                              │
│  Cosmos SDK + CosmWasm + 自定义 MSG 模块                  │
├──────────────────────────────────────────────────────────┤
│                    REST API (端口 1317)                    │
│  Cosmos SDK REST 标准                                     │
│  查询、交易广播、合约交互                                  │
├──────────────────────────────────────────────────────────┤
│                    gRPC (端口 9090)                        │
│  底层 gRPC 协议,性能最高                                 │
├──────────────────────────────────────────────────────────┤
│                    WebSocket (端口 26657)                  │
│  Tendermint RPC WebSocket + 自定义 Agent 事件             │
└──────────────────────────────────────────────────────────┘

1.2 端点地址

环境 RPC REST Agent API gRPC
本地开发 http://localhost:26657 http://localhost:1317 http://localhost:8080 localhost:9090
未来主网 https://rpc.msgchain.org https://rest.msgchain.org https://api.msgchain.org msgchain.org:9090

1.3 链参数

参数 值
Chain ID msg-chain-1
Bech32 前缀 msg
地址示例 msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3
代币符号 MSG
最小单位 umsg (1 MSG = 10^18 umsg)
小数位数 18
Gas 价格 1,000,000,000 attoMSG/gas
出块时间 ~5 秒
共识算法 Round-Robin + DAR (Dilithium-AR)
签名方案 Dilithium-5 (后量子密码学)
BIP44 币种类型 118

1.4 内容类型

所有 HTTP API 请求和响应使用 Content-Type: application/json。RPC 端点遵循 JSON-RPC 2.0 规范。

1.5 交易广播流程

构造 TxBody → Amino/Protobuf 编码 → 签名 → BroadcastTx → 等待 Inclusion
     │                                                        │
     └── Gas 估算 ←── GasPrices × GasLimit ←── 选择 Gas 价格层级 ──┘

所有交易必须包含:


二、RPC 接口

2.1 RPC 调用规范

MSG Chain RPC 使用 JSON-RPC 2.0 协议,通过 HTTP POST 访问 http://localhost:26657。

请求格式:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "method_name",
  "params": {}
}

响应格式:

{
  "jsonrpc": "2.0",
  "id": 1,
  "result": { ... }
}

错误响应:

{
  "jsonrpc": "2.0",
  "id": 1,
  "error": {
    "code": -32000,
    "message": "...",
    "data": "..."
  }
}

2.2 Cosmos SDK 标准 RPC 方法

这些方法通过 gRPC 网关暴露为 HTTP POST 到 http://localhost:26657/cosmos/*。

2.2.1 Bank 模块

/cosmos.bank.v1beta1.Query/Balance

查询账户指定代币余额。类似以太坊的 eth_getBalance。

描述: 查询指定地址的指定 denom 余额

请求参数:

字段 类型 说明
address string Bech32 地址 (msg1...)
denom string 代币单位 (umsg)

请求示例:

{
  "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "denom": "umsg"
}

响应示例:

{
  "balance": {
    "denom": "umsg",
    "amount": "1000000000000000000"
  }
}

curl 调用:

curl -X POST http://localhost:26657/cosmos.bank.v1beta1.Query/Balance \
  -H "Content-Type: application/json" \
  -d '{
    "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "denom": "umsg"
  }'

/cosmos.bank.v1beta1.Query/AllBalances

查询地址所有代币余额。

描述: 返回地址拥有的所有代币余额列表

请求参数:

字段 类型 说明
address string Bech32 地址
pagination.key bytes (optional) 分页键
pagination.offset uint64 (optional) 分页偏移
pagination.limit uint64 (optional) 每页条数 (默认 100)
pagination.count_total bool (optional) 是否返回总数

请求示例:

{
  "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "pagination": {
    "limit": "100"
  }
}

响应示例:

{
  "balances": [
    { "denom": "umsg", "amount": "1000000000000000000" },
    { "denom": "uio", "amount": "500000000000000000" }
  ],
  "pagination": {
    "next_key": null,
    "total": "2"
  }
}

/cosmos.bank.v1beta1.Query/TotalSupply

查询链上代币总供应量。

描述: 返回所有代币的总供应量

请求示例:

{}

响应示例:

{
  "supply": [
    { "denom": "umsg", "amount": "1000000000000000000000" }
  ]
}

/cosmos.bank.v1beta1.Query/SupplyOf

查询指定 denom 的供应量。

请求参数:

字段 类型 说明
denom string 代币单位

请求示例:

{ "denom": "umsg" }

响应示例:

{
  "amount": { "denom": "umsg", "amount": "1000000000000000000000" }
}

2.2.2 Staking 模块

/cosmos.staking.v1beta1.Query/Validators

查询验证者列表。

描述: 返回当前所有验证者的详细信息。类似以太坊的共识层验证者查询。

请求参数:

字段 类型 说明
status string (optional) 过滤状态: BOND_STATUS_BONDED / BOND_STATUS_UNBONDED / BOND_STATUS_UNBONDING
pagination object (optional) 分页参数

请求示例:

{
  "status": "BOND_STATUS_BONDED"
}

响应示例:

{
  "validators": [
    {
      "operator_address": "msgvaloper1...",
      "consensus_pubkey": {
        "@type": "/cosmos.crypto.dilithium.PubKey",
        "key": "base64..."
      },
      "jailed": false,
      "status": "BOND_STATUS_BONDED",
      "tokens": "500000000000000000",
      "delegator_shares": "500000000000000000",
      "description": {
        "moniker": "MyValidator",
        "identity": "",
        "website": "",
        "security_contact": "",
        "details": ""
      },
      "commission": {
        "commission_rates": {
          "rate": "0.100000000000000000",
          "max_rate": "0.200000000000000000",
          "max_change_rate": "0.010000000000000000"
        },
        "update_time": "2026-01-01T00:00:00Z"
      },
      "unbonding_time": "1970-01-01T00:00:00Z",
      "min_self_delegation": "1"
    }
  ],
  "pagination": {
    "next_key": null,
    "total": "1"
  }
}

/cosmos.staking.v1beta1.Query/DelegatorDelegations

查询委托人的所有委托。

描述: 返回指定地址的所有委托信息。类似以太坊的 stake 查询。

请求参数:

字段 类型 说明
delegator_addr string 委托人地址

请求示例:

{
  "delegator_addr": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

响应示例:

{
  "delegation_responses": [
    {
      "delegation": {
        "delegator_address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
        "validator_address": "msgvaloper1...",
        "shares": "250000000000000000"
      },
      "balance": {
        "denom": "umsg",
        "amount": "250000000000000000"
      }
    }
  ]
}

/cosmos.staking.v1beta1.Query/Validator

查询单个验证者详情。

请求参数:

字段 类型 说明
validator_addr string 验证者 operator 地址

请求示例:

{
  "validator_addr": "msgvaloper1..."
}

响应示例:

{
  "validator": {
    "operator_address": "msgvaloper1...",
    "consensus_pubkey": { "@type": "/cosmos.crypto.dilithium.PubKey", "key": "..." },
    "jailed": false,
    "status": "BOND_STATUS_BONDED",
    "tokens": "500000000000000000",
    "delegator_shares": "500000000000000000",
    "description": { "moniker": "MyValidator" },
    "commission": {
      "commission_rates": {
        "rate": "0.100000000000000000",
        "max_rate": "0.200000000000000000",
        "max_change_rate": "0.010000000000000000"
      }
    },
    "unbonding_time": "1970-01-01T00:00:00Z",
    "min_self_delegation": "1"
  }
}

2.2.3 Distribution 模块

/cosmos.distribution.v1beta1.Query/DelegationRewards

查询委托奖励。

描述: 返回委托人从指定验证者处获得的未领取奖励。

请求参数:

字段 类型 说明
delegator_address string 委托人地址
validator_address string 验证者地址

请求示例:

{
  "delegator_address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "validator_address": "msgvaloper1..."
}

响应示例:

{
  "rewards": [
    { "denom": "umsg", "amount": "50000000000000000" }
  ]
}

2.2.4 Governance 模块

/cosmos.gov.v1beta1.Query/Proposals

查询所有治理提案。

描述: 返回链上所有治理提案列表。类似以太坊的治理合约查询。

请求示例:

{
  "proposal_status": "PROPOSAL_STATUS_VOTING_PERIOD"
}

响应示例:

{
  "proposals": [
    {
      "proposal_id": "1",
      "content": {
        "@type": "/cosmos.gov.v1beta1.TextProposal",
        "title": "升级验证者最小质押量",
        "description": "将最小验证者质押量从 1 MSG 提升到 100 MSG"
      },
      "status": "PROPOSAL_STATUS_VOTING_PERIOD",
      "final_tally_result": {
        "yes": "0",
        "abstain": "0",
        "no": "0",
        "no_with_veto": "0"
      },
      "submit_time": "2026-01-01T00:00:00Z",
      "deposit_end_time": "2026-01-08T00:00:00Z",
      "total_deposit": [
        { "denom": "umsg", "amount": "1000000000000000000" }
      ],
      "voting_start_time": "2026-01-01T00:00:00Z",
      "voting_end_time": "2026-01-08T00:00:00Z"
    }
  ]
}

/cosmos.gov.v1beta1.Query/Vote

查询指定提案的投票详情。

请求参数:

字段 类型 说明
proposal_id uint64 提案 ID
voter string 投票者地址

请求示例:

{
  "proposal_id": "1",
  "voter": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

响应示例:

{
  "vote": {
    "proposal_id": "1",
    "voter": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "options": [
      { "option": "VOTE_OPTION_YES", "weight": "1.000000000000000000" }
    ]
  }
}

2.2.5 Auth 模块

/cosmos.auth.v1beta1.Query/Account

查询账户信息。

描述: 返回账户详情,包括账户号、sequence、公钥等。

请求参数:

字段 类型 说明
address string Bech32 地址

请求示例:

{
  "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

响应示例:

{
  "account": {
    "@type": "/cosmos.auth.v1beta1.BaseAccount",
    "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "pub_key": {
      "@type": "/cosmos.crypto.dilithium.PubKey",
      "key": "base64-encoded-dilithium5-public-key"
    },
    "account_number": "0",
    "sequence": "5"
  }
}

注意: MSG Chain 的默认密钥类型是 Dilithium-5,而非 ECDSA。@type 为 /cosmos.crypto.dilithium.PubKey。


2.2.6 Tx 模块

/cosmos.tx.v1beta1.Service/GetTx

根据哈希查询交易详情。

描述: 类似以太坊的 eth_getTransactionByHash。

请求参数:

字段 类型 说明
hash string 交易哈希 (hex)

请求示例:

{
  "hash": "0xABCDEF1234567890..."
}

响应示例:

{
  "tx": {
    "body": {
      "messages": [
        {
          "@type": "/cosmos.bank.v1beta1.MsgSend",
          "from_address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
          "to_address": "msg1...",
          "amount": [{ "denom": "umsg", "amount": "1000000000000000000" }]
        }
      ],
      "memo": "",
      "timeout_height": "0"
    },
    "auth_info": {
      "signer_infos": [...],
      "fee": {
        "amount": [{ "denom": "umsg", "amount": "5000" }],
        "gas_limit": "200000",
        "payer": "",
        "granter": ""
      }
    }
  },
  "tx_response": {
    "height": "12345",
    "txhash": "0xABCDEF1234567890...",
    "codespace": "",
    "code": 0,
    "data": "...",
    "raw_log": "[{\"events\":[...]}]",
    "logs": [...],
    "info": "",
    "gas_wanted": "200000",
    "gas_used": "123456",
    "timestamp": "2026-01-01T00:00:00Z",
    "events": [...]
  }
}

/cosmos.tx.v1beta1.Service/GetTxsEvent

根据事件查询交易列表。

描述: 通过事件属性过滤查询交易。类似以太坊的日志过滤。

请求参数:

字段 类型 说明
events Event[] 事件过滤条件列表
pagination object (optional) 分页

事件格式:{key: "message.sender", value: "msg1..."}

请求示例:

{
  "events": [
    { "key": "message.sender", "value": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3" }
  ],
  "pagination": { "limit": "10" }
}

响应示例:

{
  "txs": [...],
  "tx_responses": [...],
  "pagination": { "next_key": null, "total": "25" }
}

/cosmos.tx.v1beta1.Service/BroadcastTx

广播交易到链上。

描述: 类似以太坊的 eth_sendRawTransaction。接收已签名的交易并广播。

请求参数:

字段 类型 说明
tx_bytes bytes Protobuf 编码的已签名交易
mode BroadcastMode 广播模式

BroadcastMode 可选值:

模式 值 说明
BROADCAST_MODE_UNSPECIFIED 0 未指定
BROADCAST_MODE_BLOCK 1 等待交易被打包进区块后返回(阻塞)
BROADCAST_MODE_SYNC 2 检查 CheckTx 通过后立即返回
BROADCAST_MODE_ASYNC 3 立即返回,不等待 CheckTx

请求示例:

{
  "tx_bytes": "base64-encoded-protobuf-tx",
  "mode": "BROADCAST_MODE_SYNC"
}

响应示例:

{
  "tx_response": {
    "height": "0",
    "txhash": "0xABCDEF1234567890...",
    "code": 0,
    "raw_log": "[]"
  }
}

2.3 CosmWasm 标准 RPC 方法

2.3.1 Code 查询

/cosmwasm.wasm.v1.Query/Code

查询指定 Code ID 的合约代码信息。

描述: 返回已上传的 WASM 代码元数据和完整二进制。

请求参数:

字段 类型 说明
code_id uint64 代码 ID

请求示例:

{ "code_id": "1" }

响应示例:

{
  "code_info": {
    "code_id": "1",
    "creator": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "data_hash": "base64-64bytes",
    "instantiate_permission": {
      "permission": "Everybody",
      "addresses": []
    }
  },
  "data": "base64-encoded-wasm-binary"
}

/cosmwasm.wasm.v1.Query/CodeInfo

查询代码元数据(不包含二进制数据)。

请求示例:

{ "code_id": "1" }

响应示例:

{
  "code_id": "1",
  "creator": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "data_hash": "base64-64bytes",
  "instantiate_permission": {
    "permission": "Everybody",
    "addresses": []
  }
}

/cosmwasm.wasm.v1.Query/AllCode

列出所有已上传的代码。

请求示例:

{
  "pagination": { "limit": "100" }
}

响应示例:

{
  "code_infos": [
    {
      "code_id": "1",
      "creator": "msg1...",
      "data_hash": "base64..."
    },
    {
      "code_id": "2",
      "creator": "msg1...",
      "data_hash": "base64..."
    }
  ],
  "pagination": { "next_key": null, "total": "2" }
}

2.3.2 Contract 查询

/cosmwasm.wasm.v1.Query/ContractInfo

查询合约实例的元数据。

请求参数:

字段 类型 说明
address string 合约地址

请求示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
}

响应示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "contract_info": {
    "code_id": "1",
    "creator": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "admin": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "label": "my-first-contract",
    "created": { "block_height": "100", "tx_index": 0 },
    "ibc_port_id": ""
  }
}

/cosmwasm.wasm.v1.Query/ContractHistory

查询合约迁移历史。

请求示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
}

响应示例:

{
  "entries": [
    {
      "operation": "CONTRACT_CODE_HISTORY_OPERATION_TYPE_INIT",
      "code_id": "1",
      "updated": { "block_height": "100", "tx_index": 0 },
      "msg": {}
    }
  ]
}

/cosmwasm.wasm.v1.Query/ContractsByCode

查询指定 Code ID 的所有合约实例。

请求示例:

{
  "code_id": "1",
  "pagination": { "limit": "100" }
}

响应示例:

{
  "contracts": [
    "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
  ],
  "pagination": { "next_key": null, "total": "1" }
}

2.3.3 State 查询

/cosmwasm.wasm.v1.Query/AllContractState

查询合约的完整原始存储状态。

请求示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "pagination": { "limit": "100" }
}

响应示例:

{
  "models": [
    { "key": "base64-encoded-key", "value": "base64-encoded-value" }
  ],
  "pagination": { "next_key": null, "total": "1" }
}

/cosmwasm.wasm.v1.Query/RawContractState

查询合约的某个原始存储键值。

请求参数:

字段 类型 说明
address string 合约地址
query_data bytes 要查询的存储键(base64 编码)

请求示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "query_data": "c3RhdGU="
}

响应示例:

{
  "data": "base64-encoded-value"
}

/cosmwasm.wasm.v1.Query/SmartContractState

对合约执行智能查询(smart query)。

描述: 这是最常用的合约查询方式,类似以太坊的 eth_call。合约通过 #[entry_point] pub fn query(...) 处理查询。

请求参数:

字段 类型 说明
address string 合约地址
query_data bytes JSON 编码的查询消息(base64 编码)

请求示例:

{
  "address": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "query_data": "eyJnZXRfY291bnQiOiB7fX0="
}

eyJnZXRfY291bnQiOiB7fX0= 解码后为 {"get_count": {}}

响应示例:

{
  "data": "eyJjb3VudCI6IDB9"
}

eyJjb3VudCI6IDB9 解码后为 {"count": 0}

curl 快捷方式:

# 直接使用 JSON 格式的 query_data(REST 请求)
curl -X GET "http://localhost:1317/cosmwasm/wasm/v1/contract/msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal/smart/eyJnZXRfY291bnQiOiB7fX0="

/cosmwasm.wasm.v1.Query/Params

查询 CosmWasm 模块参数。

请求示例:

{}

响应示例:

{
  "params": {
    "code_upload_access": {
      "permission": "Everybody",
      "addresses": []
    },
    "instantiate_default_permission": "Everybody",
    "max_wasm_code_size": "819200"
  }
}

2.3.4 CosmWasm 交易方法

这些不是查询类 RPC,而是通过 /cosmos.tx.v1beta1.Service/BroadcastTx 广播的 Msg 类型。

Msg/StoreCode — 上传合约代码
{
  "@type": "/cosmwasm.wasm.v1.MsgStoreCode",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "wasm_byte_code": "base64-encoded-wasm-binary",
  "instantiate_permission": {
    "permission": "Everybody",
    "addresses": []
  }
}
Msg/InstantiateContract — 实例化合约
{
  "@type": "/cosmwasm.wasm.v1.MsgInstantiateContract",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "admin": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "code_id": "1",
  "label": "my-contract",
  "msg": "base64-encoded-init-json",
  "funds": []
}
Msg/ExecuteContract — 执行合约
{
  "@type": "/cosmwasm.wasm.v1.MsgExecuteContract",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "contract": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "msg": "base64-encoded-execute-json",
  "funds": []
}
Msg/MigrateContract — 迁移合约
{
  "@type": "/cosmwasm.wasm.v1.MsgMigrateContract",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "contract": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal",
  "code_id": "2",
  "msg": "base64-encoded-migrate-json"
}
Msg/UpdateAdmin — 更新合约管理员
{
  "@type": "/cosmwasm.wasm.v1.MsgUpdateAdmin",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "new_admin": "msg1...",
  "contract": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
}
Msg/ClearAdmin — 清除合约管理员
{
  "@type": "/cosmwasm.wasm.v1.MsgClearAdmin",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "contract": "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
}

2.4 MSG Chain 自定义 RPC 方法

2.4.1 Agent 模块 (/msgchain.agent.v1.Query/*)

/msgchain.agent.v1.Query/AgentConfig

查询 Agent 配置。

请求参数:

字段 类型 说明
agent_id string Agent 唯一标识

请求示例:

{
  "agent_id": "my-agent-001"
}

响应示例:

{
  "config": {
    "agent_id": "my-agent-001",
    "owner": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "constitution_version": "v1",
    "constitution_hash": "abc123...",
    "capabilities": ["text-generation", "code-review"],
    "endpoint": "https://my-agent.example.com/api",
    "risk_tier": "medium",
    "status": "active"
  }
}

/msgchain.agent.v1.Query/AgentState

查询 Agent 执行状态。

请求示例:

{
  "agent_id": "my-agent-001"
}

响应示例:

{
  "state": {
    "agent_id": "my-agent-001",
    "status": "running",
    "current_action": "executing_payment",
    "last_execution_height": "12345",
    "total_actions": 42,
    "successful_actions": 40,
    "failed_actions": 2,
    "last_error": null
  }
}

/msgchain.agent.v1.Query/AvailableActions

列出 Agent 可用的动作列表。

请求示例:

{}

响应示例:

{
  "actions": [
    { "name": "transfer", "description": "转账", "risk_tier": "medium" },
    { "name": "payment", "description": "支付", "risk_tier": "low" },
    { "name": "contract_execute", "description": "合约执行", "risk_tier": "high" },
    { "name": "governance_propose", "description": "治理提案", "risk_tier": "high" },
    { "name": "query_balance", "description": "余额查询", "risk_tier": "low" }
  ]
}

/msgchain.agent.v1.Query/ActionDetail

获取指定动作的详情。

请求参数:

字段 类型 说明
action_name string 动作名称

请求示例:

{
  "action_name": "transfer"
}

响应示例:

{
  "action": {
    "name": "transfer",
    "description": "从 Agent 钱包转账到指定地址",
    "risk_tier": "medium",
    "required_controls": ["constitution_check"],
    "parameters": [
      { "name": "to", "type": "string", "description": "目标地址" },
      { "name": "amount", "type": "uint128", "description": "转账金额 (umsg)" }
    ]
  }
}

/msgchain.agent.v1.Query/AgentBalance

查询 Agent 钱包余额。

请求示例:

{
  "agent_id": "my-agent-001"
}

响应示例:

{
  "balance": {
    "agent_id": "my-agent-001",
    "balances": [
      { "denom": "umsg", "amount": "500000000000000000" }
    ],
    "escrow_balance": "100000000000000000"
  }
}

/msgchain.agent.v1.Query/ExecutionHistory

查询 Agent 执行历史。

请求参数:

字段 类型 说明
agent_id string Agent ID
pagination object (optional) 分页

请求示例:

{
  "agent_id": "my-agent-001",
  "pagination": { "limit": "10" }
}

响应示例:

{
  "executions": [
    {
      "height": "12345",
      "tx_hash": "0xABCD...",
      "action": "transfer",
      "status": "success",
      "timestamp": "2026-01-01T00:00:00Z",
      "details": { "to": "msg1...", "amount": "1000000" }
    }
  ],
  "pagination": { "total": "42" }
}

2.4.2 Agent 交易方法

Msg/RegisterAgent — 注册 Agent
{
  "@type": "/msgchain.agent.v1.MsgRegisterAgent",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "name": "My AI Agent",
  "owner": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "capabilities": ["text-generation", "code-review"],
  "endpoint": "https://my-agent.example.com/api",
  "price_model": {
    "price_type": "per_task",
    "price": "50000",
    "currency": "umsg"
  },
  "constitution_version": "v1",
  "constitution_hash": "abc123..."
}
Msg/ExecuteAction — 执行 Agent 动作
{
  "@type": "/msgchain.agent.v1.MsgExecuteAction",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "action": "transfer",
  "params": {
    "to": "msg1...",
    "amount": "1000000"
  },
  "justification": "Pay for code review service"
}
Msg/DepositAgent — 向 Agent 充值
{
  "@type": "/msgchain.agent.v1.MsgDepositAgent",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "amount": [{ "denom": "umsg", "amount": "1000000000000000000" }]
}
Msg/WithdrawAgent — 从 Agent 提现
{
  "@type": "/msgchain.agent.v1.MsgWithdrawAgent",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "amount": [{ "denom": "umsg", "amount": "500000000000000000" }],
  "to_address": "msg1..."
}
Msg/UpdateAgentConfig — 更新 Agent 配置
{
  "@type": "/msgchain.agent.v1.MsgUpdateAgentConfig",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "config": {
    "risk_tier": "low",
    "max_gas_price": "1000000000attoMSG",
    "max_task_budget": "100000000"
  }
}
Msg/UpdateAgentMetadata — 更新 Agent 元数据
{
  "@type": "/msgchain.agent.v1.MsgUpdateAgentMetadata",
  "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "agent_id": "my-agent-001",
  "metadata": {
    "name": "Updated Agent Name",
    "capabilities": ["text-generation", "code-review", "data-analysis"],
    "endpoint": "https://new-endpoint.example.com/api"
  }
}

2.4.3 DAR 模块 (/msgchain.dar.v1.Query/*)

DAR (Dilithium-AR) 是 MSG Chain 的共识扩展模块。

/msgchain.dar.v1.Query/DarRatings

查询 DAR 评分列表。

请求示例:

{}

响应示例:

{
  "ratings": [
    {
      "validator_address": "msgvaloper1...",
      "rating": 850,
      "last_updated": "2026-01-01T00:00:00Z",
      "total_blocks_produced": 5000,
      "uptime_percentage": "99.5"
    }
  ]
}
/msgchain.dar.v1.Query/DarRating

查询指定验证者的 DAR 评分。

请求参数:

字段 类型 说明
validator_address string 验证者地址

请求示例:

{
  "validator_address": "msgvaloper1..."
}

响应示例:

{
  "rating": {
    "validator_address": "msgvaloper1...",
    "rating": 850,
    "last_updated": "2026-01-01T00:00:00Z",
    "total_blocks_produced": 5000,
    "uptime_percentage": "99.5"
  }
}

2.4.4 Dilithium 模块 (/msgchain.dilithium.v1.Query/*)

后量子密码学签名查询。

/msgchain.dilithium.v1.Query/PublicKey

查询 Dilithium-5 公钥。

请求参数:

字段 类型 说明
address string 要查询公钥的地址

请求示例:

{
  "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

响应示例:

{
  "public_key": {
    "@type": "/cosmos.crypto.dilithium.PubKey",
    "key": "base64-encoded-dilithium5-public-key"
  }
}
/msgchain.dilithium.v1.Query/VerifySignature

验证 Dilithium-5 签名。这是 MSG Chain 的后量子密码学核心功能。

请求参数:

字段 类型 说明
public_key string Dilithium-5 公钥(base64)
signature string 待验证的签名(base64)
message string 原文(base64)
algorithm string 签名算法,固定 "Dilithium5"

请求示例:

{
  "public_key": "base64-encoded-pk",
  "signature": "base64-encoded-signature",
  "message": "base64-encoded-message",
  "algorithm": "Dilithium5"
}

响应示例:

{
  "valid": true,
  "algorithm": "Dilithium5",
  "key_version": "v1"
}

2.5 Tendermint 原生 RPC 方法

这些是 Tendermint 核心 RPC,位于 http://localhost:26657 (非 gRPC 网关)。

方法 描述 示例
status 节点状态 curl http://localhost:26657/status
block 查询区块 curl "http://localhost:26657/block?height=1"
block_results 区块结果 curl "http://localhost:26657/block_results?height=1"
commit 区块提交信息 curl "http://localhost:26657/commit?height=1"
validators 验证者集 curl "http://localhost:26657/validators?height=1"
consensus_state 共识状态 curl http://localhost:26657/consensus_state
health 节点健康检查 curl http://localhost:26657/health
net_info 网络对等信息 curl http://localhost:26657/net_info
abci_query 直接 ABCI 查询 curl "http://localhost:26657/abci_query?path=\"/store/bank/key\"&data=0x00"
broadcast_tx_sync 同步广播交易 curl -X POST http://localhost:26657/broadcast_tx_sync -d '{"tx":"base64"}'
broadcast_tx_async 异步广播交易 curl -X POST http://localhost:26657/broadcast_tx_async -d '{"tx":"base64"}'
unconfirmed_txs 未确认交易 curl http://localhost:26657/unconfirmed_txs

status 响应示例:

{
  "jsonrpc": "2.0",
  "id": -1,
  "result": {
    "node_info": {
      "protocol_version": { "p2p": 8, "block": 11, "app": 1 },
      "id": "node-id-hex",
      "network": "msg-chain-1",
      "version": "0.1.0",
      "channels": "4020212223303800",
      "moniker": "msg-chain-node",
      "other": { "tx_index": "on", "rpc_address": "tcp://0.0.0.0:26657" }
    },
    "sync_info": {
      "latest_block_hash": "hex-hash",
      "latest_app_hash": "hex-hash",
      "latest_block_height": "12345",
      "latest_block_time": "2026-01-01T00:00:00Z",
      "earliest_block_height": "1",
      "earliest_block_hash": "hex-hash",
      "catching_up": false
    },
    "validator_info": {
      "address": "hex-address",
      "pub_key": { "type": "tendermint/PubKeyEd25519", "value": "base64" },
      "voting_power": "100"
    }
  }
}

三、REST API

3.1 Cosmos SDK 标准 REST 端点

所有 REST 端点基础 URL:http://localhost:1317

Bank

GET /cosmos/bank/v1beta1/balances/{address}

查询地址所有余额。

curl http://localhost:1317/cosmos/bank/v1beta1/balances/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3

响应:

{
  "balances": [
    { "denom": "umsg", "amount": "1000000000000000000" }
  ],
  "pagination": { "next_key": null, "total": "1" }
}
GET /cosmos/bank/v1beta1/supply

查询总供应量。

curl http://localhost:1317/cosmos/bank/v1beta1/supply

响应:

{
  "supply": [
    { "denom": "umsg", "amount": "1000000000000000000000" }
  ]
}

Staking

GET /cosmos/staking/v1beta1/validators

列出验证者。

curl "http://localhost:1317/cosmos/staking/v1beta1/validators?status=BOND_STATUS_BONDED"
GET /cosmos/staking/v1beta1/delegations/{delegator_addr}

查询委托人的所有委托。

curl http://localhost:1317/cosmos/staking/v1beta1/delegations/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3

Distribution

GET /cosmos/distribution/v1beta1/delegators/{delegator_addr}/rewards

查询委托奖励。

curl http://localhost:1317/cosmos/distribution/v1beta1/delegators/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3/rewards

Governance

GET /cosmos/gov/v1beta1/proposals

查询治理提案列表。

curl http://localhost:1317/cosmos/gov/v1beta1/proposals

CosmWasm

GET /cosmwasm/wasm/v1/code/{code_id}

获取代码信息。

curl http://localhost:1317/cosmwasm/wasm/v1/code/1
GET /cosmwasm/wasm/v1/contract/{address}

获取合约信息。

curl http://localhost:1317/cosmwasm/wasm/v1/contract/msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal
GET /cosmwasm/wasm/v1/contract/{address}/smart/{query}

执行合约智能查询。

# base64 编码的 {"get_count":{}}
curl "http://localhost:1317/cosmwasm/wasm/v1/contract/msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal/smart/eyJnZXRfY291bnQiOiB7fX0="
POST /cosmwasm/wasm/v1/code

上传合约代码(未签名的交易体)。

curl -X POST http://localhost:1317/cosmwasm/wasm/v1/code \
  -H "Content-Type: application/json" \
  -d '{
    "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "wasm_byte_code": "base64...",
    "instantiate_permission": { "permission": "Everybody" }
  }'
POST /cosmwasm/wasm/v1/contract/{address}

执行合约(未签名的交易体)。

curl -X POST http://localhost:1317/cosmwasm/wasm/v1/contract/msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal \
  -H "Content-Type: application/json" \
  -d '{
    "sender": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
    "msg": "base64-encoded-execute-msg",
    "funds": []
  }'

3.2 公开查询 API (/api/v1/*)

这些是 MSG Chain 自定义的公开查询端点。

GET /api/v1/chain/info

查询链基本信息。

curl http://localhost:1317/api/v1/chain/info

响应:

{
  "chain_id": "msg-chain-1",
  "height": 12345,
  "block_time": "5s",
  "consensus": "round_robin_dar",
  "signature_scheme": "Dilithium5",
  "node_version": "0.1.0",
  "genesis_time": "2026-01-01T00:00:00Z"
}
GET /api/v1/chain/params

查询模块参数。

curl http://localhost:1317/api/v1/chain/params

响应:

{
  "staking": {
    "unbonding_time": "1814400s",
    "max_validators": 100,
    "max_entries": 7,
    "historical_entries": 10000,
    "bond_denom": "umsg"
  },
  "distribution": {
    "community_tax": "0.020000000000000000",
    "base_proposer_reward": "0.010000000000000000",
    "bonus_proposer_reward": "0.040000000000000000",
    "withdraw_addr_enabled": true
  },
  "wasm": {
    "max_wasm_code_size": 819200,
    "instantiate_permission": "Everybody"
  }
}
GET /api/v1/account/{address}

查询账户详情。

curl http://localhost:1317/api/v1/account/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3

响应:

{
  "address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "balance": {
    "umsg": "1000000000000000000"
  },
  "account_number": 0,
  "sequence": 5,
  "pub_key_type": "/cosmos.crypto.dilithium.PubKey"
}
GET /api/v1/tx/{hash}

查询交易详情。

curl http://localhost:1317/api/v1/tx/0xABCDEF1234567890

响应:

{
  "hash": "0xABCDEF1234567890",
  "height": 12345,
  "success": true,
  "gas_used": 123456,
  "gas_wanted": 200000,
  "fee": [{ "denom": "umsg", "amount": "5000" }],
  "messages": [
    {
      "@type": "/cosmos.bank.v1beta1.MsgSend",
      "from": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
      "to": "msg1...",
      "amount": [{ "denom": "umsg", "amount": "1000000" }]
    }
  ],
  "timestamp": "2026-01-01T00:00:00Z"
}
GET /api/v1/validator/set

查询活跃验证者集。

curl http://localhost:1317/api/v1/validator/set
GET /api/v1/emission/rate

查询当前 emission 速率。

curl http://localhost:1317/api/v1/emission/rate
GET /api/v1/staking/pool

查询质押池统计。

curl http://localhost:1317/api/v1/staking/pool

响应:

{
  "bonded_tokens": "500000000000000000000",
  "not_bonded_tokens": "100000000000000000000",
  "total_supply": "1000000000000000000000",
  "bonded_ratio": "0.50",
  "inflation": "0.08"
}
GET /api/v1/distribution/params

查询分发参数。

curl http://localhost:1317/api/v1/distribution/params
GET /api/v1/gov/proposals

查询治理提案。

curl "http://localhost:1317/api/v1/gov/proposals?status=VOTING_PERIOD"
GET /api/v1/agent/contracts

查询已知的 Agent 合约列表。

curl http://localhost:1317/api/v1/agent/contracts
GET /api/v1/agent/contract/{address}

查询指定 Agent 合约信息。

curl http://localhost:1317/api/v1/agent/contract/msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal

四、合约 API

4.1 合约地址解析

MSG Chain 使用 genesis_registry_v1 合约作为合约注册中心。所有系统合约通过 canonical key 寻址:

# 通过 genesis_registry 解析合约地址
curl -X POST http://localhost:26657/cosmwasm.wasm.v1.Query/SmartContractState \
  -H "Content-Type: application/json" \
  -d '{
    "address": "msg1...genesisRegistry",
    "query_data": "'$(echo -n '{"resolve_canonical":{"key":"genesis_registry"}}' | base64 -w0)'"
  }'

已知 canonical keys:

Canonical Key 合约 是否在 genesis 中
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) agent_registry_v1 ❌
— 动态解析 agent_payment_v1 ❌
— 动态解析 micropayment_session_v1 ❌

4.2 ai_agent_constitution_v1

AI Agent 宪章合约,定义 Agent 的行为边界。

ExecuteMsg — Rust 结构体定义

/// 更新完整宪章
pub struct UpdateConstitution {
    pub constitution: String,
    pub version: String,
    pub constitution_hash: String,
}

/// 添加策略规则
pub struct AddRule {
    pub policy_id: String,
    pub rule: Rule,
    pub rule_id: String,
}

/// 删除规则
pub struct RemoveRule {
    pub rule_id: String,
}

/// 更新规则
pub struct UpdateRule {
    pub rule_id: String,
    pub rule: Rule,
}

/// 设置活跃状态
pub struct SetActive {
    pub active: bool,
}

pub struct Rule {
    pub action: String,
    pub risk_tier: RiskTier,
    pub allowed: bool,
    pub required_controls: Vec<String>,
    pub max_amount: Option<Uint128>,
    pub budget_id: Option<String>,
}

pub enum RiskTier {
    Low,
    Medium,
    High,
}

QueryMsg — Rust 结构体定义

/// 获取完整宪章
pub struct GetConstitution {}

/// 获取指定宪章版本
pub struct GetConstitution {
    pub version: String,
}

/// 获取单条规则
pub struct GetRule {
    pub rule_id: String,
}

/// 列出所有规则
pub struct ListRules {
    pub pagination: Option<Pagination>,
}

/// 检查动作是否被允许(核心方法)
pub struct IsActionAllowed {
    pub agent_id: String,
    pub action: String,
    pub risk_tier: RiskTier,
    pub amount: Option<Uint128>,
}

/// 获取宪章活跃状态
pub struct GetActiveStatus {}

// 响应类型
pub struct ConstitutionResponse {
    pub constitution: String,
    pub version: String,
    pub constitution_hash: String,
    pub active: bool,
}

pub struct CheckActionResponse {
    pub allowed: bool,
    pub decision: String,
    pub reasons: Vec<String>,
    pub required_controls: Vec<String>,
    pub active_constitution_version: String,
    pub active_constitution_hash: String,
}

4.3 agent_payment_v1

AI Agent 支付合约,支持 AIPAY 全生命周期支付。

ExecuteMsg — Rust 结构体定义

/// 创建支付会话
pub struct CreateSession {
    pub session_id: String,
    pub payer: String,
    pub payee: String,
    pub agent_id: String,
    pub amount: Uint128,
    pub asset: String,
    pub terms_hash: String,
    pub expiry: u64,
}

/// 向会话充值
pub struct FundSession {
    pub session_id: String,
    pub amount: Uint128,
}

/// 释放支付
pub struct ReleasePayment {
    pub payment_id: String,
    pub release_hash: String,
}

/// 争议支付
pub struct DisputePayment {
    pub payment_id: String,
    pub reason: String,
    pub proof_hash: String,
}

/// 关闭支付会话
pub struct CloseSession {
    pub session_id: String,
    pub close_receipt_hash: String,
}

/// 添加里程碑
pub struct AddMilestone {
    pub session_id: String,
    pub milestone: Milestone,
}

/// 完成里程碑
pub struct CompleteMilestone {
    pub session_id: String,
    pub milestone_id: String,
    pub completion_hash: String,
}

pub struct Milestone {
    pub milestone_id: String,
    pub description: String,
    pub amount: Uint128,
    pub due_by: u64,
}

QueryMsg — Rust 结构体定义

/// 获取支付会话详情
pub struct GetSession {
    pub session_id: String,
}

/// 获取 Agent 的所有会话
pub struct GetAgentSessions {
    pub agent_id: String,
    pub pagination: Option<Pagination>,
}

/// 列出所有支付会话
pub struct ListSessions {
    pub pagination: Option<Pagination>,
}

/// 获取余额
pub struct GetBalance {
    pub address: String,
    pub asset: Option<String>,
}

/// 获取争议状态
pub struct GetDisputeStatus {
    pub payment_id: String,
}

// 响应类型
pub struct SessionResponse {
    pub session_id: String,
    pub payer: String,
    pub payee: String,
    pub agent_id: String,
    pub amount: Uint128,
    pub funded: Uint128,
    pub released: Uint128,
    pub status: SessionStatus,
    pub asset: String,
    pub terms_hash: String,
    pub created_at: u64,
    pub expires_at: u64,
    pub milestones: Vec<MilestoneResponse>,
}

pub enum SessionStatus {
    Pending,
    Active,
    Completed,
    Disputed,
    Cancelled,
}

4.4 agent_registry_v1

Agent 注册与发现合约。

ExecuteMsg — Rust 结构体定义

/// 注册新 Agent
pub struct RegisterAgent {
    pub agent_id: String,
    pub name: Option<String>,
    pub owner: String,
    pub capabilities: Vec<String>,
    pub endpoint: Option<String>,
    pub price_model: Option<PriceModel>,
    pub natural_language: Option<String>,
    pub prompt: Option<String>,
    pub node_executes_llm: Option<bool>,
    pub consensus_llm_parse: Option<bool>,
}

/// 更新 Agent 信息
pub struct UpdateAgent {
    pub agent_id: String,
    pub name: Option<String>,
    pub capabilities: Option<Vec<String>>,
    pub endpoint: Option<String>,
    pub price_model: Option<PriceModel>,
}

/// 注销 Agent
pub struct DeregisterAgent {
    pub agent_id: String,
    pub reason: Option<String>,
}

/// 更新元数据
pub struct UpdateMetadata {
    pub agent_id: String,
    pub metadata: AgentMetadata,
}

/// 设置状态(active/paused/suspended)
pub struct SetStatus {
    pub agent_id: String,
    pub status: AgentStatus,
}

pub struct PriceModel {
    pub price_type: Option<String>,
    pub price: Option<Uint128>,
    pub currency: Option<String>,
}

pub struct AgentMetadata {
    pub natural_language: Option<String>,
    pub prompt: Option<String>,
    pub node_executes_llm: Option<bool>,
    pub consensus_llm_parse: Option<bool>,
}

QueryMsg — Rust 结构体定义

/// 查询单 Agent
pub struct GetAgent {
    pub agent_id: String,
}

/// 列出所有 Agent
pub struct ListAgents {
    pub pagination: Option<Pagination>,
}

/// 按 owner 查询
pub struct GetAgentsByOwner {
    pub owner: String,
    pub pagination: Option<Pagination>,
}

/// 按 DID 查询
pub struct GetAgentByDID {
    pub did: String,
}

/// 按状态列出
pub struct ListAgentsByStatus {
    pub status: AgentStatus,
    pub pagination: Option<Pagination>,
}

// 响应类型
pub struct AgentResponse {
    pub agent_id: String,
    pub name: String,
    pub owner: String,
    pub capabilities: Vec<String>,
    pub endpoint: String,
    pub price_model: Option<PriceModel>,
    pub status: AgentStatus,
    pub registered_height: u64,
    pub updated_at: u64,
    pub metadata: Option<AgentMetadata>,
    pub tx_hash: Option<String>,
}

pub enum AgentStatus {
    Active,
    Paused,
    Suspended,
}

4.5 aidid_did_registry_v1

AI 去中心化身份 (DID) 注册合约,基于 W3C DID 标准。

ExecuteMsg — Rust 结构体定义

/// 创建 DID
pub struct CreateDID {
    pub did: String,
    pub document: DidDocument,
    pub verification_method_id: String,
    pub signature: String,
}

/// 更新 DID
pub struct UpdateDID {
    pub did: String,
    pub document: DidDocument,
    pub signature: String,
}

/// 停用 DID
pub struct DeactivateDID {
    pub did: String,
    pub signature: String,
}

/// 添加验证方法
pub struct AddVerificationMethod {
    pub did: String,
    pub verification_method: VerificationMethod,
    pub signature: String,
}

/// 移除验证方法
pub struct RemoveVerificationMethod {
    pub did: String,
    pub verification_method_id: String,
    pub signature: String,
}

/// 添加服务端点
pub struct AddService {
    pub did: String,
    pub service: Service,
    pub signature: String,
}

/// 移除服务端点
pub struct RemoveService {
    pub did: String,
    pub service_id: String,
    pub signature: String,
}

QueryMsg — Rust 结构体定义

/// 解析 DID 文档
pub struct ResolveDID {
    pub did: String,
}

/// 检查 DID 是否活跃
pub struct CheckDIDActive {
    pub did: String,
}

/// 按 controller 列出 DID
pub struct ListDIDsByController {
    pub controller: String,
    pub pagination: Option<Pagination>,
}

/// 获取 DID 元数据
pub struct GetDIDMetadata {
    pub did: String,
}

// 核心类型
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,
    pub public_key_multibase: String,
}

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

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

4.6 micropayment_session_v1

微支付会话合约,支持按秒计费。

ExecuteMsg — Rust 结构体定义

/// 打开支付通道
pub struct OpenChannel {
    pub channel_id: String,
    pub payer: String,
    pub payee: String,
    pub rate_per_sec: Uint128,
    pub balance: Uint128,
    pub asset: String,
    pub terms_hash: String,
    pub expiry: u64,
}

/// 存入资金
pub struct Deposit {
    pub channel_id: String,
    pub amount: Uint128,
}

/// 按秒扣费(Agent 调用)
pub struct Claim {
    pub channel_id: String,
    pub elapsed_secs: u64,
    pub receipt_hash: String,
}

/// 关闭通道
pub struct CloseChannel {
    pub channel_id: String,
    pub close_receipt_hash: String,
}

/// 延长过期时间
pub struct ExtendExpiry {
    pub channel_id: String,
    pub new_expiry: u64,
}

/// 更新通道状态(争议解决)
pub struct UpdateState {
    pub channel_id: String,
    pub new_balance: Uint128,
    pub proof_hash: String,
}

QueryMsg — Rust 结构体定义

/// 查询通道详情
pub struct GetChannel {
    pub channel_id: String,
}

/// 按参与者列出通道
pub struct ListChannelsByParticipant {
    pub participant: String,
    pub pagination: Option<Pagination>,
}

/// 查询通道状态
pub struct GetChannelState {
    pub channel_id: String,
}

/// 查询通道余额
pub struct GetChannelBalance {
    pub channel_id: String,
}

// 响应类型
pub struct ChannelResponse {
    pub channel_id: String,
    pub payer: String,
    pub payee: String,
    pub rate_per_sec: Uint128,
    pub balance: Uint128,
    pub charged_total: Uint128,
    pub asset: String,
    pub status: ChannelStatus,
    pub terms_hash: String,
    pub created_at: u64,
    pub expiry: u64,
    pub last_charge_time: u64,
}

pub enum ChannelStatus {
    Active,
    Closed,
    Exhausted,
    Disputed,
}

五、Agent API

5.1 概述

Agent API 是 MSG Chain 为 AI Agent 提供的高层 REST/WebSocket 接口,位于 http://localhost:8080。共 5 个分组、18 个端点。

所有写操作需要 X-API-Key 头。Stub 端点在响应中包含 X-MSG-Stub: true 头。

5.2 Group 1: Agent Query

1 POST /api/v1/agent/query

查询 Agent 状态并获取响应。

描述: 向 Agent 发送查询并接收处理结果。

请求头:

头 值
Content-Type application/json

请求体:

{
  "agent_id": "my-agent-001",
  "query": "What is your current balance?",
  "context": {
    "session_id": "sess-001",
    "user_id": "user-001"
  }
}

响应:

{
  "agent_id": "my-agent-001",
  "response": "My current balance is 500 MSG.",
  "metadata": {
    "model": "gpt-4",
    "processing_time_ms": 1234,
    "tokens_used": 150
  }
}

curl:

curl -X POST http://localhost:8080/api/v1/agent/query \
  -H "Content-Type: application/json" \
  -d '{
    "agent_id": "my-agent-001",
    "query": "What is your balance?"
  }'

2 GET /api/v1/agent/{agent_id}/status

获取 Agent 状态。

描述: 返回 Agent 的当前运行状态、健康检查和最近活动时间。

请求参数(路径):

参数 类型 说明
agent_id string Agent ID

响应:

{
  "agent_id": "my-agent-001",
  "status": "running",
  "is_online": true,
  "last_heartbeat": "2026-01-01T00:10:00Z",
  "current_task": "processing_query",
  "uptime_seconds": 3600,
  "version": "1.0.0"
}

curl:

curl http://localhost:8080/api/v1/agent/my-agent-001/status

3 GET /api/v1/agent/{agent_id}/history

获取 Agent 执行历史。

描述: 返回 Agent 最近的操作执行历史记录。

请求参数(查询字符串):

参数 类型 说明
limit int (optional) 返回条数 (默认 20)
offset int (optional) 偏移量
action string (optional) 按动作筛选

响应:

{
  "agent_id": "my-agent-001",
  "history": [
    {
      "tx_hash": "0xABCD...",
      "action": "transfer",
      "status": "success",
      "timestamp": "2026-01-01T00:05:00Z",
      "details": {
        "from": "msg1...",
        "to": "msg1...",
        "amount": "1000000"
      }
    }
  ],
  "total": 42,
  "limit": 20,
  "offset": 0
}

curl:

curl "http://localhost:8080/api/v1/agent/my-agent-001/history?limit=10&action=transfer"

5.3 Group 2: Agent Events

4 POST /api/v1/agent/events/subscribe

订阅 Agent 事件(WebSocket 升级)。

描述: 建立 WebSocket 连接以接收实时事件。请求会触发 HTTP 到 WebSocket 的协议升级。

请求体:

{
  "event_types": ["Transfer", "ContractExecute", "BlockProduced"],
  "filter": {
    "agent_id": "my-agent-001"
  }
}

WebSocket 消息格式:

{
  "type": "Transfer",
  "data": {
    "from": "msg1...",
    "to": "msg1...",
    "amount": "1000000",
    "tx_hash": "0xABCD..."
  },
  "timestamp": 1704067200
}

Node.js 客户端:

const ws = new WebSocket("ws://localhost:8080/api/v1/agent/events/subscribe");

ws.onopen = () => {
  ws.send(JSON.stringify({
    event_types: ["Transfer", "ContractExecute"],
    filter: { agent_id: "my-agent-001" }
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(`Event: ${msg.type}`, msg.data);
};

5 POST /api/v1/agent/events/unsubscribe

取消事件订阅。

请求体:

{
  "session_id": "ws-session-uuid",
  "event_types": ["Transfer"]
}

响应:

{
  "status": "unsubscribed",
  "session_id": "ws-session-uuid"
}

6 POST /api/v1/agent/events/replay

重放历史事件。

描述: 获取过去指定时间范围内的事件日志。

请求体:

{
  "event_types": ["Transfer"],
  "from_timestamp": 1704060000,
  "to_timestamp": 1704067200,
  "limit": 100
}

响应:

{
  "events": [
    {
      "type": "Transfer",
      "data": { "from": "msg1...", "to": "msg1...", "amount": "1000000" },
      "timestamp": 1704063600,
      "block_height": 12345
    }
  ],
  "total": 1
}

5.4 Group 3: AI Oracle

7 POST /api/v1/agent/oracle/request

请求 AI Oracle 推理。

描述: 向 AI Oracle 提交推理请求。Oracle 将调用外部 AI 模型进行推理并返回结果。

请求体:

{
  "model": "gpt-4",
  "prompt": "Analyze this transaction pattern...",
  "input_data": {
    "transactions": [...]
  },
  "parameters": {
    "temperature": 0.7,
    "max_tokens": 1000
  }
}

响应:

{
  "request_id": "req-uuid-1234",
  "status": "pending",
  "estimated_completion_ms": 5000
}

8 GET /api/v1/agent/oracle/result/{request_id}

获取 Oracle 推理结果。

curl:

curl http://localhost:8080/api/v1/agent/oracle/result/req-uuid-1234

响应(处理中):

{
  "request_id": "req-uuid-1234",
  "status": "processing",
  "progress": 0.6
}

响应(完成):

{
  "request_id": "req-uuid-1234",
  "status": "completed",
  "result": {
    "analysis": "Pattern detected: ...",
    "confidence": 0.95,
    "recommendation": "approve"
  },
  "proof": {
    "model_id": "gpt-4-0613",
    "inference_hash": "0xhash...",
    "signature": "dilithium5-sig..."
  },
  "processing_time_ms": 4321
}

9 POST /api/v1/agent/oracle/verify

验证 Oracle 推理证明。

请求体:

{
  "request_id": "req-uuid-1234",
  "proof": {
    "model_id": "gpt-4-0613",
    "inference_hash": "0xhash...",
    "signature": "dilithium5-sig..."
  }
}

响应:

{
  "valid": true,
  "verified_by": "msgvaloper1...",
  "verified_at": "2026-01-01T00:00:00Z"
}

5.5 Group 4: Agent Wallet

10 POST /api/v1/agent/wallet/create

创建 Agent 钱包。

请求头:

头 值
X-API-Key your-api-key
Content-Type application/json

请求体:

{
  "agent_id": "my-agent-001",
  "owner": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

响应:

{
  "agent_id": "my-agent-001",
  "wallet_address": "msg1...agent-wallet",
  "created_at": "2026-01-01T00:00:00Z",
  "initial_balance": "0"
}

11 GET /api/v1/agent/wallet/{agent_id}/balance

查询 Agent 钱包余额。

curl:

curl -H "X-API-Key: your-api-key" \
  http://localhost:8080/api/v1/agent/wallet/my-agent-001/balance

响应:

{
  "agent_id": "my-agent-001",
  "wallet_address": "msg1...agent-wallet",
  "balances": [
    { "denom": "umsg", "amount": "500000000000000000" }
  ],
  "escrow_balance": "100000000000000000"
}

12 POST /api/v1/agent/wallet/transfer

从 Agent 钱包转账。

请求体:

{
  "agent_id": "my-agent-001",
  "to": "msg1...recipient",
  "amount": "1000000",
  "denom": "umsg",
  "justification": "Payment for code review service",
  "idempotency_key": "txn-uuid-1234"
}

响应:

{
  "status": "pending_approval",
  "approval_gate": "secret_injection",
  "next_step": "request_operator_signer",
  "tx_hash": null
}

注意: Agent 钱包的写操作受"受保护钱包操作"模式管控,可能需要额外审批。


13 GET /api/v1/agent/wallet/{agent_id}/transactions

查询 Agent 钱包交易历史。

curl:

curl -H "X-API-Key: your-api-key" \
  "http://localhost:8080/api/v1/agent/wallet/my-agent-001/transactions?limit=10"

响应:

{
  "agent_id": "my-agent-001",
  "transactions": [
    {
      "tx_hash": "0xABCD...",
      "type": "outgoing",
      "to": "msg1...",
      "amount": "1000000",
      "denom": "umsg",
      "status": "confirmed",
      "timestamp": "2026-01-01T00:05:00Z",
      "height": 12345
    }
  ],
  "total": 42
}

5.6 Group 5: MPC (Multi-Party Computation)

14 POST /api/v1/agent/mpc/sign

发起 MPC 签名。

描述: 启动多方计算签名流程。MSG Chain 的 MPC 支持 Dilithium-5 后量子分布式签名。

请求体:

{
  "key_id": "mpc-key-001",
  "payload": "base64-encoded-payload",
  "participants": ["msg1...", "msg1..."],
  "threshold": 2,
  "algorithm": "Dilithium5"
}

响应:

{
  "session_id": "mpc-sess-uuid",
  "status": "initiated",
  "participants_required": 2,
  "participants_ready": 0
}

15 POST /api/v1/agent/mpc/submit

提交 MPC 部分签名。

请求体:

{
  "session_id": "mpc-sess-uuid",
  "participant": "msg1...",
  "partial_signature": "base64-encoded-partial-sig"
}

响应:

{
  "session_id": "mpc-sess-uuid",
  "status": "awaiting_more",
  "participants_submitted": 1,
  "threshold": 2
}

16 POST /api/v1/agent/mpc/aggregate

聚合 MPC 签名。

请求体:

{
  "session_id": "mpc-sess-uuid"
}

响应:

{
  "session_id": "mpc-sess-uuid",
  "status": "completed",
  "aggregated_signature": "base64-encoded-aggregated-sig",
  "public_key": "base64-encoded-public-key"
}

5.7 Group 6: Agent Payment

17 POST /api/v1/agent/payment/create-session

创建微支付会话。

描述: 创建基于按秒计费的微支付会话,用于 Agent 间的实时服务计费。

请求体:

{
  "agent_id": "my-agent-001",
  "payer": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3",
  "payee": "msg1...service-provider",
  "rate_per_sec": "100",
  "initial_balance": "10000000",
  "asset": "umsg",
  "terms_hash": "0xterms-hash"
}

响应:

{
  "session_id": "pay-sess-uuid",
  "status": "active",
  "rate_per_sec": "100",
  "balance": "10000000",
  "created_at": "2026-01-01T00:00:00Z"
}

18 POST /api/v1/agent/payment/close-session

关闭微支付会话。

描述: 关闭活跃的微支付会话,结算未付余额。

请求体:

{
  "session_id": "pay-sess-uuid",
  "close_receipt_hash": "0xreceipt-hash"
}

响应:

{
  "session_id": "pay-sess-uuid",
  "status": "closed",
  "total_charged": "500000",
  "remaining_balance": "9500000",
  "refund_address": "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3"
}

六、错误码大全

6.1 通用错误码

Code 名称 描述 HTTP 状态码
0 SUCCESS_OK 成功 200
1 AGENT_STUB_SUCCESS Stub 端点成功响应(携带 X-MSG-Stub=true 头) 200
2 STUB_NOT_YET_IMPLEMENTED 功能尚未实现(携带 X-MSG-Stub=true 头) 501
3 UNAUTHORIZED 未授权,缺少或无效的 API Key 401
4 INSUFFICIENT_FUNDS 余额不足,无法完成操作 402
5 CONTRACT_EXECUTION_FAILED 合约执行失败,检查 raw_log 获取详情 500
6 QUERY_TIMEOUT_OR_EMPTY 查询超时或返回空结果 404
7 INVALID_PARAMETER 请求参数无效 400
8 DAO_TIMELOCK_NOT_FINISHED DAO 时间锁期间未结束 403
9 HIGH_VALUE_THRESHOLD_NOT_MET 高价值交易门槛未满足(需要额外签名) 403
10 AGENT_NOT_FOUND 未找到指定 Agent 404
11 AGENT_ALREADY_REGISTERED Agent 已经注册 409
12 CONSTITUTION_VIOLATION 动作违反 Agent 宪章 403
13 SESSION_EXPIRED 支付会话已过期 410
14 SESSION_LIMIT_EXCEEDED 支付会话超限 429
15 INVALID_SIGNATURE Dilithium-5 签名验证失败 401
16 DUPLICATE_NONCE 检测到重复 Nonce 409
17 RATE_LIMIT_EXCEEDED 请求频率超限 429

6.2 Stub 端点识别

所有 stub 端点的 HTTP 响应包含 X-MSG-Stub: true 头,客户端应据此判断功能是否真实可用。

// Stub 端点检测示例
async function detectStub(response: Response): Promise<boolean> {
  return response.headers.get("X-MSG-Stub") === "true";
}

6.3 错误响应格式

{
  "error": {
    "code": 3,
    "name": "UNAUTHORIZED",
    "message": "未授权:缺少 X-API-Key 请求头",
    "details": "写操作需要提供有效的 API Key。请在 HTTP 头中添加 X-API-Key。"
  },
  "request_id": "req-uuid-1234"
}

七、CosmJS 集成示例

7.1 安装依赖

npm install @cosmjs/cosmwasm-stargate \
  @cosmjs/proto-signing \
  @cosmjs/encoding \
  @cosmjs/stargate \
  @cosmjs/tendermint-rpc

7.2 连接 MSG Chain

只读客户端 (CosmWasmClient)

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

const RPC_ENDPOINT = "http://localhost:26657";

async function connectReadOnly(): Promise<CosmWasmClient> {
  const client = await CosmWasmClient.connect(RPC_ENDPOINT);

  // 验证连接
  const height = await client.getHeight();
  const chainId = await client.getChainId();
  console.log(`Connected to ${chainId} at height ${height}`);

  return client;
}

签名客户端 (SigningCosmWasmClient)

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

const RPC_ENDPOINT = "http://localhost:26657";
const CHAIN_ID = "msg-chain-1";
const PREFIX = "msg";

async function connectSigning(
  mnemonic: string
): Promise<SigningCosmWasmClient> {
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: PREFIX,
  });

  const client = await SigningCosmWasmClient.connectWithSigner(
    RPC_ENDPOINT,
    wallet,
    {
      gasPrice: GasPrice.fromString("1000000000attoMSG"),
    }
  );

  const [account] = await wallet.getAccounts();
  console.log(`Connected with address: ${account.address}`);

  return client;
}

7.3 查询操作

查询银行余额

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

async function queryBalance(
  client: CosmWasmClient,
  address: string
) {
  // 查询指定代币余额
  const balance = await client.getBalance(address, "umsg");
  console.log(`Balance: ${balance.amount} ${balance.denom}`);

  // 查询所有余额
  const allBalances = await client.getAllBalances(address);
  console.log("All balances:", allBalances);

  return { balance, allBalances };
}

查询合约状态(Smart Query)

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

async function queryContractSmart<T>(
  client: CosmWasmClient,
  contractAddress: string,
  queryMsg: Record<string, unknown>
): Promise<T> {
  try {
    const result = await client.queryContractSmart(contractAddress, queryMsg);
    return result as T;
  } catch (error) {
    console.error(`Smart query failed for ${contractAddress}:`, error);
    throw error;
  }
}

// 查询计数器合约
interface GetCountResponse {
  count: number;
}

async function getCount(
  client: CosmWasmClient,
  contractAddress: string
): Promise<number> {
  const result = await queryContractSmart<GetCountResponse>(contractAddress, {
    get_count: {},
  });
  return result.count;
}

7.4 交易操作

执行合约交易

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

interface ExecuteResult {
  transactionHash: string;
  gasUsed: number;
  height: number;
  rawLog: string;
}

async function executeContract(
  client: SigningCosmWasmClient,
  senderAddress: string,
  contractAddress: string,
  executeMsg: Record<string, unknown>,
  funds?: { denom: string; amount: string }[]
): Promise<ExecuteResult> {
  const result = await client.execute(
    senderAddress,
    contractAddress,
    executeMsg,
    "auto",
    undefined,
    funds
  );

  return {
    transactionHash: result.transactionHash,
    gasUsed: result.gasUsed,
    height: result.height,
    rawLog: result.rawLog,
  };
}

// 使用示例:递增计数器
async function incrementCounter(
  client: SigningCosmWasmClient,
  sender: string,
  contractAddress: string
) {
  const result = await executeContract(client, sender, contractAddress, {
    increment: {},
  });
  console.log(`Transaction sent: ${result.transactionHash}`);
  console.log(`Gas used: ${result.gasUsed}`);
  return result;
}

发送代币转账交易

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

async function sendTokens(
  client: SigningCosmWasmClient,
  senderAddress: string,
  recipientAddress: string,
  amount: string,
  denom: string = "umsg"
) {
  const result = await client.sendTokens(
    senderAddress,
    recipientAddress,
    coins(amount, denom),
    "auto"
  );

  console.log(`Transfer sent: ${result.transactionHash}`);
  return result;
}

广播已签名的交易

import { SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { TxRaw } from "cosmjs-types/cosmos/tx/v1beta1/tx";

async function broadcastTx(
  client: SigningCosmWasmClient,
  txBytes: Uint8Array
) {
  // 使用 BroadcastTx Sync 模式
  const result = await client.broadcastTx(
    txBytes,
    60000 // 60s 超时
  );

  if (result.code !== 0) {
    throw new Error(`Transaction failed: ${result.rawLog}`);
  }

  console.log(`Transaction broadcast: ${result.transactionHash}`);
  return result;
}

7.5 治理提案操作

查询治理提案

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

interface Proposal {
  proposal_id: string;
  content: {
    "@type": string;
    title: string;
    description: string;
  };
  status: string;
  final_tally_result: {
    yes: string;
    abstain: string;
    no: string;
    no_with_veto: string;
  };
  submit_time: string;
  deposit_end_time: string;
  total_deposit: Array<{ denom: string; amount: string }>;
  voting_start_time: string;
  voting_end_time: string;
}

async function queryProposals(
  client: CosmWasmClient,
  status?: "PROPOSAL_STATUS_VOTING_PERIOD" | "PROPOSAL_STATUS_PASSED" | "PROPOSAL_STATUS_REJECTED"
): Promise<Proposal[]> {
  // 通过 Tendermint RPC 查询
  const proposals = await client.queryContractSmart(
    "msg1...govContractAddress",
    {
      list_proposals: {
        status: status || "PROPOSAL_STATUS_VOTING_PERIOD",
      },
    }
  );
  return proposals;
}

7.6 Keplr 钱包集成

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

// 定义 MSG Chain 链配置
const msgChainConfig = {
  chainId: "msg-chain-1",
  chainName: "MSG Chain",
  rpc: "http://localhost:26657",
  rest: "http://localhost:1317",
  bip44: { coinType: 118 },
  bech32Config: {
    bech32PrefixAccAddr: "msg",
    bech32PrefixAccPub: "msgpub",
    bech32PrefixValAddr: "msgvaloper",
    bech32PrefixValPub: "msgvaloperpub",
    bech32PrefixConsAddr: "msgvalcons",
    bech32PrefixConsPub: "msgvalconspub",
  },
  currencies: [
    {
      coinDenom: "MSG",
      coinMinimalDenom: "umsg",
      coinDecimals: 18,
    },
  ],
  feeCurrencies: [
    {
      coinDenom: "MSG",
      coinMinimalDenom: "umsg",
      coinDecimals: 18,
      gasPriceStep: { low: 1000000000, average: 1000000000, high: 1000000000 },
    },
  ],
  stakeCurrency: {
    coinDenom: "MSG",
    coinMinimalDenom: "umsg",
    coinDecimals: 18,
  },
};

// 通过 Keplr 获取签名客户端
async function getKeplrClient(): Promise<{
  client: SigningCosmWasmClient;
  address: string;
}> {
  if (!window.keplr) {
    throw new Error("请安装 Keplr 钱包扩展");
  }

  await window.keplr.experimentalSuggestChain(msgChainConfig);
  await window.keplr.enable("msg-chain-1");

  const offlineSigner = window.keplr.getOfflineSigner("msg-chain-1");
  const accounts = await offlineSigner.getAccounts();
  const address = accounts[0].address;

  const client = await SigningCosmWasmClient.connectWithSigner(
    "http://localhost:26657",
    offlineSigner,
    {
      gasPrice: GasPrice.fromString("1000000000attoMSG"),
    }
  );

  return { client, address };
}

7.7 Agent API 交互封装

// agent-api-client.ts — Agent API 完整客户端
interface AgentAPIConfig {
  baseUrl: string;
  apiKey?: string;
}

class AgentAPIClient {
  private config: AgentAPIConfig;

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

  private async request<T>(
    path: string,
    options: RequestInit = {}
  ): Promise<T> {
    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: { ...headers, ...(options.headers as Record<string, string>) },
    });

    // 检查 Stub 标记
    const isStub = res.headers.get("X-MSG-Stub") === "true";

    if (!res.ok) {
      const body = await res.json().catch(() => ({}));
      const error = new Error(
        `Agent API error ${res.status}: ${body.error?.message || res.statusText}`
      );
      (error as any).code = body.error?.code;
      (error as any).isStub = isStub;
      throw error;
    }

    if (isStub) {
      console.warn(`[Stub] ${path} — 此端点尚未完全实现`);
    }

    return res.json();
  }

  // Agent Query
  async query(agentId: string, query: string, context?: Record<string, unknown>) {
    return this.request("/api/v1/agent/query", {
      method: "POST",
      body: JSON.stringify({ agent_id: agentId, query, context }),
    });
  }

  async getStatus(agentId: string) {
    return this.request(`/api/v1/agent/${agentId}/status`);
  }

  async getHistory(agentId: string, params?: { limit?: number; action?: string }) {
    const query = new URLSearchParams();
    if (params?.limit) query.set("limit", String(params.limit));
    if (params?.action) query.set("action", params.action);
    return this.request(`/api/v1/agent/${agentId}/history?${query}`);
  }

  // Wallet
  async createWallet(agentId: string, owner: string) {
    return this.request("/api/v1/agent/wallet/create", {
      method: "POST",
      body: JSON.stringify({ agent_id: agentId, owner }),
    });
  }

  async getBalance(agentId: string) {
    return this.request(`/api/v1/agent/wallet/${agentId}/balance`);
  }

  async transfer(agentId: string, to: string, amount: string, justification: string) {
    return this.request("/api/v1/agent/wallet/transfer", {
      method: "POST",
      body: JSON.stringify({ agent_id: agentId, to, amount, denom: "umsg", justification }),
    });
  }

  // MPC
  async mpcSign(keyId: string, payload: string, participants: string[], threshold: number) {
    return this.request("/api/v1/agent/mpc/sign", {
      method: "POST",
      body: JSON.stringify({ key_id: keyId, payload, participants, threshold, algorithm: "Dilithium5" }),
    });
  }

  async mpcSubmit(sessionId: string, participant: string, partialSignature: string) {
    return this.request("/api/v1/agent/mpc/submit", {
      method: "POST",
      body: JSON.stringify({ session_id: sessionId, participant, partial_signature: partialSignature }),
    });
  }

  async mpcAggregate(sessionId: string) {
    return this.request("/api/v1/agent/mpc/aggregate", {
      method: "POST",
      body: JSON.stringify({ session_id: sessionId }),
    });
  }

  // Payment
  async createPaymentSession(
    agentId: string, payer: string, payee: string,
    ratePerSec: string, initialBalance: string
  ) {
    return this.request("/api/v1/agent/payment/create-session", {
      method: "POST",
      body: JSON.stringify({
        agent_id: agentId, payer, payee,
        rate_per_sec: ratePerSec, initial_balance: initialBalance, asset: "umsg",
      }),
    });
  }

  async closePaymentSession(sessionId: string, closeReceiptHash: string) {
    return this.request("/api/v1/agent/payment/close-session", {
      method: "POST",
      body: JSON.stringify({ session_id: sessionId, close_receipt_hash: closeReceiptHash }),
    });
  }

  // Oracle
  async oracleRequest(model: string, prompt: string, inputData: unknown) {
    return this.request("/api/v1/agent/oracle/request", {
      method: "POST",
      body: JSON.stringify({ model, prompt, input_data: inputData }),
    });
  }

  async oracleResult(requestId: string) {
    return this.request(`/api/v1/agent/oracle/result/${requestId}`);
  }
}

export { AgentAPIClient, type AgentAPIConfig };

7.8 完整交互示例

// full-integration.ts — 完整集成示例
import { CosmWasmClient, SigningCosmWasmClient } from "@cosmjs/cosmwasm-stargate";
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { GasPrice } from "@cosmjs/stargate";
import { AgentAPIClient } from "./agent-api-client";

async function fullIntegration() {
  // 1. 连接 RPC
  const rpcClient = await CosmWasmClient.connect("http://localhost:26657");
  const chainId = await rpcClient.getChainId();
  console.log(`Connected to ${chainId}`);

  // 2. 查询账户余额
  const address = "msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3";
  const balance = await rpcClient.getBalance(address, "umsg");
  console.log(`Balance: ${balance.amount} ${balance.denom}`);

  // 3. 获取签名客户端
  const mnemonic = "your test mnemonic here...";
  const wallet = await DirectSecp256k1HdWallet.fromMnemonic(mnemonic, {
    prefix: "msg",
  });
  const [account] = await wallet.getAccounts();

  const signingClient = await SigningCosmWasmClient.connectWithSigner(
    "http://localhost:26657",
    wallet,
    { gasPrice: GasPrice.fromString("1000000000attoMSG") }
  );

  // 4. 合约智能查询
  const contractAddr = "msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal";
  const queryResult = await rpcClient.queryContractSmart(contractAddr, {
    get_count: {},
  });
  console.log("Contract state:", queryResult);

  // 5. 执行合约交易
  const executeResult = await signingClient.execute(
    account.address,
    contractAddr,
    { increment: {} },
    "auto"
  );
  console.log(`Tx hash: ${executeResult.transactionHash}`);
  console.log(`Gas used: ${executeResult.gasUsed}`);

  // 6. 通过 Agent API 查询
  const agentApi = new AgentAPIClient({
    baseUrl: "http://localhost:8080",
    apiKey: "your-api-key",
  });

  // 检查 Agent 状态
  try {
    const status = await agentApi.getStatus("my-agent-001");
    console.log("Agent status:", status);
  } catch (err) {
    console.error("Agent API error:", err);
  }

  // 7. 错误处理示例
  try {
    await rpcClient.getBalance("invalid-address", "umsg");
  } catch (err) {
    console.error("Query failed (expected):", (err as Error).message);
  }
}

fullIntegration().catch(console.error);

八、curl 使用示例

8.1 链基础操作

# 查询节点状态
curl -s http://localhost:26657/status | jq '.result.sync_info'

# 查询区块
curl -s "http://localhost:26657/block?height=1" | jq '.'

# 查询账户余额
curl -s http://localhost:1317/cosmos/bank/v1beta1/balances/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3 | jq '.'

# 查询总供应量
curl -s http://localhost:1317/cosmos/bank/v1beta1/supply | jq '.'

# 查询链信息
curl -s http://localhost:1317/api/v1/chain/info | jq '.'

8.2 验证者与质押

# 列出所有验证者
curl -s http://localhost:1317/cosmos/staking/v1beta1/validators | jq '.validators | length'

# 查询活跃验证者集
curl -s "http://localhost:1317/cosmos/staking/v1beta1/validators?status=BOND_STATUS_BONDED" | jq '.'

# 查询委托
curl -s http://localhost:1317/cosmos/staking/v1beta1/delegations/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3 | jq '.'

# 查询委托奖励
curl -s http://localhost:1317/cosmos/distribution/v1beta1/delegators/msg1qypqxpq9kcrn2c9afea5lq35ef37c5x7jqylz3/rewards | jq '.'

8.3 合约操作

# 查询合约信息
CONTRACT="msg14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9s4hmal"
curl -s http://localhost:1317/cosmwasm/wasm/v1/contract/$CONTRACT | jq '.'

# 智能查询(base64 编码的查询消息)
QUERY_JSON='{"get_count":{}}'
QUERY_B64=$(echo -n "$QUERY_JSON" | base64 -w0)
curl -s "http://localhost:1317/cosmwasm/wasm/v1/contract/$CONTRACT/smart/$QUERY_B64" | jq '.'

8.4 交易广播

# 使用 msgd CLI 查询交易
./build/msgd query tx 0xABCDEF1234567890

# 通过 RPC 查询交易
curl -X POST http://localhost:26657/cosmos.tx.v1beta1.Service/GetTx \
  -H "Content-Type: application/json" \
  -d '{"hash": "0xABCDEF1234567890"}' | jq '.'

8.5 Agent API

# 查询 Agent 状态
curl -s http://localhost:8080/api/v1/agent/my-agent-001/status | jq '.'

# 查询 Agent 执行历史
curl -s "http://localhost:8080/api/v1/agent/my-agent-001/history?limit=5" | jq '.'

# 查询 Agent 钱包余额(需 API Key)
curl -s -H "X-API-Key: your-api-key" \
  http://localhost:8080/api/v1/agent/wallet/my-agent-001/balance | jq '.'

# 查询 Agent 钱包交易历史
curl -s -H "X-API-Key: your-api-key" \
  "http://localhost:8080/api/v1/agent/wallet/my-agent-001/transactions?limit=10" | jq '.'

# 发起 Agent 查询
curl -X POST http://localhost:8080/api/v1/agent/query \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "my-agent-001", "query": "What services do you offer?"}' | jq '.'

# 请求 Oracle 推理
curl -X POST http://localhost:8080/api/v1/agent/oracle/request \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4",
    "prompt": "Analyze this transaction",
    "input_data": {"tx": {"from": "msg1...", "to": "msg1...", "amount": "1000000"}}
  }' | jq '.'

8.6 治理操作

# 查询提案列表
curl -s http://localhost:1317/cosmos/gov/v1beta1/proposals | jq '.proposals | length'

# 查询投票中提案
curl -s "http://localhost:1317/api/v1/gov/proposals?status=VOTING_PERIOD" | jq '.'

# 查询交易
curl -s http://localhost:1317/api/v1/tx/0xABCDEF1234567890 | jq '.'

九、WebSocket 事件订阅

9.1 Tendermint WebSocket

Tendermint RPC 提供原生 WebSocket 接口,位于 ws://localhost:26657/websocket。

订阅事件:

{
  "jsonrpc": "2.0",
  "method": "subscribe",
  "id": 1,
  "params": {
    "query": "tm.event='NewBlock'"
  }
}

支持的事件类型:

事件 查询 说明
新区块 tm.event='NewBlock' 每个新区块产生时触发
新区块头 tm.event='NewBlockHeader' 新区块头
新交易 tm.event='Tx' 任何新交易
验证者集合更新 tm.event='ValidatorSetUpdates' 验证者集变化

TypeScript 示例:

import { WebSocket } from "ws";
import { createRpcClient } from "@cosmjs/tendermint-rpc";

// 使用 CosmJS WebSocket 客户端
async function subscribeNewBlocks() {
  const client = await CosmWasmClient.connect("http://localhost:26657");

  // CosmJS 不直接暴露 WebSocket,但可以通过 Tendermint RPC 使用
  const ws = new WebSocket("ws://localhost:26657/websocket");

  ws.on("open", () => {
    ws.send(JSON.stringify({
      jsonrpc: "2.0",
      method: "subscribe",
      id: 1,
      params: { query: "tm.event='NewBlock'" },
    }));
  });

  ws.on("message", (data: string) => {
    const msg = JSON.parse(data);
    if (msg.result?.data?.value?.block) {
      const height = msg.result.data.value.block.header.height;
      const txs = msg.result.data.value.block.data.txs?.length || 0;
      console.log(`New block: ${height}, transactions: ${txs}`);
    }
  });

  ws.on("close", () => console.log("WebSocket closed"));

  return ws;
}

9.2 Agent API WebSocket

Agent API 提供自定义 WebSocket 事件,位于 ws://localhost:8080/api/v1/agent/events/subscribe。

支持的事件类型:

事件类型 说明
Transfer 转账事件
ContractExecute 合约执行事件
BlockProduced 新区块产生事件
ValidatorChange 验证者变更事件
AgentAction Agent 动作事件
PaymentSettled 支付结算事件

完整 WebSocket 客户端:

import { EventEmitter } from "events";

interface AgentEvent {
  type: string;
  data: Record<string, unknown>;
  timestamp: number;
}

class AgentEventSubscriber extends EventEmitter {
  private ws: WebSocket | null = null;
  private url: string;
  private eventTypes: string[];
  private filter: Record<string, string>;
  private reconnectDelay: number = 3000;
  private maxReconnectAttempts: number = 10;
  private reconnectAttempts: number = 0;

  constructor(config: {
    baseUrl: string;
    eventTypes: string[];
    filter?: Record<string, string>;
  }) {
    super();
    this.url = config.baseUrl.replace(/^http/, "ws") + "/api/v1/agent/events/subscribe";
    this.eventTypes = config.eventTypes;
    this.filter = config.filter || {};
  }

  connect(): void {
    try {
      this.ws = new WebSocket(this.url);

      this.ws.onopen = () => {
        this.reconnectAttempts = 0;
        this.ws!.send(JSON.stringify({
          event_types: this.eventTypes,
          filter: this.filter,
        }));
        this.emit("connected");
        console.log("[AgentEventSubscriber] Connected");
      };

      this.ws.onmessage = (event: MessageEvent) => {
        try {
          const msg: AgentEvent = JSON.parse(event.data);
          this.emit(msg.type, msg.data, msg.timestamp);
          this.emit("event", msg);
        } catch (err) {
          console.error("[AgentEventSubscriber] Parse error:", err);
        }
      };

      this.ws.onclose = () => {
        this.emit("disconnected");
        this.reconnect();
      };

      this.ws.onerror = (err) => {
        this.emit("error", err);
      };
    } catch (err) {
      console.error("[AgentEventSubscriber] Connection failed:", err);
      this.reconnect();
    }
  }

  private reconnect(): void {
    if (this.reconnectAttempts >= this.maxReconnectAttempts) {
      this.emit("max_reconnect_exceeded");
      return;
    }

    this.reconnectAttempts++;
    const delay = this.reconnectDelay * Math.min(this.reconnectAttempts, 5);
    console.log(`[AgentEventSubscriber] Reconnecting in ${delay}ms (attempt ${this.reconnectAttempts})`);

    setTimeout(() => {
      this.connect();
    }, delay);
  }

  disconnect(): void {
    if (this.ws) {
      this.ws.close();
      this.ws = null;
    }
  }
}

// 使用示例
const subscriber = new AgentEventSubscriber({
  baseUrl: "http://localhost:8080",
  eventTypes: ["Transfer", "ContractExecute"],
  filter: { agent_id: "my-agent-001" },
});

subscriber.on("Transfer", (data, timestamp) => {
  console.log(`Transfer event:`, data);
});

subscriber.on("ContractExecute", (data, timestamp) => {
  console.log(`Contract executed:`, data);
});

subscriber.on("connected", () => {
  console.log("Event subscriber ready");
});

subscriber.on("error", (err) => {
  console.error("Event subscriber error:", err);
});

subscriber.connect();

十、限流与安全

10.1 限流策略

MSG Chain API 实施多层限流:

层 速率 突发 范围
RPC 请求 100 req/s 200 按 IP
REST 查询 200 req/s 300 按 IP
Agent API 查询 100 req/s 200 按 API Key
Agent API 写操作 20 req/s 40 按 API Key
交易广播 10 req/s 20 按 IP
WebSocket 连接 5 连接/IP — 按 IP

限流响应:

// HTTP 429 Too Many Requests
{
  "error": {
    "code": 17,
    "name": "RATE_LIMIT_EXCEEDED",
    "message": "请求频率超限",
    "details": "请在 1000ms 后重试"
  }
}

限流头:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 42
X-RateLimit-Reset: 1704067200
Retry-After: 1

10.2 API 认证

API Key 认证

所有 Agent API 写操作需要 X-API-Key 头:

curl -X POST http://localhost:8080/api/v1/agent/wallet/transfer \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{"agent_id": "my-agent-001", "to": "msg1...", "amount": "1000000"}'

Dilithium-5 后量子签名验证

MSG Chain 使用 Dilithium-5 后量子签名方案替代传统的 ECDSA/EdDSA。所有交易签名使用 Dilithium-5 算法:

// 验证 Dilithium-5 签名(通过链上查询)
async function verifyDilithiumSignature(
  client: CosmWasmClient,
  publicKey: string,
  signature: string,
  message: string
): Promise<boolean> {
  const result: any = await client.queryContractSmart(
    "msg1...dilithiumVerifyAddress",
    {
      verify_signature: {
        algorithm: "Dilithium5",
        public_key: publicKey,
        signature: signature,
        message: message,
      },
    }
  );
  return result.valid;
}

10.3 安全最佳实践

  1. API Key 管理:不要在客户端代码中硬编码 API Key。使用环境变量或安全的密钥管理服务。
  2. 幂等性:使用 idempotency_key 确保交易不会重复执行。
  3. Gas 管理:始终设置合理的 gasPrice 和 gasLimit,避免交易因 out of gas 失败。
  4. Nonce 管理:顺序交易必须确保 nonce 递增,等待前一笔交易确认后再发送下一笔。
  5. Constitution 预检:所有 Agent 写操作前先调用 IsActionAllowed 或 CheckAction 预检。
  6. Stub 检测:检查响应的 X-MSG-Stub 头,stub 端点不应在生产环境中使用。
  7. WebSocket 重连:实现指数退避重连逻辑,避免对服务器造成压力。
  8. TLS:生产环境始终使用 HTTPS/WSS,传输敏感信息时必须加密。

10.4 Stub 端点清单

以下端点当前为 stub 实现,返回 X-MSG-Stub: true:

端点 说明 预期实现时间
/api/v1/agent/mpc/* MPC 签名相关 未来版本
/api/v1/agent/oracle/* AI Oracle 未来版本
/api/v1/agent/wallet/create 钱包创建 未来版本
/cosmwasm.wasm.v1.Msg/* 部分 msg 类型 确定性实现中

附录

A. CLI 命令参考(msgd)

命令 说明
msgd status 查询节点状态
msgd query bank balances <address> 查询余额
msgd query wasm list-code 列出所有合约代码
msgd query wasm contract-state smart <addr> <query> 智能查询
msgd tx wasm store <file> 上传合约
msgd tx wasm instantiate <code-id> <msg> 实例化合约
msgd tx wasm execute <addr> <msg> 执行合约
msgd keys add <name> 添加密钥
msgd keys list 列出密钥

B. 常用数据类型

TypeScript 类型 Protobuf 类型 说明
string string UTF-8 字符串
number uint64 64 位无符号整数
string (数字字符串) uint128 128 位无符号整数(金额)
Uint8Array bytes 字节数组
string (hex) bytes 哈希值
boolean bool 布尔值

C. 资源链接

资源 链接
MSG Chain 官网 https://msgchain.org
CosmWasm 文档 https://docs.cosmwasm.com
CosmJS 文档 https://cosmwasm.github.io/cosmjs
Keplr 钱包 https://www.keplr.app
Dilithium 算法 https://pq-crystals.org/dilithium

D. 响应码汇总

HTTP 状态码 说明
200 成功
400 请求参数错误
401 未授权
403 权限不足/宪章阻止
404 资源不存在
409 资源冲突(重复注册等)
410 资源已过期
429 请求频率超限
500 服务器内部错误
501 功能未实现(Stub)

本文档基于 MSG Chain 代码库核实的技术事实。
白皮书系统: https://msgchain.org/whitepaper/