---
name: cosmos
description: Use when building blockchain applications, creating custom modules, running validator nodes, managing chain upgrades, or working with Cosmos SDK chains. Agents should reach for this skill when building app chains, implementing state machines, configuring nodes, or understanding blockchain architecture.
metadata:
    mintlify-proj: cosmos
    version: "1.0"
---

# Cosmos SDK Skill

## Product summary

The Cosmos SDK is a modular framework for building application-specific blockchains (app chains) on top of CometBFT consensus. It provides production-ready modules for accounts, token transfers, staking, governance, and more, plus tools to build custom modules and run validator nodes. Key files: `app.go` (application wiring), `config/app.toml` and `config/config.toml` (node configuration), `.proto` files (message definitions), `keeper.go` (state access), `msg_server.go` (message handlers). Primary CLI: `<appd>` binary (e.g., `simd`, `exampled`). Core concepts: modules, messages, queries, keepers, state, transactions. See [Cosmos SDK docs](https://docs.cosmos.network/sdk/latest) for comprehensive reference.

## When to use

- **Building a blockchain**: Create a custom app chain with your own business logic and modules
- **Creating modules**: Implement custom state machines, messages, and queries for specific functionality
- **Running nodes**: Set up validator nodes, full nodes, or light clients; manage keys and signing
- **Chain operations**: Configure nodes, manage upgrades, handle state migrations, run testnets
- **Understanding blockchain architecture**: Learn how transactions flow, state is managed, consensus works
- **Integrating with chains**: Query state via gRPC/REST, submit transactions, interact with modules
- **Testing**: Write unit tests for keepers, integration tests with full chain, or simulation tests

## Quick reference

### Essential CLI commands

| Task | Command |
|------|---------|
| Initialize chain | `<appd> init <moniker> --chain-id <chain-id>` |
| Create account | `<appd> keys add <key-name> --keyring-backend test` |
| Add genesis account | `<appd> genesis add-genesis-account <address> <amount><denom>` |
| Create validator | `<appd> genesis gentx <key-name> <amount><denom> --chain-id <chain-id>` |
| Collect gentxs | `<appd> genesis collect-gentxs` |
| Start node | `<appd> start` |
| Query state | `<appd> query <module> <query-name> [args]` |
| Submit transaction | `<appd> tx <module> <msg-name> [args] --from <key> --chain-id <chain-id>` |
| Check version | `<appd> version` |

### Key file paths (default: `~/.appd/`)

| File | Purpose |
|------|---------|
| `config/app.toml` | SDK app configuration (gRPC, REST, state pruning, telemetry) |
| `config/config.toml` | CometBFT node configuration (P2P, RPC, consensus) |
| `config/genesis.json` | Initial chain state and parameters |
| `config/node_key.json` | P2P node identity key |
| `config/priv_validator_key.json` | Validator consensus signing key |
| `data/` | Application database (LevelDB) |

### Module structure

```
x/mymodule/
├── keeper/
│   ├── keeper.go          # State access layer
│   ├── msg_server.go      # Message handlers
│   └── query_server.go    # Query handlers
├── types/
│   ├── expected_keepers.go  # External module interfaces
│   ├── keys.go              # Store key definitions
│   └── *.pb.go              # Generated from proto
└── module.go              # AppModule implementation
```

### Proto file conventions

| File | Defines |
|------|---------|
| `tx.proto` | Message types and `service Msg` |
| `query.proto` | Query types and `service Query` |
| `state.proto` | On-chain state types |
| `genesis.proto` | Genesis state structure |

### Configuration essentials (app.toml)

```toml
# Minimum gas price validator accepts
minimum-gas-prices = "0.025stake"

# gRPC server
[grpc]
enable = true
address = "0.0.0.0:9090"

# REST API
[api]
enable = true
address = "tcp://0.0.0.0:1317"

# State snapshots for state sync
[state-sync]
snapshot-interval = 1000
snapshot-keep-recent = 2
```

## Decision guidance

| Scenario | Use X | Use Y | Condition |
|----------|-------|-------|-----------|
| **Querying state** | gRPC | REST | gRPC is faster; REST is browser-friendly |
| **Running node** | Full node | Pruned node | Full node for validators; pruned for light clients |
| **Storing state** | Collections API | Direct KVStore | Collections for type safety; KVStore for custom encoding |
| **Message validation** | MsgServer | Keeper | MsgServer for authorization; Keeper for business logic |
| **Chain upgrade** | In-place migration | Genesis export | In-place for live chains; genesis export for testing |
| **Testing** | Unit tests | Integration tests | Unit tests for speed; integration tests for full stack |

## Workflow

### 1. Build a chain from scratch

1. **Set up environment**: Install Go 1.21+, clone SDK example repo
2. **Initialize chain**: `make install && make start` (or `<appd> init`)
3. **Create accounts**: `<appd> keys add alice --keyring-backend test`
4. **Add to genesis**: `<appd> genesis add-genesis-account alice 100000000stake`
5. **Create validator**: `<appd> genesis gentx alice 100000000stake --chain-id demo`
6. **Collect gentxs**: `<appd> genesis collect-gentxs`
7. **Start node**: `<appd> start`
8. **Verify**: `<appd> query counter count` (or appropriate module query)

### 2. Create a custom module

1. **Define proto files**: Write `tx.proto`, `query.proto`, `state.proto` in `proto/myapp/mymodule/v1/`
2. **Generate code**: Run `buf generate` or `protoc` to create `.pb.go` files
3. **Implement keeper**: Create `keeper.go` with state access methods using Collections API
4. **Implement handlers**: Write `msg_server.go` (message validation) and `query_server.go` (read-only queries)
5. **Register module**: Add to `app.go` in module manager and dependency injection
6. **Write tests**: Unit tests for keeper, integration tests with full chain
7. **Wire into app**: Ensure module is included in `app.go` constructor and module manager

### 3. Submit a transaction

1. **Construct message**: `<appd> tx <module> <msg> [args] --from <key>`
2. **Review**: Check gas estimate and fees
3. **Sign and broadcast**: Confirm with `--yes` flag or sign separately
4. **Track**: Query with `<appd> query tx <tx-hash>` or use event logs

### 4. Configure and run a validator

1. **Initialize**: `<appd> init <moniker> --chain-id <chain-id>`
2. **Configure**: Edit `config/app.toml` (minimum-gas-prices, gRPC, REST)
3. **Add validator key**: `<appd> keys add validator --keyring-backend file` (or use KMS)
4. **Join network**: Obtain genesis file, set peers in `config/config.toml`
5. **Start node**: `<appd> start` (or use systemd/Docker)
6. **Monitor**: Check logs, use `<appd> status` to verify sync

### 5. Upgrade a chain

1. **Plan upgrade**: Create governance proposal with upgrade height
2. **Vote**: Validators vote on `MsgSoftwareUpgrade`
3. **Write migrations**: Implement store migrations in `x/module/migrations/`
4. **Register migrations**: Add to module's `ConsensusVersion()` and `RegisterMigrations()`
5. **Halt at height**: Node stops at upgrade height automatically
6. **Swap binary**: Replace old binary with new version
7. **Restart**: Node resumes from upgrade height with migrated state

## Common gotchas

- **Missing minimum-gas-prices**: Node halts on startup if `app.toml` has empty `minimum-gas-prices`. Set to at least `"0stake"` or appropriate value.
- **Sequence number mismatch**: Transactions fail if sequence number is wrong. Use `<appd> query auth account <address>` to check current sequence.
- **Proto file changes**: Always regenerate code after modifying `.proto` files. Forgetting this causes runtime panics.
- **Keeper access**: Never access store directly outside keeper. All state changes must go through keeper methods to enforce invariants.
- **Module ordering**: Module initialization order in `app.go` matters. Dependencies must be initialized before modules that use them.
- **Genesis validation**: Invalid genesis state causes chain to fail at startup. Always run `<appd> genesis validate-genesis` before starting.
- **Unordered transactions**: Transactions with `unordered=true` require `timeout_timestamp` and sequence `0`. Don't mix with ordered transactions.
- **State sync snapshots**: Snapshots only work if `snapshot-interval > 0` in `app.toml`. Pruning nodes may not produce snapshots if interval is too small.
- **Cross-module calls**: Use keeper interfaces from `expected_keepers.go`, not direct imports. This prevents circular dependencies.
- **Gas estimation**: `--gas auto` may underestimate. Use `--gas-adjustment 1.5` to add buffer for complex transactions.

## Verification checklist

Before submitting work on a Cosmos SDK chain:

- [ ] Proto files are valid and regenerated with `buf generate` or `protoc`
- [ ] All keeper methods are implemented and tested
- [ ] Message handlers validate inputs and check authorization
- [ ] Module is registered in `app.go` with correct dependencies
- [ ] Unit tests pass: `go test ./x/mymodule/...`
- [ ] Integration tests pass: `go test ./tests/...`
- [ ] Genesis file is valid: `<appd> genesis validate-genesis`
- [ ] Node starts without errors: `<appd> start`
- [ ] Queries work: `<appd> query mymodule <query>`
- [ ] Transactions execute: `<appd> tx mymodule <msg> ... --from alice`
- [ ] State persists across restarts
- [ ] Configuration files (`app.toml`, `config.toml`) are properly set
- [ ] For upgrades: migrations are registered and tested on testnet first

## Resources

- **Comprehensive navigation**: See [llms.txt](https://docs.cosmos.network/llms.txt) for complete page-by-page documentation index
- **Start here**: [Cosmos SDK Start Here](https://docs.cosmos.network/sdk/latest/learn/start-here) — choose your learning path
- **Build a chain**: [Chain Quickstart](https://docs.cosmos.network/sdk/latest/tutorials/example/02-quickstart) — get running in minutes
- **Module concepts**: [Intro to Modules](https://docs.cosmos.network/sdk/latest/learn/concepts/modules) — understand module architecture
- **Transactions and messages**: [Transactions, Messages, and Queries](https://docs.cosmos.network/sdk/latest/learn/concepts/transactions) — how state changes work
- **Running nodes**: [Running a Node](https://docs.cosmos.network/sdk/latest/node/run-node) — validator setup and configuration
- **Module directory**: [Modules](https://docs.cosmos.network/sdk/latest/modules/modules) — reference for all built-in modules
- **API reference**: [gRPC and REST APIs](https://docs.cosmos.network/sdk/latest/api-reference/index) — query and transaction endpoints

---

> For additional documentation and navigation, see: https://docs.cosmos.network/llms.txt