use crate::{errors::ClockworkError, state::*};
use anchor_lang::{
prelude::*,
solana_program::system_program,
system_program::{transfer, Transfer},
};
#[derive(Accounts)]
#[instruction(settings: ThreadSettings)]
pub struct ThreadUpdate<'info> {
#[account(mut)]
pub authority: Signer<'info>,
#[account(address = system_program::ID)]
pub system_program: Program<'info, System>,
#[account(
mut,
seeds = [
SEED_THREAD,
thread.authority.as_ref(),
thread.id.as_slice(),
],
bump = thread.bump,
has_one = authority,
)]
pub thread: Account<'info, Thread>,
}
pub fn handler(ctx: Context<ThreadUpdate>, settings: ThreadSettings) -> Result<()> {
let authority = &ctx.accounts.authority;
let thread = &mut ctx.accounts.thread;
let system_program = &ctx.accounts.system_program;
if let Some(fee) = settings.fee {
thread.fee = fee;
}
if let Some(instructions) = settings.instructions {
thread.instructions = instructions;
}
if let Some(rate_limit) = settings.rate_limit {
thread.rate_limit = rate_limit;
}
if let Some(trigger) = settings.trigger {
require!(
std::mem::discriminant(&thread.trigger) == std::mem::discriminant(&trigger),
ClockworkError::InvalidTriggerVariant
);
thread.trigger = trigger.clone();
if thread.exec_context.is_some() {
thread.exec_context = Some(ExecContext {
trigger_context: match trigger {
Trigger::Account {
address: _,
offset: _,
size: _,
} => TriggerContext::Account { data_hash: 0 },
_ => thread.exec_context.unwrap().trigger_context,
},
..thread.exec_context.unwrap()
});
}
}
thread.realloc()?;
let data_len = 8 + thread.try_to_vec()?.len();
let minimum_rent = Rent::get().unwrap().minimum_balance(data_len);
if minimum_rent > thread.to_account_info().lamports() {
transfer(
CpiContext::new(
system_program.to_account_info(),
Transfer {
from: authority.to_account_info(),
to: thread.to_account_info(),
},
),
minimum_rent
.checked_sub(thread.to_account_info().lamports())
.unwrap(),
)?;
}
Ok(())
}