1

Let's say I have this CampaignCount account:

#[account]
pub struct CampaignCount {
    // I keep track of how many campaigns I have so far
    pub id: u32,
}

Imagine I need to refer to this in the CreateCampaign context:

#[derive(Accounts)]
pub struct CreateCampaign<'info> {
    // initializing a Campaign account
    #[account(init,payer = payer,space = 8 + 4 + 32,seeds =[SEED.as_bytes()],bump,)]
    pub campaign: Account<'info, Campaign>,
    #[account(
        mut,
        seeds = [COUNT_SEED.as_bytes()],
        bump,
    )]
    pub count: Account<'info, CampaignCount>, 
 // ....    
}

I need to reach CampaignCount inside CreateCampaign with this code:

  #[account(
        mut,
        seeds = [COUNT_SEED.as_bytes()],
        bump,
    )]

How come this code will make sure that I will get the correct account? Maybe when I created CampaignCount, I got it after 5th bump. (If there is already a created account with given SEED, bump will iterate down from 255 to find an available account address) How come this code will know it and get me the correct account?

1 Answer 1

1

When you derive it on the front end, e.g.:

[countKey, countBump] = PublicKey.findProgramAddressSync(
      [Buffer.from(COUNT_SEED)],
      program.programId
);

or on chain with anchor_lang::prelude::Pubkey::find_program_address(...) you're going to get the first bump it can find, starting with 255 and going down.

You can keep going and get another valid address with the same seeds but another (lower) bump, but this is rarely used: it's much easier to just change the seeds. There isn't a library function to find the "next" valid bump, as the find address function just returns when it finds a valid address, it doesn't care if the account is occupied.

The anchor constraints will read your seeds + bump (from the bump map, or as an instruction arg previously) and validate that they derive to the address of the Account provided. Without a bump, it can just call find_program_address until it finds that same first valid bump.

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.