sablier_network_program/jobs/take_snapshot/
create_snapshot.rs

1use anchor_lang::{prelude::*, solana_program::instruction::Instruction, InstructionData};
2use anchor_spl::associated_token::get_associated_token_address;
3use sablier_utils::thread::{ThreadResponse, PAYER_PUBKEY};
4
5use crate::{constants::*, state::*};
6
7#[derive(Accounts)]
8pub struct TakeSnapshotCreateSnapshot<'info> {
9    #[account(address = Config::pubkey())]
10    pub config: AccountLoader<'info, Config>,
11
12    #[account(mut)]
13    pub payer: Signer<'info>,
14
15    #[account(
16        address = Registry::pubkey(),
17        constraint = registry.locked
18    )]
19    pub registry: Account<'info, Registry>,
20
21    #[account(
22        init,
23        seeds = [
24            SEED_SNAPSHOT,
25            (registry.current_epoch + 1).to_be_bytes().as_ref(),
26        ],
27        bump,
28        space = 8 + Snapshot::INIT_SPACE,
29        payer = payer
30    )]
31    pub snapshot: Account<'info, Snapshot>,
32
33    pub system_program: Program<'info, System>,
34
35    #[account(address = config.load()?.epoch_thread)]
36    pub thread: Signer<'info>,
37}
38
39pub fn handler(ctx: Context<TakeSnapshotCreateSnapshot>) -> Result<ThreadResponse> {
40    // Get accounts
41    let config_key = ctx.accounts.config.key();
42    let config = &ctx.accounts.config.load()?;
43    let registry = &ctx.accounts.registry;
44    let snapshot = &mut ctx.accounts.snapshot;
45    let system_program = &ctx.accounts.system_program;
46    let thread = &ctx.accounts.thread;
47
48    // Start a new snapshot.
49    snapshot.init(registry.current_epoch + 1)?;
50
51    Ok(ThreadResponse {
52        dynamic_instruction: if registry.total_workers > 0 {
53            // The registry has workers. Create a snapshot frame for the zeroth worker.
54            let snapshot_frame_pubkey = SnapshotFrame::pubkey(snapshot.key(), 0);
55            let worker_pubkey = Worker::pubkey(0);
56            Some(
57                Instruction {
58                    program_id: crate::ID,
59                    accounts: crate::accounts::TakeSnapshotCreateFrame {
60                        config: config_key,
61                        payer: PAYER_PUBKEY,
62                        registry: registry.key(),
63                        snapshot: snapshot.key(),
64                        snapshot_frame: snapshot_frame_pubkey,
65                        system_program: system_program.key(),
66                        thread: thread.key(),
67                        worker: worker_pubkey,
68                        worker_stake: get_associated_token_address(&worker_pubkey, &config.mint),
69                    }
70                    .to_account_metas(Some(true)),
71                    data: crate::instruction::TakeSnapshotCreateFrame {}.data(),
72                }
73                .into(),
74            )
75        } else {
76            None
77        },
78        close_to: None,
79        trigger: None,
80    })
81}