use crate::errors::AntegenFiberError;
use crate::state::Fiber;
use anchor_lang::prelude::*;
#[derive(Accounts)]
pub struct Close<'info> {
#[account(mut)]
pub thread: Signer<'info>,
#[account(mut)]
pub fiber: UncheckedAccount<'info>,
}
pub fn close(ctx: Context<Close>) -> Result<()> {
let fiber_info = ctx.accounts.fiber.to_account_info();
let thread_info = ctx.accounts.thread.to_account_info();
let read = {
let data = fiber_info.try_borrow_data()?;
Fiber::try_deserialize(&mut &data[..])?
};
require!(
read.thread() == thread_info.key(),
AntegenFiberError::InvalidFiberPDA
);
sweep_fiber_lamports(&fiber_info, &thread_info)?;
Ok(())
}
pub(crate) fn sweep_fiber_lamports<'info>(
fiber: &AccountInfo<'info>,
thread: &AccountInfo<'info>,
) -> Result<()> {
let fiber_lamports = fiber.lamports();
**thread.try_borrow_mut_lamports()? = thread
.lamports()
.checked_add(fiber_lamports)
.ok_or(ProgramError::ArithmeticOverflow)?;
**fiber.try_borrow_mut_lamports()? = 0;
let mut data = fiber.try_borrow_mut_data()?;
for byte in data.iter_mut() {
*byte = 0;
}
if data.len() >= 8 {
data[..8].copy_from_slice(&[0xff; 8]);
}
Ok(())
}