triggr-program 0.1.1

Created with Anchor
Documentation
pub use crate::state::*;
use anchor_lang::{prelude::*, system_program::{System}};

// Only an account which authority is specified correctly can be used to derive the authority
// the authority is not stored in the parent account but it's linked by derivation.
// The authority is the payer of initializing the parent account

#[derive(Accounts)]
#[instruction(condition_tree: AdjacencyTree)]
pub struct CreateTrigger<'info> {
    /// CHECK: Used for parent account seeds check
    #[account(mut)]
    signer: Signer<'info>,

    #[account(
        mut, 
        seeds = ["user".as_bytes(), &signer.key().to_bytes()], 
        bump, 
        realloc = 8 + User::MIN_SIZE + (user.active_triggers.len() * 32) + 8 + 4, 
        realloc::payer = signer, 
        realloc::zero = true
    )]
    user: Account<'info, User>,

    #[account(
        init, 
        seeds = ["trigger".as_bytes(), &signer.key().to_bytes()[..], &user.trigger_count.to_le_bytes()], 
        bump, 
        space = 8 + Trigger::get_size(&condition_tree),
        payer = signer
    )]
    trigger: Account<'info, Trigger>,


    system_program: Program<'info, System>,
}

pub fn handler(
    ctx: Context<CreateTrigger>,
    condition_tree: AdjacencyTree,
    lifetime: Lifetime,
    workflow_title: String
) -> Result<()> {

    // log lifetime
    *ctx.accounts.trigger = Trigger::new(
        ctx.accounts.signer.key(),
        condition_tree,
        lifetime,
        workflow_title,
        ctx.accounts.user.trigger_count,
    );

    // Increment user's total trigger count
    ctx.accounts.user.trigger_count += 1;

msg!("trigger: {:?}", ctx.accounts.trigger);

    if ctx.accounts.trigger.status == Status::Active {
        
        // Add trigger to user's active triggers
        ctx.accounts
            .user
            .active_triggers
            .push(ctx.accounts.trigger.key());
    }

    Ok(())
}