Overview
PostHandlers are optional middleware that execute after message handlers but before the transaction result is finalized. They use the same decorator pattern as AnteHandlers but are applied after state changes from message execution.PostHandler Signature
ctx: The current context with state after message executiontx: The transaction that was executedsimulate: Whether this is a simulation runsuccess: Whether message execution succeeded
Default PostHandler
The default PostHandler inx/auth is currently empty but provides the structure for chaining decorators:
x/auth/posthandler/post.go
PostDecorator Pattern
PostDecorators follow the same pattern as AnteDecorators:Use Cases
PostHandlers are useful for:1. Transaction Cleanup
Perform cleanup operations after transaction execution:2. Post-Transaction Hooks
Execute hooks after message processing:3. Metrics and Logging
Collect metrics about transaction execution:4. Fee Refunds
Refund unused gas or fees:Custom PostHandler Chain
Create a custom PostHandler by chaining decorators:Integrating PostHandler
Set the PostHandler in your app:PostHandler vs AnteHandler
| Feature | AnteHandler | PostHandler |
|---|---|---|
| Execution | Before message execution | After message execution |
| Purpose | Validation and preprocessing | Cleanup and post-processing |
| State Access | Pre-execution state | Post-execution state |
| Failure Impact | Prevents message execution | Can revert entire transaction |
| Common Uses | Signature verification, fee deduction | Metrics, hooks, refunds |
| Required | Yes (transaction won’t execute without) | No (optional) |
Important Considerations
State Changes
PostHandlers operate on the state after message execution:Error Handling
Errors from PostHandlers will fail the entire transaction:Simulation Mode
Handle simulation appropriately:Best Practices
- Lightweight Operations: Keep PostHandler logic fast and efficient
- Idempotency: Ensure operations are safe if called multiple times
- Error Handling: Be cautious about failing transactions in PostHandler
- Simulation: Always handle simulation mode correctly
- Logging: Use the context logger for debugging
- Gas: Be mindful of gas consumption in PostHandler operations
Example: Comprehensive PostHandler
See Also
- AnteHandler - Pre-transaction validation
- Transaction Lifecycle - Complete transaction flow
- Events - Event emission and querying