Back
+20 XP
6/16
Challenge: Define a Counter Account (PDA)
Add a Counter account struct and update the Initialize accounts to create it as a Program Derived Address (PDA).
What is a PDA?
A PDA is an account address derived deterministically from seeds and the program ID. Unlike keypair accounts, PDAs don't have a private key — the program itself controls them. The same seeds always produce the same address.
For our counter: seeds = ["counter", user_wallet_pubkey] means each wallet gets exactly one counter per program.
Requirements
- Add a
Counterstruct with#[account]attribute containingpub count: u64andpub authority: Pubkey - Add lifetime
<'info>to theInitializestruct - Add a
counterfield with#[account(init, payer = user, space = 8 + 8 + 32, seeds = [b"counter", user.key().as_ref()], bump)] - Add a
userfield asSigner<'info>with#[account(mut)] - Add
system_programasProgram<'info, System>
What Each Constraint Does
init— creates the account (allocates space, assigns owner)payer = user— theuseraccount pays the rent depositspace = 8 + 8 + 32— 8 bytes discriminator + 8 bytesu64+ 32 bytesPubkeyseeds— the byte arrays used to derive the PDA addressbump— Anchor finds the valid bump seed automaticallymutonuser— required because their lamport balance changes (pays rent)
Tips
- The
Counterstruct goes outside the#[program]module - The
Initializestruct needs a lifetime parameter:pub struct Initialize<'info> - Make sure
counterhas typeAccount<'info, Counter> - The
authorityfield records who created the counter (useful for access control later)
Test Cases
Program compiles successfully
Input:
Expected: trueCounter struct is defined
Input:
Expected: true