1

Why haven't we given mut to the account Poll but given it to the Signer despite the fact that both accounts will be modified

#![allow(clippy::result_large_err)]

use anchor_lang::prelude::*;

declare_id!("AsjZ3kWAUSQRNt2pZVeJkywhZ6gpLpHZmJjduPmKZDZZ");

#[program]
pub mod voting {
    use super::*;

    pub fn initialize_poll(
        ctx: Context<InitializePoll>,
        poll_id: u64,
        description: String,
        poll_start: u64,
        poll_end: u64,
    ) -> Result<()> {
        let poll = &mut ctx.accounts.poll;
        poll.poll_id = poll_id;
        poll.description = description;
        poll.poll_start = poll_start;
        poll.poll_end = poll_end;
        poll.candidate_amount = 0;
        Ok(())
    }
}

#[derive(Accounts)]
#[instruction(poll_id: u64)]
pub struct InitializePoll<'info> {
    #[account(mut)]
    pub signer: Signer<'info>,

    #[account(
        init,
        payer = signer,
        space = 8 + Poll::INIT_SPACE,
        seeds = [poll_id.to_le_bytes().as_ref()],
        bump
    )]
    pub poll: Account<'info, Poll>,

    pub system_program: Program<'info, System>,
}

#[account]
#[derive(InitSpace)]
pub struct Poll {
    pub poll_id: u64,
    #[max_len(280)]
    pub description: String,
    pub poll_start: u64,
    pub poll_end: u64,
    pub candidate_amount: u64,
}

This code is from Solana Bootcamp official youtube video

1 Answer 1

1

The mut is an anchor constraint that marks the signer account mutables. This is because we will deduct lamports to pay for tx fees and any other fees e.g creation of the poll account.

Poll on the other hand is our data account that we are creating. It does not exist and as such we have to use the init constraint together with the other required fields such as the fee payer to initialize the account. We don't use mut on the account because it doesn't exists yet and we first have to create it. IF it did exist, and we needed to modify it, then we would market it as mutable by using the mut constraint.

check out other constraints on the anchor docs -> https://www.anchor-lang.com/docs/account-constraints

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.