Skill站外收录 @skilllib/skill-2117939930272411405
api-design
面向 CosmWasm 智能合约的 API 设计指导,涵盖消息类型定义、执行与查询接口设计、响应结构组织及序列化规范,强调精简性、命名清晰性、跨合约一致性,并通过完整文档注释和 serde 模式支撑可维护性与工具链集成。
区块链 AI 技能
Skills.MD
# CosmWasm API Design Best Practices
This skill helps you design clean, minimal, and well-documented APIs for CosmWasm smart contracts.
## When to use this skill
Use this skill when you need to:
- Define message types (InstantiateMsg, ExecuteMsg, QueryMsg, MigrateMsg)
- Design execute or query interfaces
- Document APIs for schema generation
- Apply serde patterns for optional fields
- Ensure API consistency across contracts
## Core Principles
1. **Minimalism** - Include only what's necessary; avoid bloated APIs
2. **Clarity** - Names should be self-documenting
3. **Consistency** - Follow established patterns across all contracts
4. **Documentation** - Every public type and field must have doc comments
## Message Type Patterns
### InstantiateMsg
```rust
/// Contract instantiation message
#[cosmwasm_schema::cw_serde]
#[derive(Default)]
pub struct MyContractInstantiateMsg {
/// Optional configuration parameter with sensible default
#[serde(default)]
pub some_config: Option<String>,
}
```
**Guidelines:**
- Derive `Default` when possible for easier testing
- Use `#[serde(default)]` for optional fields
- Keep required fields minimal
- Document each field
### ExecuteMsg
```rust
/// Contract execute messages
#[cosmwasm_schema::cw_serde]
#[derive(cw_orch::ExecuteFns)]
pub enum MyContractExecuteMsg {
/// Update the contract configuration
UpdateConfig {
/// New admin address (optional)
new_admin: Option<String>,
},
/// Process an action with the given parameters
ProcessAction {
/// Unique identifier for the action
action_id: String,
/// Amount to process
amount: Uint128,
},
}
```
**Guidelines:**
- Use verb-based names (Update, Process, Create, Remove)
- Group related parameters in structs if >3 fields
- Document each variant AND each field
- Derive `ExecuteFns` for cw-orch integration
### QueryMsg
```rust
/// Contract query messages
#[cosmwasm_schema::cw_serde]
#[derive(cw_orch::QueryFns, QueryResponses)]
pub enum MyContractQueryMsg {
/// Get the current configuration
#[returns(ConfigResponse)]
Config {},
/// Get item by ID
#[returns(ItemResponse)]
Item {
/// The item identifier
id: String,
},
/// List all items with pagination
#[returns(ItemsResponse)]
Items {
/// Start after this ID for pagination
start_after: Option<String>,
/// Maximum number of items to return
limit: Option<u32>,
},
}
```
**Guidelines:**
- Always include `#[returns(ResponseType)]` attribute
- Use noun-based names for queries
- Include pagination for list queries (`start_after`, `limit`)
- Derive `QueryFns` and `QueryResponses`
### Response Types
```rust
#[cosmwasm_schema::cw_serde]
pub struct ConfigResponse {
/// Current admin address
pub admin: Addr,
/// Whether the contract is paused
pub paused: bool,
}
#[cosmwasm_schema::cw_serde]
pub struct ItemsResponse {
/// List of items
pub items: Vec<ItemInfo>,
}
```
**Guidelines:**
- Response types should mirror what clients need
- Use specific types (Addr, Uint128) not strings
- Document all fields
## Abstract SDK Integration
Use the `app_msg_types!` macro to generate wrapper types:
```rust
use crate::contract::MyContract;
use cosmwasm_schema::QueryResponses;
// Generates ExecuteMsg, QueryMsg, InstantiateMsg wrappers
abstract_app::app_msg_types!(MyContract, MyContractExecuteMsg, MyContractQueryMsg);
```
## Documentation Standards
### Rust Doc Comments
```rust
/// Brief one-line description of the variant.
///
/// Optional longer description that explains:
/// - When to use this
/// - Side effects
/// - Related messages
///
/// # Errors
///
/// Returns `ContractError::Unauthorized` if caller is not admin.
```
### Field Documentation
Every field must have a doc comment:
- Describe what the field represents
- Mention default values if applicable
- Note any constraints (min/max values, format)
## Serde Patterns
### Optional Fields with Defaults
```rust
#[serde(default)]
pub optional_field: Option<String>,
#[serde(default = "default_limit")]
pub limit: u32,
fn default_limit() -> u32 {
10
}
```
### Flatten for Nested Configs
```rust
#[cosmwasm_schema::cw_serde]
pub struct InstantiateMsg {
#[serde(flatten)]
pub base_config: BaseConfig,
pub custom_field: String,
}
```
### Rename for JSON Clarity
```rust
#[serde(rename = "owner")]
pub owner_addr: Addr,
```
## Checklist for New APIs
- [ ] All message variants have doc comments
- [ ] All struct fields have doc comments
- [ ] Query messages have `#[returns(...)]` attribute
- [ ] Execute messages describe potential errors
- [ ] Pagination is included for list queries
- [ ] Optional fields use `Option<T>` or `#[serde(default)]`
- [ ] Response types are defined for all queries
- [ ] Types use `Addr`/`Uint128` not raw strings/numbers
评论 0
还没有评论,来抢沙发。
相关内容
同类或同场景的收录内容
building-with-kafka-strimzi
在 Kubernetes 上构建基于 Apache Kafka 的事件驱动系统,支持高可靠的消息传递、事务性处理与精确一次语义,结合 Strimzi 运营商实现集群自动化管理,利用 Schema Registry 保障事件模式演进,适用于微服务间解耦通信与实时数据流处理场景。
站外数据与分析
609 0.0
personal-tool-builder
专注于从个人真实痛点出发快速构建实用工具,涵盖命令行程序、本地优先应用和自动化脚本的开发与演进,强调先满足自身需求再逐步扩展,通过持续自用打磨功能,避免过度设计,确保工具简洁有效且长期可维护。
站外商业与营销
196 0.0
threejs-lighting
实现三维场景中的光照与阴影控制,支持多种光源类型及环境光照明,提供从基础布光到高级阴影优化的完整方案,适用于需要真实感渲染或性能平衡的可视化项目。
站外效率工具
442 0.0
aggregation-helper
提供数据聚合场景的自动化辅助能力,涵盖 SQL 查询编写、统计分析建模、可视化方案设计及商业智能配置,支持从需求理解到生产级代码生成的全流程指导。
站外效率工具数据与分析
217 0.0
举报「api-design」
举报信息仅审核团队可见,同一资产 24 小时内仅可举报一次