use {
super::Queue,
anchor_lang::{prelude::*, AnchorDeserialize},
std::convert::TryFrom,
};
const SEED_FEE: &[u8] = b"fee";
#[account]
#[derive(Debug)]
pub struct Fee {
pub balance: u64,
pub withholding: u64,
pub worker: Pubkey,
}
impl Fee {
pub fn pubkey(worker: Pubkey) -> Pubkey {
Pubkey::find_program_address(&[SEED_FEE, worker.as_ref()], &crate::ID).0
}
}
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())
}
}
pub trait FeeAccount {
fn pubkey(&self) -> Pubkey;
fn init(&mut self, worker: Pubkey) -> Result<()>;
fn claim_balance(&mut self, amount: u64, pay_to: &mut SystemAccount) -> Result<()>;
fn claim_withholding(&mut self, amount: u64, pay_to: &mut SystemAccount) -> Result<()>;
fn escrow_balance(&mut self, amount: u64, queue: &mut Account<Queue>) -> Result<()>;
fn escrow_withholding(&mut self, amount: u64, queue: &mut Account<Queue>) -> Result<()>;
}
impl FeeAccount for Account<'_, Fee> {
fn pubkey(&self) -> Pubkey {
Fee::pubkey(self.worker)
}
fn init(&mut self, worker: Pubkey) -> Result<()> {
self.worker = worker;
self.balance = 0;
self.withholding = 0;
Ok(())
}
fn claim_balance(&mut self, amount: u64, pay_to: &mut SystemAccount) -> Result<()> {
self.balance = self.balance.checked_sub(amount).unwrap();
**self.to_account_info().try_borrow_mut_lamports()? = self
.to_account_info()
.lamports()
.checked_sub(amount)
.unwrap();
**pay_to.to_account_info().try_borrow_mut_lamports()? = pay_to
.to_account_info()
.lamports()
.checked_add(amount)
.unwrap();
Ok(())
}
fn claim_withholding(&mut self, amount: u64, pay_to: &mut SystemAccount) -> Result<()> {
self.withholding = self.withholding.checked_sub(amount).unwrap();
**self.to_account_info().try_borrow_mut_lamports()? = self
.to_account_info()
.lamports()
.checked_sub(amount)
.unwrap();
**pay_to.to_account_info().try_borrow_mut_lamports()? = pay_to
.to_account_info()
.lamports()
.checked_add(amount)
.unwrap();
Ok(())
}
fn escrow_withholding(&mut self, amount: u64, queue: &mut Account<Queue>) -> Result<()> {
self.withholding = self.withholding.checked_add(amount).unwrap();
**queue.to_account_info().try_borrow_mut_lamports()? = queue
.to_account_info()
.lamports()
.checked_sub(amount)
.unwrap();
**self.to_account_info().try_borrow_mut_lamports()? = self
.to_account_info()
.lamports()
.checked_add(amount)
.unwrap();
Ok(())
}
fn escrow_balance(&mut self, amount: u64, queue: &mut Account<Queue>) -> Result<()> {
self.balance = self.balance.checked_add(amount).unwrap();
**queue.to_account_info().try_borrow_mut_lamports()? = queue
.to_account_info()
.lamports()
.checked_sub(amount)
.unwrap();
**self.to_account_info().try_borrow_mut_lamports()? = self
.to_account_info()
.lamports()
.checked_add(amount)
.unwrap();
Ok(())
}
}