You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Solana Anchor合约burn_liquidity出现temporary value dropped while borrow错误如何解决

错误根因

该借用错误来自Context::new调用时的临时值生命周期不匹配:

  • 构造remaining_accounts参数时直接传入临时切片&[pool_account.to_account_info()],该临时切片在Context::new语句执行完成后就会被销毁,但Context实例会持续持有该切片的引用,违反了Rust借用规则。
  • 局部变量cpi_accounts的生命周期和Context实例要求的生命周期不匹配。

解决方案

调整变量声明顺序,将临时值提前绑定到生命周期足够长的变量上,同时优先使用Anchor内置的CpiContext构造CPI调用上下文,避免手动构造Context出现生命周期问题。

调整后的代码

pub fn burn_liquidity(ctx: Context<BurnLiquidity>, _to: Pubkey) -> ProgramResult {
    let pool_account = &ctx.accounts.pool_account;
    let token1_account = &ctx.accounts.pool_token1_account;
    let token2_account = &ctx.accounts.pool_token2_account;
    let source = &ctx.accounts.source;
    let (reserve1, reserve2) = (pool_account.token1_balance, pool_account.token2_balance);
    let balance1: u64 = token1_account.amount;
    let balance2: u64 = token2_account.amount;
    let liquidity = source.amount;
    let total_supply = ctx.accounts.mint.supply;
    let amount1 = liquidity as f64 * balance1 as f64 / total_supply as f64;
    let amount2 = liquidity as f64 * balance2 as f64 / total_supply as f64;

    // 提前绑定remaining accounts到变量,延长生命周期
    let remaining_accounts = vec![pool_account.to_account_info()];
    // 构造CPI账户
    let cpi_accounts = UpdatePool {
        pool_account: pool_account.clone(),
    };
    // 用Anchor的CpiContext构造调用上下文,自动处理生命周期
    let update_ctx = CpiContext::new(
        ctx.accounts.system_program.to_account_info(),
        cpi_accounts,
    ).with_remaining_accounts(remaining_accounts);

    let update_data = UpdateData {
        token1: pool_account.token1.to_string(),
        token2: pool_account.token2.to_string(),
        token1_amount: amount1 as u64,
        token2_amount: amount2 as u64,
    };
    update_pool(update_ctx, update_data)?;

    Ok(())
}

关键修改点

  • 移除了不必要的内部嵌套作用域,避免变量被提前销毁
  • 将remaining_accounts提前绑定到Vec变量,生命周期和函数周期一致
  • 改用Anchor官方提供的CpiContext构造CPI上下文,自动处理引用生命周期匹配,不需要手动调用Context::new
  • 给update_pool调用加上了?操作符正确传播错误返回值

内容的提问来源于stack exchange,提问作者mohan A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 20:54:02