Back
+20 XP
11/16
Capstone: Complete Counter Program
This is the capstone challenge. Build the complete counter program with:
initialize— create the counter PDA, set to 0increment— add 1decrement— subtract 1, with underflow protection
Requirements
- Add a
decrementinstruction that subtracts 1 fromcounter.count - Use
require!(counter.count > 0, ErrorCode::Underflow)to prevent underflow - Add a
Decrementaccounts struct (same shape asIncrement— PDA counter + user Signer) - Define a custom
ErrorCodeenum with anUnderflowvariant
Custom Error Enum
Anchor uses #[error_code] to define program-specific errors:
#[error_code]
pub enum ErrorCode {
#[msg("Cannot decrement below zero")]
Underflow,
}
The #[msg] attribute provides the human-readable error message.
This Is It
When this compiles, you've built a real Solana program from scratch using PDAs — the production-standard pattern. The next lesson covers deployment.
Test Cases
Program compiles successfully
Input:
Expected: trueCode contains decrement function with underflow check
Input:
Expected: true