Unlock efficient CosmWasm smart contract development with these comprehensive rules tailored for Cursor AI users. Covering Rust standards, testing, security, and deployment for Cosmos blockchain apps.
## Introduction to CosmWasm Smart Contract Development
CosmWasm enables developers to build secure, efficient smart contracts on the Cosmos SDK ecosystem using Rust. This guide provides a complete set of rules and practices to streamline your workflow, especially when leveraging tools like Cursor AI for code generation and editing. By adhering to these guidelines, you'll ensure your contracts are production-ready, secure, and compliant with CosmWasm standards. We'll cover everything from setup to deployment, with practical examples and code snippets.
## Core Language and Tooling Requirements
### Stick Exclusively to Rust
All CosmWasm smart contracts must be written in Rust—no exceptions. Rust's memory safety, performance, and ecosystem make it ideal for blockchain. Avoid other languages like Go or JavaScript for contract logic.
- **Why Rust?** It prevents common vulnerabilities like buffer overflows and ensures deterministic execution in the Wasm VM.
- **Setup Command:** Initialize your project with Cargo:
```bash
cargo new my_contract --lib
cd my_contract
cargo add cosmwasm-std
```
Reference the official [CosmWasm repository](https://github.com/CosmWasm/cosmwasm) for the latest Rust crates.
### Use Official CosmWasm Scaffolding
Start every project from verified templates to avoid boilerplate errors. Clone from [CosmWasm contract examples](https://github.com/CosmWasm/contract-examples) and adapt them.
**Example:** For a basic CW20 token:
```rust
use cosmwasm_std::{DepsMut, Env, MessageInfo, Response};
#[entry_point]
pub fn execute(
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: ExecuteMsg,
) -> Result<Response, ContractError> {
// Your logic here
Ok(Response::new())
}
```
## Contract Structure and Standards
### Follow SemVer Strictly
Version your contracts using Semantic Versioning as outlined in [CosmWasm's SEMVER.md](https://github.com/CosmWasm/cosmwasm/blob/main/SEMVER.md). Bumping major versions for breaking changes ensures safe migrations on-chain.
- **Patch:** Bug fixes.
- **Minor:** New features backward-compatible.
- **Major:** Breaking changes—deploy as new contract.
### Implement All Required Traits
Every contract needs `Instantiate`, `Execute`, and `Query` entry points from `cosmwasm_std`. Add `Migrate` for upgradability.
**Practical Tip:** Always handle errors explicitly:
```rust
use cosmwasm_std::StdError;
pub fn validate_input(s: String) -> Result<(), StdError> {
if s.is_empty() {
return Err(StdError::generic_err("Input cannot be empty"));
}
Ok(())
}
```
## Testing: Comprehensive and Deterministic
### Unit Tests with cosmwasm-vm
Write exhaustive unit tests using the [cosmwasm-vm](https://github.com/CosmWasm/cosmwasm/blob/main/cosmwasm-vm/README.md). Mock the blockchain state for isolation.
**Cargo.toml Addition:**
```toml
[dev-dependencies]
cosmwasm-vm = { version = "1.5", features = ["iterator"] }
```
**Example Test:**
```rust
#[test]
fn test_instantiate() {
let mut deps = mock_dependencies();
let info = mock_info("creator", &[]);
let msg = InstantiateMsg { count: 17 };
instantiate(deps.as_mut(), mock_env(), info, msg).unwrap();
}
```
### Integration Tests
Test full execution paths with serialized messages. Use `cw-multi-test` for simulated chains.
### Fuzz Testing
Incorporate `cargo-fuzz` for edge cases, focusing on inputs like malformed JSON.
## Security Best Practices
### Binary Size Optimization
Keep Wasm binaries under 2MB. Use `wee_alloc` and strip debug symbols:
```toml
[profile.release]
codegen-units = 1
lto = true
overflow-checks = false
panic = "abort"
```
Build with:
```bash
RUSTFLAGS='-C link-arg=-s' cargo wasm
```
### Reentrancy Protection
CosmWasm's single-entry-point model prevents reentrancy, but validate states atomically.
### Access Control
Use `cosmwasm_std::ensure` for authorization:
```rust
ensure_sender_is_admin(deps.as_ref(), info.sender())?;
```
## Schema Generation and JSON Handling
### Auto-Generate Schemas
Use [cosmwasm-schema](https://github.com/CosmWasm/cosmwasm/blob/main/cosmwasm-schema/README.md) for type-safe serialization.
**Commands:**
```bash
cargo install cosmwasm-schema
cargo schema
```
This creates JSON schemas for frontend integration.
## Deployment Workflow
### Local Development with Docker
Follow [CosmWasm WORKFLOW.md](https://github.com/CosmWasm/cosmwasm/blob/main/WORKFLOW.md) for Dockerized optimization and testing.
**Dockerfile Example:**
```dockerfile
FROM rust:1.75
COPY . .
RUN rustup target add wasm32-unknown-unknown
RUN cargo build --target wasm32-unknown-unknown --release
```
### Chain Deployment
Optimize, store code on-chain via `cosmwasmd tx wasm store`, then instantiate.
**Real-World Application:** Deploying a DAO contract—test governance messages end-to-end before mainnet.
## Advanced Topics
### Custom Extensions
Extend with `CustomMsg` only if needed; prefer standard messages for interoperability.
### Upgrades and Migrations
Design for `migrate` entry point. Test with multiple versions.
**Migration Example:**
```rust
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
// State upgrades
Ok(Response::default())
}
```
### Multi-Contract Interactions
Use `CosmosMsg` for submessages and replies. Handle `SubMsgResult` in `execute`.
## Optimization Techniques
- **Iterator Usage:** Leverage `Deps::iter_*` for efficient storage reads.
- **Gas Management:** Profile with `wasmd` flags.
- **Benchmarking:** Use `criterion` for Rust performance.
## Common Pitfalls and Fixes
- **Pitfall:** Ignoring `CanonicalAddr` vs `HumanAddr`—always convert properly.
- **Fix:** Use `deps.api.addr_humanize` and `addr_canonicalize`.
- **Pitfall:** Mutable storage without checks.
- **Fix:** Sudo prefix or admin validation.
## Integration with Cursor AI
When using Cursor AI:
- Prefix prompts with these rules.
- Request code matching [std crate](https://github.com/CosmWasm/cosmwasm/tree/main/packages/std).
- Always verify generated code against examples.
## Resources and Next Steps
- Explore [full CosmWasm docs](https://docs.cosmwasm.com).
- Join Cosmos developer communities.
- Prototype a CW721 NFT contract using these rules.
This framework ensures your CosmWasm contracts are robust, scalable, and secure. Apply it step-by-step for every project to accelerate development.
<div style="text-align: center; margin-top: 2rem;">
<a href="https://cursor.directory/cosmwasm-smart-contract-development-rules" target="_blank" rel="noopener noreferrer" class="view-full-resource-btn" style="display: inline-block; background-color: #f97316; color: white; padding: 12px 24px; border-radius: 8px; text-decoration: none; font-weight: 600; transition: background-color 0.2s;">View Full Resource</a>
</div>