sablier_thread_program/instructions/
thread_instruction_add.rs

1use anchor_lang::{
2    prelude::*,
3    system_program::{transfer, Transfer},
4};
5use sablier_utils::account::AccountInfoExt;
6
7use crate::{constants::*, state::*};
8
9/// Accounts required by the `thread_instruction_add` instruction.
10#[derive(Accounts)]
11#[instruction(instruction: SerializableInstruction)]
12pub struct ThreadInstructionAdd<'info> {
13    /// The authority (owner) of the thread.
14    #[account(mut)]
15    pub authority: Signer<'info>,
16
17    /// The Solana system program.
18    pub system_program: Program<'info, System>,
19
20    /// The thread to be paused.
21    #[account(
22        mut,
23        seeds = [
24            SEED_THREAD,
25            thread.authority.as_ref(),
26            thread.id.as_slice(),
27            thread.domain.as_ref().unwrap_or(&Vec::new()).as_slice()
28        ],
29        bump = thread.bump,
30        has_one = authority
31    )]
32    pub thread: Account<'info, Thread>,
33}
34
35pub fn handler(
36    ctx: Context<ThreadInstructionAdd>,
37    instruction: SerializableInstruction,
38) -> Result<()> {
39    // Get accounts
40    let authority = &ctx.accounts.authority;
41    let thread = &mut ctx.accounts.thread;
42    let system_program = &ctx.accounts.system_program;
43
44    // Append the instruction.
45    thread.instructions.push(instruction);
46
47    // Reallocate mem for the thread account.
48    thread.realloc_account()?;
49
50    // If lamports are required to maintain rent-exemption, pay them.
51    let data_len = thread.data_len();
52    let minimum_rent = Rent::get()?.minimum_balance(data_len);
53    let thread_lamports = thread.get_lamports();
54    if minimum_rent > thread_lamports {
55        transfer(
56            CpiContext::new(
57                system_program.to_account_info(),
58                Transfer {
59                    from: authority.to_account_info(),
60                    to: thread.to_account_info(),
61                },
62            ),
63            minimum_rent - thread_lamports,
64        )?;
65    }
66
67    Ok(())
68}