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
78
79
80
81
82
83
84
use {
    crate::{errors::ClockworkError, objects::*},
    anchor_lang::{prelude::*, system_program::{transfer, Transfer}, solana_program::system_program},
};

const MAX_RATE_LIMIT: u64 = 32; 

/// Accounts required by the `queue_update` instruction.
#[derive(Accounts)]
#[instruction(
    kickoff_instruction: Option<InstructionData>, 
    rate_limit: Option<u64>, 
    trigger: Option<Trigger>
)]
pub struct QueueUpdate<'info> {
    /// The authority (owner) of the queue.
    #[account(mut)]
    pub authority: Signer<'info>,

    /// The queue to be updated.
    #[account(
        mut,
        address = queue.pubkey(),
        has_one = authority,
    )]
    pub queue: Account<'info, Queue>,

    /// The Solana system program
    #[account(address = system_program::ID)]
    pub system_program: Program<'info, System>,
}

pub fn handler(
    ctx: Context<QueueUpdate>, 
    kickoff_instruction: Option<InstructionData>, 
    rate_limit: Option<u64>, 
    trigger: Option<Trigger>
) -> Result<()> {
    
    // Get accounts
    let authority = &ctx.accounts.authority;
    let queue = &mut ctx.accounts.queue;
    let system_program = &ctx.accounts.system_program;

    // If provided, update the queue's first instruction
    if let Some(kickoff_instruction) = kickoff_instruction {
        queue.kickoff_instruction = kickoff_instruction;
    }

    // If provided, update the rate_limit
    if let Some(rate_limit) = rate_limit {
        require!(rate_limit.le(&MAX_RATE_LIMIT), ClockworkError::RateLimitTooLarge);
        queue.rate_limit = rate_limit;
    }

    // If provided, update the queue's trigger and reset the exec context
    if let Some(trigger) = trigger {
        queue.trigger = trigger;
        queue.exec_context = None;
    }

    // Reallocate mem for the queue account
    queue.realloc()?;

    // If lamports are required to maintain rent-exemption, pay them
    let data_len = 8 + queue.try_to_vec()?.len();
    let minimum_rent = Rent::get().unwrap().minimum_balance(data_len);
    if minimum_rent > queue.to_account_info().lamports() {
        transfer(
            CpiContext::new(
                system_program.to_account_info(),
                Transfer {
                    from: authority.to_account_info(),
                    to: queue.to_account_info(),
                },
            ),
            minimum_rent
                .checked_sub(queue.to_account_info().lamports())
                .unwrap(),
        )?;
    }

    Ok(())
}