Skip to main content

chronicle_core/
config.rs

1//! Book configuration. Every capacity and the whole tick grid are fixed
2//! at construction (ARCHITECTURE.md section 3.2); nothing resizes later,
3//! which is what makes the zero steady-state allocation contract
4//! possible.
5
6use crate::error::BookError;
7use crate::types::StpPolicy;
8
9/// Static configuration for one [`crate::Book`].
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct BookConfig {
12    /// Arena capacity: the maximum number of simultaneously live orders.
13    /// At least 1 and at most 2^31 - 2, so slot indices can reserve
14    /// `u32::MAX` as NIL.
15    pub max_orders: u32,
16    /// Number of price ticks on the grid. A multiple of 64, at least 64,
17    /// at most 2^22.
18    pub grid_len: u32,
19    /// Quote units per tick, at least 1.
20    pub tick_size: u64,
21    /// Tick value of grid index 0. A price whose tick is `t` maps to grid
22    /// index `t - grid_start_tick`.
23    pub grid_start_tick: u64,
24    /// Self-trade prevention policy applied when a command does not name
25    /// one (executes from Milestone 2).
26    pub default_stp: StpPolicy,
27}
28
29impl BookConfig {
30    /// The tick value one past the last tick on the grid.
31    ///
32    /// # Errors
33    ///
34    /// Returns [`BookError::InvalidConfig`] if the grid end overflows
35    /// `u64` (the m9a construction bound, ARCHITECTURE.md section 3.2).
36    pub fn grid_end_tick(&self) -> Result<u64, BookError> {
37        self.grid_start_tick
38            .checked_add(u64::from(self.grid_len))
39            .ok_or(BookError::InvalidConfig {
40                field: "grid_start_tick + grid_len",
41                rule: "the grid end must fit in u64 (checked_add at construction)",
42            })
43    }
44
45    /// Smallest valid raw price on the grid, in quote units.
46    ///
47    /// Price zero is never valid on a [`crate::Book`] (ARCHITECTURE.md
48    /// section 3.2), so when `grid_start_tick` is `0` the lowest
49    /// addressable price tick is `1` (`tick_size`); otherwise it is
50    /// `grid_start_tick * tick_size`.
51    ///
52    /// # Examples
53    ///
54    /// ```
55    /// use chronicle_core::{BookConfig, StpPolicy};
56    ///
57    /// let cfg = BookConfig {
58    ///     max_orders: 64,
59    ///     grid_len: 640,
60    ///     tick_size: 5,
61    ///     grid_start_tick: 100,
62    ///     default_stp: StpPolicy::CancelIncoming,
63    /// };
64    /// assert_eq!(cfg.min_price(), 500);
65    /// assert_eq!(cfg.max_price().unwrap(), 3695);
66    /// ```
67    #[must_use]
68    pub const fn min_price(&self) -> u64 {
69        let first_tick = if self.grid_start_tick == 0 {
70            1
71        } else {
72            self.grid_start_tick
73        };
74        first_tick.saturating_mul(self.tick_size)
75    }
76
77    /// Largest valid raw price on the grid, in quote units:
78    /// `(grid_start_tick + grid_len - 1) * tick_size`.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`BookError::InvalidConfig`] when `grid_len` or
83    /// `tick_size` is zero or when the grid end or highest raw price
84    /// overflows `u64`.
85    pub fn max_price(&self) -> Result<u64, BookError> {
86        if self.grid_len == 0 {
87            return Err(BookError::InvalidConfig {
88                field: "grid_len",
89                rule: "must be a multiple of 64, at least 64, at most 2^22",
90            });
91        }
92        if self.tick_size == 0 {
93            return Err(BookError::InvalidConfig {
94                field: "tick_size",
95                rule: "must be at least 1",
96            });
97        }
98        let end = self.grid_end_tick()?;
99        let highest_tick = end - 1;
100        highest_tick
101            .checked_mul(self.tick_size)
102            .ok_or(BookError::InvalidConfig {
103                field: "grid end * tick_size",
104                rule: "the largest raw price on the grid must fit in u64",
105            })
106    }
107
108    /// Validate every construction rule.
109    ///
110    /// # Errors
111    ///
112    /// Returns [`BookError::InvalidConfig`] naming the first field and
113    /// rule that fail.
114    pub fn validate(&self) -> Result<(), BookError> {
115        if self.max_orders == 0 || self.max_orders > (1 << 31) - 2 {
116            return Err(BookError::InvalidConfig {
117                field: "max_orders",
118                rule: "must be at least 1 and at most 2^31 - 2",
119            });
120        }
121        if self.grid_len < 64 || !self.grid_len.is_multiple_of(64) || self.grid_len > 1 << 22 {
122            return Err(BookError::InvalidConfig {
123                field: "grid_len",
124                rule: "must be a multiple of 64, at least 64, at most 2^22",
125            });
126        }
127        if self.tick_size == 0 {
128            return Err(BookError::InvalidConfig {
129                field: "tick_size",
130                rule: "must be at least 1",
131            });
132        }
133        let _ = self.max_price()?;
134        Ok(())
135    }
136
137    /// Raw price (quote units) of an absolute tick value. Callers pass
138    /// only ticks inside the validated grid, so the multiplication
139    /// cannot overflow (see [`BookConfig::validate`]).
140    #[must_use]
141    pub(crate) const fn price_of_tick(&self, tick: u64) -> u64 {
142        tick * self.tick_size
143    }
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn base() -> BookConfig {
151        BookConfig {
152            max_orders: 1024,
153            grid_len: 4096,
154            tick_size: 1,
155            grid_start_tick: 1,
156            default_stp: StpPolicy::CancelIncoming,
157        }
158    }
159
160    #[test]
161    fn valid_config_passes() {
162        assert!(base().validate().is_ok());
163    }
164
165    #[test]
166    fn grid_end_overflow_is_a_config_error() {
167        let mut cfg = base();
168        cfg.grid_start_tick = u64::MAX - 10;
169        cfg.grid_len = 64;
170        assert!(matches!(
171            cfg.validate(),
172            Err(BookError::InvalidConfig { .. })
173        ));
174    }
175
176    #[test]
177    fn grid_len_must_be_a_multiple_of_64() {
178        let mut cfg = base();
179        cfg.grid_len = 100;
180        assert!(matches!(
181            cfg.validate(),
182            Err(BookError::InvalidConfig { .. })
183        ));
184    }
185}