sablier_network_program/state/
pool.rs

1use std::collections::VecDeque;
2
3use anchor_lang::{prelude::*, AnchorDeserialize};
4
5use crate::constants::SEED_POOL;
6
7const DEFAULT_POOL_SIZE: usize = 1;
8
9/**
10 * Pool
11 */
12
13#[account]
14#[derive(Debug)]
15pub struct Pool {
16    pub id: u64,
17    pub size: usize,
18    pub workers: VecDeque<Pubkey>,
19}
20
21impl Pool {
22    pub fn pubkey(id: u64) -> Pubkey {
23        Pubkey::find_program_address(&[SEED_POOL, id.to_be_bytes().as_ref()], &crate::ID).0
24    }
25}
26
27impl Space for Pool {
28    const INIT_SPACE: usize = 8 + DEFAULT_POOL_SIZE + 32;
29}
30
31/**
32 * PoolSettings
33 */
34
35#[derive(AnchorSerialize, AnchorDeserialize)]
36pub struct PoolSettings {
37    pub size: usize,
38}
39
40/**
41 * PoolAccount
42 */
43
44pub trait PoolAccount {
45    fn pubkey(&self) -> Pubkey;
46
47    fn init(&mut self, id: u64) -> Result<()>;
48
49    fn rotate(&mut self, worker: Pubkey) -> Result<()>;
50
51    fn update(&mut self, settings: &PoolSettings) -> Result<()>;
52}
53
54impl PoolAccount for Account<'_, Pool> {
55    fn pubkey(&self) -> Pubkey {
56        Pool::pubkey(self.id)
57    }
58
59    fn init(&mut self, id: u64) -> Result<()> {
60        self.id = id;
61        self.size = DEFAULT_POOL_SIZE;
62        self.workers = VecDeque::new();
63        Ok(())
64    }
65
66    fn rotate(&mut self, worker: Pubkey) -> Result<()> {
67        // Push new worker into the pool.
68        self.workers.push_back(worker);
69
70        // Drain pool to the configured size limit.
71        while self.workers.len() > self.size {
72            self.workers.pop_front();
73        }
74
75        Ok(())
76    }
77
78    fn update(&mut self, settings: &PoolSettings) -> Result<()> {
79        self.size = settings.size;
80
81        // Drain pool to the configured size limit.
82        while self.workers.len() > self.size {
83            self.workers.pop_front();
84        }
85
86        Ok(())
87    }
88}