Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
2.4 kB
1
Indexable
Never
use anchor_lang::prelude::*;

// This is your program's public key and it will update
// automatically when you build the project.
declare_id!("9bCY7hbhpQozuoPn8yDDQ77YuQgDwKaCkAWqHYNBFmvM");

#[program]
mod hello_anchor {
    use super::*;

    pub fn create_proposal(
        ctx: Context<CreateProposal>,
        title: String,
        description: String,
        choices: Vec<String>,
        deadline: u64,
    ) -> Result<()> {
        let proposal_account = &mut ctx.accounts.proposal;

        // Verifier < 10 choices sinon erreur
        require!(
            choices.len() as u8 > MAX_COUNT_OF_CHOICES as u8,
            VoteError::NotManyChoices
        );

        proposal_account.title = title;
        proposal_account.description = description;
        proposal_account.deadline = deadline;

        let mut vec_choices = Vec::new();

        for choice in choices {
            let option = Choice {
                label: choice,
                count: 0,
            };

            vec_choices.push(option);
        }

        proposal_account.choices = vec_choices;

        Ok(())
    }

    pub fn vote(ctx: Context<TODO>, choice: u8) -> Result<()> {
        let proposal_account = &mut ctx.accounts.proposal;
        // Vérifier que l'index choice de l'utlisateur est bien dans la taille du Vec, sinon erreur
        // +1

        // 1 vote max par addresse
        Ok(())
    }
}

const MAX_COUNT_OF_CHOICES: usize = 10;

#[derive(Accounts)]
pub struct CreateProposal<'info> {
    #[account(init, payer = signer, space = 8 + 32 + 32 + (32 + 8) * MAX_COUNT_OF_CHOICES + 8)]
    pub proposal: Account<'info, Proposal>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[derive(Accounts)]
pub struct Cast<'info> {
    #[account(init, payer = signer, space = 8 + 32 + 32 + (32 + 8) * MAX_COUNT_OF_CHOICES + 8)]
    pub proposal: Account<'info, Proposal>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct Proposal {
    title: String,
    description: String,
    choices: Vec<Choice>,
    deadline: u64,
}

#[derive(AnchorSerialize, AnchorDeserialize, Clone)]
pub struct Choice {
    label: String,
    count: u64,
}

pub enum VoteError {
    NotManyChoices,
}
Leave a Comment