3

I get the below error whenever try to initialize PDA account:

Error: failed to send transaction: Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account


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

 pub fn initialize(ctx: Context<Initialize>, bump:u8) -> ProgramResult {
        let base_account: &mut Account<BaseAccount> = &mut ctx.accounts.base_account;
        base_account.bump = bump;
        base_account.counter = Some(0);
        return Ok(());
    }
}



#[derive(Accounts)]
#[instruction(bump:u8)]
pub struct Initialize<'info> {
    #[account(
        seeds = [b"seed".as_ref()], 
        bump, init, payer = creator, space = 20000)]
    pub base_account: Account<'info, BaseAccount>,
    #[account(mut)]
    pub creator: Signer<'info>,
    #[account(address = system_program::ID)]
    pub system_program: AccountInfo<'info>,
}

#[account]
#[derive(Default)]
pub struct BaseAccount {
    pub counter: Option<u64>,
    pub bump: u8,
}

My test code looks like this:

const [baseAccountPDA, baseAccountPDABump] = await anchor.web3.PublicKey.findProgramAddress(
      [Buffer.from("seed")],
      program.programId
    );

    await program.rpc.initialize(baseAccountPDABump, {
      accounts: {
        baseAccount: baseAccountPDA,
        creator: program.provider.wallet.publicKey,
        systemProgram: anchor.web3.SystemProgram.programId,
      },
      signers: [],
    });

I have tried using a newly generated keypair as the creator, and adding that keypair to the signers, but i cannot seem to get this to work.

2 Answers 2

2

Turns out this code is the correct way to create a PDA :) I had a test-validator running so it was trying to execute against a previously existing contract!

Sign up to request clarification or add additional context in comments.

Comments

1

as you mentioned you should close test-validator terminal before execute

anchor test

anchor run test-validator for you by itself and after test you can see the test-ledger folder inside your solana anchor project root another point is you should add test-ledger folder to your .gitignore file. maybe it helps.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.