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
use super::Treasury;
use crate::pda::PDA;

use anchor_lang::prelude::*;
use anchor_lang::AccountDeserialize;

use std::convert::TryFrom;

pub const SEED_FEE: &[u8] = b"fee";

/**
 * Fee
 */

#[account]
#[derive(Debug)]
pub struct Fee {
    pub daemon: Pubkey,
    pub balance: u64,
    pub bump: u8,
}

impl TryFrom<Vec<u8>> for Fee {
    type Error = Error;
    fn try_from(data: Vec<u8>) -> std::result::Result<Self, Self::Error> {
        Fee::try_deserialize(&mut data.as_slice())
    }
}

impl Fee {
    pub fn pda(daemon: Pubkey) -> PDA {
        Pubkey::find_program_address(&[SEED_FEE, daemon.as_ref()], &crate::ID)
    }
}

/**
 * FeeAccount
 */

pub trait FeeAccount {
    fn init(&mut self, daemon: Pubkey, bump: u8) -> Result<()>;

    fn collect(&mut self, treasury: &mut Account<Treasury>) -> Result<()>;
}

impl FeeAccount for Account<'_, Fee> {
    fn init(&mut self, daemon: Pubkey, bump: u8) -> Result<()> {
        self.daemon = daemon;
        self.balance = 0;
        self.bump = bump;
        Ok(())
    }

    fn collect(&mut self, treasury: &mut Account<Treasury>) -> Result<()> {
        // Collect lamports from fee account to treasury.
        **self.to_account_info().try_borrow_mut_lamports()? = self
            .to_account_info()
            .lamports()
            .checked_sub(self.balance)
            .unwrap();
        **treasury.to_account_info().try_borrow_mut_lamports()? = treasury
            .to_account_info()
            .lamports()
            .checked_add(self.balance)
            .unwrap();

        // Zero out the collectable balance.
        self.balance = 0;

        Ok(())
    }
}