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
use {
    crate::state::*,
    anchor_lang::prelude::*,
    clockwork_scheduler::{response::TaskResponse, state::Queue},
};

#[derive(Accounts)]
pub struct SnapshotClose<'info> {
    #[account(seeds = [SEED_AUTHORITY], bump)]
    pub authority: Account<'info, Authority>,

    #[account(signer, has_one = authority, constraint = cleanup_queue.name.eq("cleanup"))]
    pub cleanup_queue: Account<'info, Queue>,

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

    #[account(mut, has_one = authority, constraint = snapshot_queue.name.eq("snapshot"))]
    pub snapshot_queue: Account<'info, Queue>,
}

pub fn handler(ctx: Context<SnapshotClose>) -> Result<TaskResponse> {
    // Get accounts
    let snapshot_queue = &mut ctx.accounts.snapshot_queue;
    let snapshot = &mut ctx.accounts.snapshot;

    msg!("Closing snapshot {} {:#?}", snapshot.id, snapshot.status);

    // If snapshot is not archived, then noop and try again on next invocation.
    if snapshot.status != SnapshotStatus::Archived {
        return Ok(TaskResponse::default());
    }

    // If this snapshot has no entries, then close immediately
    let snapshot_pubkey = snapshot.key().clone();
    let snapshot_id = snapshot.id.clone();
    if snapshot.node_count == 0 {
        let snapshot_lamports = snapshot.to_account_info().lamports();
        **snapshot.to_account_info().lamports.borrow_mut() = 0;
        **snapshot_queue.to_account_info().lamports.borrow_mut() = snapshot_queue
            .to_account_info()
            .lamports()
            .checked_add(snapshot_lamports)
            .unwrap();
    } else {
        // Otherwise, set the status to closing
        snapshot.status = SnapshotStatus::Closing;
    }

    // Use dynamic accounts to run the next invocation with the next snapshot
    let next_snapshot_pubkey = Snapshot::pubkey(snapshot_id.checked_add(1).unwrap());
    Ok(TaskResponse {
        dynamic_accounts: Some(
            ctx.accounts
                .to_account_metas(None)
                .iter()
                .map(|acc| match acc.pubkey {
                    _ if acc.pubkey == snapshot_pubkey => next_snapshot_pubkey,
                    _ => acc.pubkey,
                })
                .collect(),
        ),
    })
}