1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//! Common math routines.

use {
    crate::error::FarmError,
    arrayref::array_ref,
    solana_program::{hash::Hasher, msg, program_error::ProgramError, pubkey::Pubkey},
    std::fmt::Display,
};

pub fn checked_add<T>(arg1: T, arg2: T) -> Result<T, ProgramError>
where
    T: num_traits::PrimInt + Display,
{
    if let Some(res) = arg1.checked_add(&arg2) {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} + {}", arg1, arg2);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_sub<T>(arg1: T, arg2: T) -> Result<T, ProgramError>
where
    T: num_traits::PrimInt + Display,
{
    if let Some(res) = arg1.checked_sub(&arg2) {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} - {}", arg1, arg2);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_div<T>(arg1: T, arg2: T) -> Result<T, ProgramError>
where
    T: num_traits::PrimInt + Display,
{
    if let Some(res) = arg1.checked_div(&arg2) {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} / {}", arg1, arg2);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_mul<T>(arg1: T, arg2: T) -> Result<T, ProgramError>
where
    T: num_traits::PrimInt + Display,
{
    if let Some(res) = arg1.checked_mul(&arg2) {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} * {}", arg1, arg2);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_pow<T>(arg: T, exp: usize) -> Result<T, ProgramError>
where
    T: num_traits::PrimInt + Display,
{
    if let Some(res) = num_traits::checked_pow(arg, exp) {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} ^ {}", arg, exp);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_powf(arg: f64, exp: f64) -> Result<f64, ProgramError> {
    let res = f64::powf(arg, exp);
    if res.is_finite() {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} ^ {}", arg, exp);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_powi(arg: f64, exp: i32) -> Result<f64, ProgramError> {
    let res = if exp > 0 {
        f64::powi(arg, exp)
    } else {
        // wrokaround due to f64::powi() not working properly on-chain with negative exponent
        1.0 / f64::powi(arg, -exp)
    };
    if res.is_finite() {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} ^ {}", arg, exp);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_as_u64<T>(arg: T) -> Result<u64, ProgramError>
where
    T: Display + num_traits::ToPrimitive + Clone,
{
    let option: Option<u64> = num_traits::NumCast::from(arg.clone());
    if let Some(res) = option {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} as u64", arg);
        Err(FarmError::MathOverflow.into())
    }
}

pub fn checked_as_u128<T>(arg: T) -> Result<u128, ProgramError>
where
    T: Display + num_traits::ToPrimitive + Clone,
{
    let option: Option<u128> = num_traits::NumCast::from(arg.clone());
    if let Some(res) = option {
        Ok(res)
    } else {
        msg!("Error: Overflow in {} as u128", arg);
        Err(FarmError::MathOverflow.into())
    }
}

/// Returns numerator and denominator for the given fee
pub fn get_fee_parts(fee: f64) -> (u64, u64) {
    if fee <= 0.0 || fee > 1.0 {
        return (0, 1);
    }
    let mut numerator = fee;
    let mut denominator = 1u64;
    let mut i = 0;
    while numerator != (numerator as u64) as f64 && i < 6 {
        numerator *= 10.0;
        denominator *= 10;
        i += 1;
    }
    if numerator as u64 == denominator {
        (1, 1)
    } else {
        (numerator as u64, denominator)
    }
}

pub fn get_no_fee_amount(
    amount: u64,
    fee_numerator: u64,
    fee_denominator: u64,
) -> Result<u64, ProgramError> {
    if amount == 0 {
        return Ok(0);
    }
    checked_sub(
        amount,
        std::cmp::max(
            checked_as_u64(checked_div(
                checked_mul(amount as u128, fee_numerator as u128)?,
                fee_denominator as u128,
            )?)?,
            1,
        ),
    )
}

pub fn hash_address(current_hash: u64, address: &Pubkey) -> u64 {
    let mut input: Vec<u8>;
    let mut hasher = Hasher::default();
    if current_hash != 0 {
        input = current_hash.to_le_bytes().to_vec();
        input.extend_from_slice(address.as_ref());
    } else {
        input = address.as_ref().to_vec();
    }
    hasher.hash(input.as_slice());
    let hash = hasher.result();
    u64::from_le_bytes(*array_ref!(hash.as_ref(), 0, 8))
}