3

I would like to create a PDA and close it in the same method, but can't find how.

if i use init and close, it says i should add mut, but if i add mut, it says it can't be used with init.

Why do i need to create and close the account in the same method ? this account is used in a CPI to receive funds and then send them back to other accounts.

The only solution i can see is creating this account in another method before calling this one, but if i can avoid it, that would be wonderfull.

1 Answer 1

3

You can try directly modifying the lamport balance of the PDA within the instruction where you init the account.

For example,

use anchor_lang::prelude::*;
declare_id!("CShtV32yVjfxG2kyGkpTcx4jbxYm6ZJBqfakkydgdyAY");

#[program]
mod hello_anchor {
    use super::*;

    pub fn initialize(ctx: Context<Initialize>, data: u64) -> Result<()> {
        ctx.accounts.new_account.data = data;
        msg!("Changed data to: {}!", data);

        let amount = **ctx
            .accounts
            .new_account
            .to_account_info()
            .try_borrow_mut_lamports()?;

        msg!("Lamports: {}!", amount);

        **ctx
            .accounts
            .new_account
            .to_account_info()
            .try_borrow_mut_lamports()? -= amount;

        **ctx.accounts.signer.try_borrow_mut_lamports()? += amount;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Initialize<'info> {
    #[account(init, payer = signer, space = 8 + 8)]
    pub new_account: Account<'info, NewAccount>,
    #[account(mut)]
    pub signer: Signer<'info>,
    pub system_program: Program<'info, System>,
}

#[account]
pub struct NewAccount {
    data: u64,
}
4
  • 1
    removing all the lamports is the same as close an account ? (for a pda i mean)
    – Effe2
    Commented Oct 2, 2023 at 15:51
  • 1
    yep, when you transfer out all the lamports from an account it effectively closes the account
    – john
    Commented Oct 2, 2023 at 16:41
  • 2
    In addition to removing all the lamports, to completely close an account, you should set its owner to the system program and reallocate its size to 0
    – Jon C
    Commented Oct 3, 2023 at 20:03
  • Anybody looking for more info on how this is done.. solana.stackexchange.com/questions/3136/…
    – ZeroNine
    Commented Jan 23 at 4:48

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.