Rust/Anchor临时值释放报错求助:seeds变量生命周期问题
修复Solana Rust程序中签名种子的类型错误
问题描述
编写Solana指令时,使用PDA签名进行CPI转账时触发类型错误,错误由seeds变量引发,尝试两种写法均未解决:
代码示例1
pub fn exec_payout(ctx: Context<MyInstruction>, amount: u64, bump:u8, p1:Pubkey, p2:Pubkey, rstring:String) -> Result<()> { let cpi_program = ctx.accounts.system_program.to_account_info(); let cpi_accounts = system_program::Transfer { from: ctx.accounts.account_a.clone(), to: ctx.accounts.account_b.clone(), }; let seeds = [rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), &[bump]].as_slice(); let seedz = &[seeds.clone()]; let cpi_context = CpiContext::new(cpi_program, cpi_accounts) .with_signer(seedz); system_program::transfer(cpi_context, amount)?; Ok(()) }
代码示例2
let cpi_context = CpiContext::new(cpi_program, cpi_accounts) .with_signer(&[&[rstring.as_bytes().as_ref(), p1.as_ref(), p2.as_ref(), &[bump]]]);
错误信息(翻译自截图)
类型不匹配:expected a slice of &[u8], found a slice of &[&[u8]]``the trait bound &[&[u8]]: AsRef<[u8]> is not satisfied
解决方案
问题源于种子的嵌套层级错误,with_signer方法要求参数为&[&[u8]]——即一组签名种子数组,每个元素是完整的PDA种子字节切片,你的写法多嵌套了一层。
修正后的代码
pub fn exec_payout(ctx: Context<MyInstruction>, amount: u64, bump:u8, p1:Pubkey, p2:Pubkey, rstring:String) -> Result<()> { let cpi_program = ctx.accounts.system_program.to_account_info(); let cpi_accounts = system_program::Transfer { from: ctx.accounts.account_a.clone(), to: ctx.accounts.account_b.clone(), }; // 构造PDA种子数组:每个元素为&[u8]类型 let seeds = &[ rstring.as_bytes(), p1.as_ref(), p2.as_ref(), &[bump] ]; let cpi_context = CpiContext::new(cpi_program, cpi_accounts) .with_signer(seeds); // 直接传入符合类型要求的种子切片 system_program::transfer(cpi_context, amount)?; Ok(()) }
关键说明
rstring.as_bytes()本身就是&[u8]类型,无需额外调用as_ref()- 种子数组
seeds的类型为&[&[u8]],完全匹配with_signer的参数要求 - 不要将种子数组再包裹进另一层切片(如
&[seeds]),否则会导致类型变为&[&[&[u8]]],不符合方法参数规范
内容的提问来源于stack exchange,提问作者Sing
相关产品推荐
相关产品推荐

