Skip to main content

antegen_thread_program/instructions/
thread_withdraw.rs

1use {
2    crate::{errors::*, *},
3    anchor_lang::prelude::*,
4};
5
6/// Accounts required by the `thread_withdraw` instruction.
7#[derive(Accounts)]
8#[instruction(amount: u64)]
9pub struct ThreadWithdraw<'info> {
10    /// The authority (owner) of the thread.
11    #[account()]
12    pub authority: Signer<'info>,
13
14    /// CHECK: The account to withdraw lamports to.
15    #[account(mut)]
16    pub pay_to: UncheckedAccount<'info>,
17
18    /// The thread to be.
19    #[account(
20        mut,
21        has_one = authority,
22        seeds = [
23            SEED_THREAD,
24            thread.authority.as_ref(),
25            thread.id.as_slice(),
26        ],
27        bump = thread.bump,
28    )]
29    pub thread: Account<'info, Thread>,
30}
31
32pub fn thread_withdraw(ctx: Context<ThreadWithdraw>, amount: u64) -> Result<()> {
33    // Get accounts
34    let pay_to = &mut ctx.accounts.pay_to;
35    let thread = &mut ctx.accounts.thread;
36
37    // Calculate the minimum rent threshold
38    let data_len = 8 + borsh::to_vec(&**thread)?.len();
39    let minimum_rent = Rent::get().unwrap().minimum_balance(data_len);
40    let post_balance = thread
41        .to_account_info()
42        .lamports()
43        .checked_sub(amount)
44        .unwrap();
45    require!(
46        post_balance.gt(&minimum_rent),
47        AntegenThreadError::WithdrawalTooLarge
48    );
49
50    // Withdraw balance from thread to the pay_to account
51    **thread.to_account_info().try_borrow_mut_lamports()? -= amount;
52    **pay_to.try_borrow_mut_lamports()? += amount;
53    Ok(())
54}