hydra_dx_math/
lib.rs

1//! # HydraDX Math
2//!
3//! A collection of utilities to make performing liquidity pool
4//! calculations more convenient.
5
6#![cfg_attr(not(feature = "std"), no_std)]
7
8#[cfg(all(not(feature = "std"), test))]
9extern crate std;
10
11#[cfg(test)]
12#[macro_use]
13extern crate approx;
14
15pub mod fee;
16pub mod lbp;
17pub mod liquidity_mining;
18pub mod stableswap;
19pub mod transcendental;
20pub mod types;
21pub mod xyk;
22
23#[cfg(test)]
24mod tests;
25
26#[macro_export]
27macro_rules! ensure {
28    ($e:expr, $f:expr) => {
29        match $e {
30            true => (),
31            false => {
32                return Err($f);
33            }
34        }
35    };
36}
37
38#[macro_export]
39macro_rules! round_up {
40    ($e:expr) => {
41        $e.checked_add(FIXED_ROUND_UP).ok_or(Overflow)
42    };
43}
44
45#[macro_export]
46macro_rules! to_u256 {
47    ($($x:expr),+) => (
48        {($(U256::from($x)),+)}
49    );
50}
51
52#[macro_export]
53macro_rules! to_balance {
54    ($x:expr) => {
55        Balance::try_from($x).map_err(|_| Overflow)
56    };
57}
58
59#[macro_export]
60macro_rules! to_lbp_weight {
61    ($x:expr) => {
62        LBPWeight::try_from($x).map_err(|_| Overflow)
63    };
64}
65
66#[derive(PartialEq, Debug)]
67pub enum MathError {
68    Overflow,
69    InsufficientOutReserve,
70    ZeroWeight,
71    ZeroReserve,
72    ZeroDuration,
73}
74
75#[cfg(test)]
76mod conversion_tests {
77    use super::MathError::Overflow;
78    use crate::types::Balance;
79    use crate::types::LBPWeight;
80    use core::convert::TryFrom;
81
82    const FIXED_ROUND_UP: Balance = 1;
83
84    #[test]
85    fn test_conversion() {
86        let one: u32 = 1;
87        assert_eq!(to_balance!(one), Ok(Balance::from(1u128)));
88        assert_eq!(to_lbp_weight!(one), Ok(LBPWeight::from(1u32)));
89        assert_eq!(round_up!(Balance::from(one)), Ok(Balance::from(2u128)));
90    }
91}