What is the Cron Module?
The Cron module enables on-chain time-based automation by maintaining a registry of schedules and executing them at the appropriate block heights. Traditional blockchain applications require external triggers for time-sensitive operations, which creates several challenges:- Reliability concerns: External automation services might fail
- Centralization risks: Reliance on third-party services
- Coordination problems: Multiple actors might attempt the same operation
- Timing precision: Exact execution timing is difficult to ensure
Governance-Only Access: The Cron module is governance-gated. Only the Main DAO or Cron SubDAO can create, modify, or remove schedules. Individual users and contracts cannot directly interact with this module.
How does the Cron module work?
The Cron module enables on-chain time-based automation through several components working together:Schedule Registration
When a governance proposal creates a schedule, it specifies:- A unique name for identification
- The execution period (in blocks)
- One or more CosmWasm contract messages to execute
- The execution stage (BEGIN_BLOCKER or END_BLOCKER)
Execution Mechanism
The module hooks into Neutron’s block production process to check for schedules due for execution:-
During each block’s
BeginBlock
orEndBlock
phase (depending on the schedule’s execution_stage), the module queries for all schedules where: -
The module processes up to the configured
limit
of schedules per block to prevent resource exhaustion. -
For each schedule that meets the execution condition:
- The module constructs
wasmtypes.MsgExecuteContract
messages from the stored schedule data - Sets the sender as the Cron module account
- Sets funds to empty (no tokens are sent)
- Executes the messages using the WASM message server
- Updates the schedule’s
last_execute_height
to the current block height
- The module constructs
- Atomicity: All messages within a single schedule must succeed, or the entire schedule execution is rolled back.
Schedule Structure
A schedule is the core data structure in the Cron module:Execution Stages
The Cron module supports two execution stages:- BEGIN_BLOCKER: Schedules are executed at the beginning of the block, before any transactions. This is useful for operations that need to happen before other transactions in the block.
- END_BLOCKER: Schedules are executed at the end of the block, after all transactions. This is useful for operations that should occur after all other transactions in the block have been processed.
Governance-Based Management
- Schedule creation is controlled through governance (Main DAO or Cron SubDAO)
- Contracts cannot directly create schedules
- Schedule management requires governance proposals
Security Model
The Cron module implements several mechanisms to ensure security and prevent abuse:Execution Limits
To prevent DoS attacks and excessive resource consumption:- There’s a network-wide
limit
parameter (default: configurable) that restricts the number of schedules processed in a single block - If more schedules are due than the limit allows, some are delayed until subsequent blocks
- Schedules are processed in deterministic order (by last execution height, then alphabetically by name)
Message Validation
The module validates messages before execution:- Messages must be properly formatted JSON for CosmWasm contracts
- Invalid messages are rejected during schedule creation
- Execution failures are logged but don’t stop other schedules from executing
Protected State Access
The module’s state can only be modified through governance:- Direct state manipulation is not possible
- All state changes follow proper authorization checks
- Only governance proposals can manage schedules
Design Decisions
Why use block heights instead of timestamps?
Block heights provide several advantages over timestamps for scheduling:- Determinism: Block heights advance in a predictable manner, while block times can vary
- Simplicity: Working with integer increments is simpler than datetime calculations
- Consensus: All validators agree on the current block height without ambiguity
Why allow multiple messages per schedule?
Supporting multiple messages in a single schedule enables more complex workflows:- Atomicity: Related operations can be grouped together and either all succeed or all fail
- Efficiency: Reduces the number of separate schedules needed
- Sequence: Actions can be executed in a specific order within the same block
Why have different execution stages?
Having both BEGIN_BLOCKER and END_BLOCKER execution stages provides flexibility for different types of automated tasks:- State Preparation: BEGIN_BLOCKER allows setting up state before any transactions in the block
- Post-Processing: END_BLOCKER enables operations that should occur after all transactions
- Dependency Management: Different stages help manage dependencies between automated operations
Why governance-gate the module?
The governance-only access pattern serves several important purposes:- Security: Prevents malicious actors from creating disruptive schedules
- Resource Management: Ensures only necessary automation is added to the network
- Quality Control: Community review process for all automated tasks
- Accountability: Clear ownership and responsibility for scheduled operations
Implementation Considerations
Schedule Execution Order
When multiple schedules are due for execution in the same block, they are processed in a deterministic order:- First by
last_execution_height
(schedules that haven’t run in longer get priority) - Then by name (alphabetical order for ties)
Failure Handling
If a scheduled message fails during execution:- The entire schedule’s execution is rolled back (atomicity)
- The failure is logged with details
- The schedule’s
last_execution_height
is still updated to prevent retry loops - The schedule continues to be processed in future blocks if it’s periodic
Message Construction
When executing schedules, the module constructswasmtypes.MsgExecuteContract
messages:
Module Parameters
Network-wide parameters that can be adjusted through governance:Parameter | Description | Purpose |
---|---|---|
security_address | Address authorized to remove schedules | Emergency schedule removal |
limit | Maximum schedules executed per block | Resource management and DoS prevention |
Metrics and Monitoring
The Cron module collects several metrics for monitoring and observability:execute_ready_schedules
(histogram): Time taken to execute all ready schedules in EndBlockerschedule_count
(gauge): Current number of active schedulesschedule_executions_count
(counter): Total schedule executions, labeled by success/failure and schedule name
Best Practices for Integration
Error Handling
Since schedules might fail for various reasons, contracts should:- Make scheduled operations idempotent (safe to execute multiple times)
- Include validation within scheduled messages
- Implement fallback mechanisms for critical operations
- Design messages to be robust against temporary failures
Schedule Organization
For complex applications:- Use descriptive, consistent naming schemes for schedules
- Create separate schedules for independent operations
- Consider execution stages carefully to manage dependencies
- Group related operations into single schedules for atomicity
Typical Use Cases
The Cron module supports a wide range of time-based tasks:Financial Operations
- Interest accrual: Regular updates to lending/borrowing rates
- Vesting schedules: Gradual token unlocking over time
- Reward distribution: Periodic rewards to stakers or liquidity providers
- Fee collection: Regular harvesting of accumulated fees
Protocol Maintenance
- State cleanup: Removing expired or obsolete data
- Parameter updates: Scheduled changes to protocol parameters
- Rebalancing: Periodic adjustments to maintain target ratios
- Health checks: Regular validation of system state
Time-Sensitive Events
- Auction endings: Automatic settlement at deadline
- Governance execution: Implementing approved proposals after timelock
- Emergency procedures: Scheduled failsafes or circuit breakers
- Market operations: Regular price updates or arbitrage opportunities