Overview
The Cosmos SDK uses a modular architecture where applications are composed of independent, reusable modules. Each module encapsulates specific functionality, state, and business logic while interacting with other modules through well-defined interfaces.Module Interface
Module Lifecycle Hooks
Modules can implement optional lifecycle interfaces:PreBlocker
- Processing vote extensions
- Updating consensus parameters
BeginBlocker
- Mint inflation rewards
- Distribute staking rewards
- Update validator set
EndBlocker
- Process validator updates
- Mature unbonding delegations
- Execute governance proposals
Additional Hooks
Module Structure
A typical module contains:Keeper Pattern
Keepers manage module state and provide controlled access to other modules:Keeper Constructor
Dependency Injection
Modules use depinject for wiring dependencies.Module Configuration
Define a protobuf configuration message:Provider Functions
Service Registration
Modules register message and query services:Message Server
Query Server
Module Manager
The ModuleManager coordinates all modules:Module Ordering
Modules execute in specified order:Common Module Patterns
Account Management
Modules can hold tokens through module accounts:Permissions
Hooks
Modules can define hooks for other modules to implement:Genesis
Modules define their genesis state:Module Communication
Keeper Interfaces
Modules depend on interfaces, not concrete keepers:Object Capability Model
Modules receive only the capabilities they need:Example Module: Counter
A minimal example module:Built-in Modules
x/auth
Account authentication and management
x/bank
Token transfers and balances
x/staking
Proof-of-Stake staking logic
x/gov
On-chain governance
x/distribution
Fee distribution to stakers
x/slashing
Validator slashing penalties
Best Practices
Use Collections for State
Use Collections for State
Use the
collections package for type-safe state management instead of raw KVStore access.Define Expected Keepers
Define Expected Keepers
Depend on interfaces (expected keepers) rather than concrete keeper types.
Implement Only Needed Hooks
Implement Only Needed Hooks
Don’t implement lifecycle hooks your module doesn’t need.
Use Module Accounts
Use Module Accounts
Store module-owned tokens in module accounts, not regular accounts.
Document Dependencies
Document Dependencies
Clearly document which modules yours depends on in the README.
Related Documentation
- State Management - Using Collections for module state
- BaseApp - How modules integrate with BaseApp
- Building Modules - Detailed module development guide