miclockwork_network_program/state/
worker.rs

1use anchor_lang::{prelude::*, AnchorDeserialize};
2
3use crate::errors::*;
4
5pub const SEED_WORKER: &[u8] = b"worker";
6
7/// Worker
8#[account]
9#[derive(Debug)]
10pub struct Worker {
11    /// The worker's authority (owner).
12    pub authority: Pubkey,
13    /// The number of lamports claimable by the authority as commission for running the worker.
14    pub commission_balance: u64,
15    /// Integer between 0 and 100 determining the percentage of fees worker will keep as commission.
16    pub commission_rate: u64,
17    /// The worker's id.
18    pub id: u64,
19    /// The worker's signatory address (used to sign txs).
20    pub signatory: Pubkey,
21    /// The number delegations allocated to this worker.
22    pub total_delegations: u64,
23}
24
25impl Worker {
26    pub fn pubkey(id: u64) -> Pubkey {
27        Pubkey::find_program_address(&[SEED_WORKER, id.to_be_bytes().as_ref()], &crate::ID).0
28    }
29}
30
31/// WorkerSettings
32#[derive(AnchorSerialize, AnchorDeserialize)]
33pub struct WorkerSettings {
34    pub commission_rate: u64,
35    pub signatory: Pubkey,
36}
37
38/// WorkerAccount
39pub trait WorkerAccount {
40    fn pubkey(&self) -> Pubkey;
41
42    fn init(&mut self, authority: &mut Signer, id: u64, signatory: &Signer) -> Result<()>;
43
44    fn update(&mut self, settings: WorkerSettings) -> Result<()>;
45}
46
47impl WorkerAccount for Account<'_, Worker> {
48    fn pubkey(&self) -> Pubkey {
49        Worker::pubkey(self.id)
50    }
51
52    fn init(&mut self, authority: &mut Signer, id: u64, signatory: &Signer) -> Result<()> {
53        self.authority = authority.key();
54        self.commission_balance = 0;
55        self.commission_rate = 0;
56        self.id = id;
57        self.signatory = signatory.key();
58        self.total_delegations = 0;
59        Ok(())
60    }
61
62    fn update(&mut self, settings: WorkerSettings) -> Result<()> {
63        require!(
64            settings.commission_rate.ge(&0) && settings.commission_rate.le(&100),
65            ClockworkError::InvalidCommissionRate
66        );
67        self.commission_rate = settings.commission_rate;
68
69        require!(
70            settings.signatory.ne(&self.authority),
71            ClockworkError::InvalidSignatory
72        );
73        self.signatory = settings.signatory;
74        Ok(())
75    }
76}