1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
use anchor_lang::{prelude::*, solana_program::instruction::Instruction, InstructionData};
use sablier_utils::thread::ThreadResponse;

use crate::{constants::*, state::*};

#[derive(Accounts)]
pub struct DeleteSnapshotProcessSnapshot<'info> {
    #[account(address = Config::pubkey())]
    pub config: AccountLoader<'info, Config>,

    #[account(
        address = Registry::pubkey(),
        constraint = !registry.locked
    )]
    pub registry: Account<'info, Registry>,

    #[account(
        mut,
        seeds = [
            SEED_SNAPSHOT,
            snapshot.id.to_be_bytes().as_ref(),
        ],
        bump,
        constraint = snapshot.id < registry.current_epoch
    )]
    pub snapshot: Account<'info, Snapshot>,

    #[account(
        mut,
        address = config.load()?.epoch_thread
    )]
    pub thread: Signer<'info>,
}

pub fn handler(ctx: Context<DeleteSnapshotProcessSnapshot>) -> Result<ThreadResponse> {
    // Get accounts
    let config = &ctx.accounts.config;
    let registry = &ctx.accounts.registry;
    let snapshot = &mut ctx.accounts.snapshot;
    let thread = &mut ctx.accounts.thread;

    // If this snapshot has no entries, then close immediately
    if snapshot.total_frames == 0 {
        let snapshot_lamports = snapshot.get_lamports();
        snapshot.sub_lamports(snapshot_lamports)?;
        thread.add_lamports(snapshot_lamports)?;
    }

    // Build next instruction the thread.
    let dynamic_instruction = if snapshot.total_frames > 0 {
        // There are frames in this snapshot. Delete them.
        Some(
            Instruction {
                program_id: crate::ID,
                accounts: crate::accounts::DeleteSnapshotProcessFrame {
                    config: config.key(),
                    registry: registry.key(),
                    snapshot: snapshot.key(),
                    snapshot_frame: SnapshotFrame::pubkey(snapshot.key(), 0),
                    thread: thread.key(),
                }
                .to_account_metas(Some(true)),
                data: crate::instruction::DeleteSnapshotProcessFrame {}.data(),
            }
            .into(),
        )
    } else {
        // This snaphot has no frames. We are done!
        None
    };

    Ok(ThreadResponse {
        dynamic_instruction,
        close_to: None,
        trigger: None,
    })
}