Practical Applications of PDAs

Program-Derived Addresses (PDAs)

Chapter 5: Practical Applications of PDAs

PDAs are versatile—here, we’ll build a voting system as an example.

  • Key Points:

    • Store state (e.g., votes) in PDAs.

    • Restrict access to authorized users.

    • Example: Each proposal gets a PDA.

  • Code Example:

#[account]
pub struct Proposal {
    pub yes_votes: u64,
    pub no_votes: u64,
}

pub fn vote(ctx: Context<Vote>, is_yes: bool) -> Result<()> {
    if is_yes {
        ctx.accounts.proposal.yes_votes += 1;
    } else {
        ctx.accounts.proposal.no_votes += 1;
    }
    Ok(())
}
  • Interactivity: Cast votes and see the tallies update in real time.

Last updated