Skip to main content

antegen_thread_program/instructions/
fiber_close.rs

1use crate::{errors::AntegenThreadError, *};
2use anchor_lang::prelude::*;
3
4/// Accounts required by the `fiber_close` instruction.
5/// Validates authority, CPIs to Fiber Program to close, updates thread fiber tracking.
6#[derive(Accounts)]
7#[instruction(fiber_index: u8)]
8pub struct FiberClose<'info> {
9    /// The authority of the thread or the thread itself
10    #[account(
11        constraint = authority.key().eq(&thread.authority) || authority.key().eq(&thread.key())
12    )]
13    pub authority: Signer<'info>,
14
15    /// The thread to remove the fiber from
16    #[account(
17        mut,
18        constraint = thread.fiber_ids.contains(&fiber_index) @ AntegenThreadError::InvalidFiberIndex,
19        seeds = [
20            SEED_THREAD,
21            thread.authority.as_ref(),
22            thread.id.as_slice(),
23        ],
24        bump = thread.bump,
25    )]
26    pub thread: Account<'info, Thread>,
27
28    /// CHECK: fiber account to close (owned by Fiber Program). Shape-agnostic
29    /// — the fiber program validates the `thread` field against the signer.
30    #[account(mut)]
31    pub fiber: UncheckedAccount<'info>,
32
33    /// The Fiber Program for CPI
34    pub fiber_program: Program<'info, antegen_fiber_program::program::AntegenFiber>,
35}
36
37pub fn fiber_close(ctx: Context<FiberClose>, fiber_index: u8) -> Result<()> {
38    let thread = &mut ctx.accounts.thread;
39
40    // If we're closing the current fiber, advance to next one first
41    if thread.fiber_cursor.eq(&fiber_index) && thread.fiber_ids.len().gt(&1) {
42        thread.advance_to_next_fiber();
43    }
44
45    thread.fiber_ids.retain(|&x| x != fiber_index);
46    if thread.fiber_ids.is_empty() {
47        thread.fiber_cursor = 0;
48    }
49
50    thread.sign(|seeds| {
51        antegen_fiber_program::cpi::close(CpiContext::new_with_signer(
52            ctx.accounts.fiber_program.key(),
53            antegen_fiber_program::cpi::accounts::Close {
54                thread: thread.to_account_info(),
55                fiber: ctx.accounts.fiber.to_account_info(),
56            },
57            &[seeds],
58        ))
59    })?;
60
61    Ok(())
62}