Anchor docs show how to create PDA accounts via the account validation struct:
// validation struct
#[derive(Accounts)]
pub struct CreateUserStats<'info> {
#[account(mut)]
pub user: Signer<'info>,
// space: 8 discriminator + 2 level + 4 name length + 200 name + 1 bump
#[account(
init,
payer = user,
space = 8 + 2 + 4 + 200 + 1, seeds = [b"user-stats", user.key().as_ref()], bump
)]
pub user_stats: Account<'info, UserStats>,
pub system_program: Program<'info, System>,
But how can we create accounts dynamically, only when they don't exist for instance. I have seen an example using accounts.system_program.create_account()
:
/// pseudo code
fn initialize(accounts) {
accounts.system_program.create_account(accounts.payer, accounts.counter);
let counter = deserialize(accounts.counter);
counter.count = 0;
}
but I don't know if there is something like this for creating PDA accounts (including seeds and bump).
So in summary:
- How can we check if a PDA account already exist within a function (not using struct).
- How can we create a PDA account within a function (not using struct).
- Is there a way to create a PDA account using struct only if doesn't exist already?