0

I am trying to transfer 0.1 SOL from the signer account to all the accounts passed in the remaining_accounts to the function call. Here's a breakdown of the code.

anchor

    pub fn purchase_package(ctx: Context<PurchasePackage>) -> Result<()> {
        let total_amount: u64 = ctx.accounts.user.to_account_info().lamports();
        let LAMPORTS_PER_SOL: u64 = 1_000_000_000; // Number of lamports in one SOL
        let transfer_amount: u64 = LAMPORTS_PER_SOL / 10; // 0.1 SOL in lamports

        for i in 0..ctx.remaining_accounts.len() {
            let account_info: &AccountInfo = &ctx.remaining_accounts[i];

            if !account_info.is_writable || account_info.is_signer {
                return Err(ErrorCode::InvalidAccount.into());
            }

            let transfer_instruction = system_instruction::transfer(
                &ctx.accounts.user.key(),
                account_info.key,
                transfer_amount,
            );

            // Use a more explicit invocation pattern
            invoke(
                &transfer_instruction,
                &[
                    ctx.accounts.user.to_account_info(),
                    account_info.clone(), // Cloning here to get a new reference
                ],
            )?;

            distributed_amount += transfer_amount;
        }

        Ok(())
    }

The Javascript to call this function:

const response = await program.methods.purchasePackage().accounts({
          user: wallet.publicKey,
          systemProgram: SystemProgram.programId,
          lpWallet: lpWallet,
    })
    .signers([wallet.payer])
    .remainingAccounts(referralChainArray.map((referral) => ({
      pubkey: referral,
      isWritable: true,
      isSigner: false
    })))

When I build the anchor contract, I get error saying:

ctx.accounts.user.to_account_info()
^^^^^^^^^^^^^^^^^^^^^^argument requires that `'2` must outlive `'1`

I also tried passing the clone() of the account, but the error still persists.

1 Answer 1

0

This is a Rust issue. There isn't enough information given about the error in the question, but I think it might be borrowing parts of ctx.accounts.user: using key() and to_account_info().

Try changing the instruction creation to the following:

            let user_key = ctx.accounts.user.key();
            let transfer_instruction = system_instruction::transfer(
                &user_key,
                account_info.key,
                transfer_amount,
            );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.