Back to Rules
Rust

CosmWasm Smart Contracts: Rust Development Best Practices Guide

Claude Directory November 29, 2025
0 copies 0 downloads

Unlock secure and optimized CosmWasm smart contract development in Rust. Essential rules for modular structure, security hardening, performance tuning, testing, and deployment on Cosmos blockchain.

Rule Content
## Core Principles for CosmWasm Development

Focus on crafting robust, high-performance Rust code for CosmWasm contracts. Emphasize security, modularity, and efficiency to handle Cosmos blockchain demands. Always prioritize rigorous testing and audits prior to any mainnet deployment.

## Recommended Project Structure

Organize your contract into a clean, modular layout for better maintainability:

- Place core interfaces in `contract/mod.rs`.
- Handle instantiation logic in `contract/init.rs`.
- Manage execution functions in `contract/exec.rs`.
- Implement queries in `contract/query.rs`.
- Store message definitions in `msg/` directory (e.g., `msg/init.rs`, `msg/exec.rs`, `msg/query.rs`).
- Define custom errors in a dedicated file like `error.rs`.

**Example Structure:**
```rust
// src/contract/mod.rs
pub mod init;
pub mod exec;
pub mod query;

#[cw_serde]
pub struct InstantiateMsg { /* fields */ }
```

## Input Validation and Security Measures

Enforce strict checks on all inputs to block exploits like reentrancy or overflows. Leverage CosmWasm's built-in safeguards and Rust's type system.

**Practical Example:**
```rust
// src/contract/exec.rs
use cosmwasm_std::{DepsMut, Env, MessageInfo, Response, StdResult};

pub fn execute(
    deps: DepsMut,
    env: Env,
    info: MessageInfo,
    msg: ExecuteMsg,
) -> StdResult<Response> {
    // Validate sender
    if info.sender != ADMIN {
        return Err(ContractError::Unauthorized {});
    }
    // Additional input sanitization
    msg.amount.checked_u128()?;
    // ...
    Ok(Response::new())
}
```

## Performance Optimization Techniques

Minimize gas usage and boost speed by profiling code and using Rust's zero-cost abstractions. Avoid unnecessary allocations and leverage async patterns where supported.

**Benchmarking Tip:** Use `criterion` for local profiling:
```toml
[dev-dependencies]
criterion = { version = "0.5", features = ["html_reports"] }
```

## Comprehensive Testing Strategy

Build exhaustive tests with unit, integration, and fuzzing via `cw-multi-test` and QuickCheck. Simulate chain states and attack scenarios.

**Example Unit Test:**
```rust
#[cfg(test)]
mod tests {
    use super::*;
    use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info};

    #[test]
    fn proper_initialization() {
        let mut deps = mock_dependencies();
        let env = mock_env();
        let info = mock_info("creator", &[]);
        let msg = InstantiateMsg { /* ... */ };
        let res = instantiate(deps.as_mut(), env, info, msg).unwrap();
        assert_eq!(0, res.messages.len());
    }
}
```

Test on local testnets before mainnet. Set up CI/CD with GitHub Actions for automated validation.

## Documentation Standards

Provide detailed English comments for all structs, functions, and modules. Create a comprehensive README with setup, build, and usage examples.

**README Snippet:**
```markdown
## Building and Deploying
cargo build --release --target wasm32-unknown-unknown

## Usage
See `examples/` for integration with CosmJS.

Comments

More Rules

View all
AI/ML

GLM-4.7 Optimized Config & System Prompt Designer

Expert system prompt for designing high-performance configurations tailored to GLM-4.7's strengths in coding, reasoning, tool use, and multilingual tasks, backed by benchmarks like SWE-bench and τ²-Bench.

C
Community
AI/ML

GLM-4.7 Open-Source Coding Expert: Optimized System Prompt

Leverage GLM-4.7's top benchmarks in SWE-bench, LiveCodeBench, and more with this system prompt designed for generating clean, secure, open-source-ready code, stunning UIs, and agentic workflows.

C
Community
AI/ML

GLM-4.7 Optimized Coding Agent

This system prompt transforms an AI into GLM-4.7, a benchmark-leading coding agent excelling in agentic workflows, tool use, multilingual coding, and complex reasoning with verified best practices for production-ready open-source development.

C
Community
DevOps

Agentic Dev Loop: Autonomous Jira-Driven Coding Agent with GitHub CI Self-Healing

Ralph, a persistent autonomous AI agent, implements Jira tickets through an endless loop until 100% test success, with GitHub PRs, Jules AI reviews, and CI self-healing for reliable development workflows.

C
Claude Directory
AI/ML

Türk Hukuku Uzmanı AI Agent: Güvenilir Yasal Danışman System Prompt

Claude'u Türk hukuku alanında dünyanın en önde gelen uzmanı olarak yapılandıran, yapılandırılmış yanıtlar, zorunlu uyarılar ve etik sınırlarla donatılmış profesyonel AI agent promptu.

C
Community
Database

PostgreSQL Best Practices: Expert Subagent Guide

Expert subagent providing production-ready PostgreSQL guidance on schema design, query optimization, security, performance tuning, and administration with structured, actionable advice and official references.

C
Claude Directory