每当尝试初始化PDA帐户时,我都会收到以下错误:
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,
}
我的测试代码如下:
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: [],
});
我曾尝试使用一个新生成的密钥对作为创建者,并将该密钥对添加到签名者中,但我似乎无法实现这一点。
原来这段代码是创建PDA的正确方法:(我运行了一个测试验证器,所以它试图根据以前存在的合同执行!
正如您所提到的,您应该在执行之前关闭测试验证器终端
anchor test
anchor为您自己运行测试验证器,测试后您可以在solanaanchor项目根目录中看到测试分类账文件夹另一点是,您应该将testledger文件夹添加到.gitignore文件中。也许这会有所帮助。