在Solana Anchor框架内初始化PDA的正确方法



我正试图使用使用PDA的Rust/Anchor编写一个简单的Solana程序,但当我试图调用它时,即使没有发生CPI(可能是PDA帐户初始化?(,我也会遇到CPI错误。

这是程序代码:

use anchor_lang::prelude::*;
declare_id!("51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p");
#[program]
pub mod solana_sandbox {
use super::*;
pub fn initialize(ctx: Context<Initialize>, bump: u8) -> ProgramResult {
ctx.accounts.sandbox_account.bump = bump;
Ok(())
}
}
#[derive(Accounts)]
#[instruction(bump: u8)]
pub struct Initialize<'info> {
#[account(mut)]
pub signer: Signer<'info>,
#[account(
init,
seeds = [b"seed".as_ref()],
bump,
payer = signer,
)]
pub sandbox_account: Account<'info, SandboxAccount>,
pub system_program: Program<'info, System>,
}
#[account]
#[derive(Default)]
pub struct SandboxAccount {
pub bump: u8,
}

这是客户端代码:

const [sandboxPda, sandboxBump] = await PublicKey.findProgramAddress([Buffer.from('seed')], SystemProgram.programId);
await program.rpc.initialize(
sandboxBump,
{
accounts: {
signer: keypair.publicKey,
sandboxAccount: sandboxPda,
systemProgram: anchor.web3.SystemProgram.programId,
},
signers: [keypair],
instructions: []
});

当我运行上述程序时,我会得到以下内容:

Transaction simulation failed: Error processing Instruction 0: Cross-program invocation with unauthorized signer or writable account 
Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p invoke [1]
8ZiyjNgnFFPyw39NyMQE5FGETTjyUhSHUVQG3oKAFZiU's signer privilege escalated
Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p consumed 200000 of 200000 compute units
Program 51v31qHaEQniLoYuvvtXByZcfiyvog3R2EKC39EPD52p failed: Cross-program invocation with unauthorized signer or writable account

8ZiyjNgnFFPyw39NyMQE5FGETTjyUhSHUVQG3oKAFZiU是我传入的PDA地址,我使用的是anchor-cli 0.18.0

原来我在客户端代码中使用系统程序ID来派生PDA,而不是使用实际的程序ID。

应为:

const [sandboxPda, sandboxBump] = await PublicKey.findProgramAddress([Buffer.from('seed')], <PROGRAM_ID>);

相关内容

  • 没有找到相关文章

最新更新