Created
August 28, 2025 16:01
-
-
Save yuhcee/8962db853f524b857b86136bb3748ce8 to your computer and use it in GitHub Desktop.
An Anchor poll program with create and vote instructions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| use anchor_lang::prelude::*; | |
| declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS"); | |
| #[program] | |
| pub mod anchor_poll { | |
| use super::*; | |
| pub fn create_poll(ctx: Context<CreatePoll>, question: String, options: Vec<String>) -> Result<()> { | |
| let poll = &mut ctx.accounts.poll; | |
| poll.question = question; | |
| poll.options = options.into_iter().map(|option| (option, 0)).collect(); | |
| poll.creator = *ctx.accounts.user.key; | |
| Ok(()) | |
| } | |
| pub fn vote(ctx: Context<Vote>, option_index: u8) -> Result<()> { | |
| let poll = &mut ctx.accounts.poll; | |
| if let Some((_, count)) = poll.options.get_mut(option_index as usize) { | |
| *count += 1; | |
| } else { | |
| return err!(PollError::InvalidOption); | |
| } | |
| Ok(()) | |
| } | |
| } | |
| #[account] | |
| pub struct Poll { | |
| pub question: String, | |
| pub options: Vec<(String, u64)>, | |
| pub creator: Pubkey, | |
| } | |
| #[derive(Accounts)] | |
| pub struct CreatePoll<'info> { | |
| #[account(init, payer = user, space = 8 + 32 + 4 + 256 + 4 + 256)] // Adjust space as needed | |
| pub poll: Account<'info, Poll>, | |
| #[account(mut)] | |
| pub user: Signer<'info>, | |
| pub system_program: Program<'info, System>, | |
| } | |
| #[derive(Accounts)] | |
| pub struct Vote<'info> { | |
| #[account(mut)] | |
| pub poll: Account<'info, Poll>, | |
| pub user: Signer<'info>, | |
| } | |
| #[error_code] | |
| pub enum PollError { | |
| #[msg("Invalid option selected.")] | |
| InvalidOption, | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment