Search code examples
solanaanchor-solanasolana-transaction-instruction

Is it possible to transfer tokens to account declared in remaining accounts?


Try to transfer tokens to one of the account declared in remaining_accounts list.

Here's the way I create CpiContext:

let cpi_context = CpiContext::new(ctx.accounts.token_program.to_account_info(), 
    Transfer {
        from: ctx.accounts.account_x.to_account_info(),
        to: ctx.remaining_accounts.first().unwrap().to_account_info(),
        authority: ctx.accounts.owner.to_account_info().clone()
  });

I got error related to CpiContext lifetime mismatch. Exact log error: lifetime mismatch ...but data from ctx flows into ctx here.

Why I want to use remaining accounts to transfer tokens? This transfer is optional depending on whether user decides to pass the account (referral links/affiliation). Other methods than passing account as remaining accounts to implement the optional transfer will be also highly appreciated.


Solution

  • Make sure that you help out Rust's lifetime inference in your instruction:

    pub fn your_instruction<'info>(ctx: Context<'_, '_, '_, 'info, YourContext<'info>>, ...)