cronos_pool/state/
pool.rs

1use {
2    super::Config,
3    crate::pda::PDA,
4    anchor_lang::{prelude::*, AnchorDeserialize},
5    std::{collections::VecDeque, convert::TryFrom},
6};
7
8pub const SEED_POOL: &[u8] = b"pool";
9
10/**
11 * Pool
12 */
13
14#[account]
15#[derive(Debug)]
16pub struct Pool {
17    pub delegates: VecDeque<Pubkey>,
18}
19
20impl Pool {
21    pub fn pda() -> PDA {
22        Pubkey::find_program_address(&[SEED_POOL], &crate::ID)
23    }
24}
25
26impl TryFrom<Vec<u8>> for Pool {
27    type Error = Error;
28    fn try_from(data: Vec<u8>) -> std::result::Result<Self, Self::Error> {
29        Pool::try_deserialize(&mut data.as_slice())
30    }
31}
32
33/**
34 * PoolAccount
35 */
36
37pub trait PoolAccount {
38    fn new(&mut self) -> Result<()>;
39
40    fn rotate(&mut self, config: &Account<Config>, delegate: Pubkey) -> Result<()>;
41}
42
43impl PoolAccount for Account<'_, Pool> {
44    fn new(&mut self) -> Result<()> {
45        self.delegates = VecDeque::new();
46        Ok(())
47    }
48
49    fn rotate(&mut self, config: &Account<Config>, delegate: Pubkey) -> Result<()> {
50        // Pop a delegate out of the pool
51        self.delegates.pop_front();
52
53        // Push provided delegate into the pool
54        self.delegates.push_back(delegate);
55
56        // Drain pool to the configured size limit
57        while self.delegates.len() > config.pool_size {
58            self.delegates.pop_front();
59        }
60
61        Ok(())
62    }
63}