gmsol-model 0.9.0

GMX-Solana is an extension of GMX on the Solana blockchain.
Documentation
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::fmt;

use num_traits::{
    CheckedAdd, CheckedDiv, CheckedMul, CheckedNeg, CheckedSub, FromPrimitive, One, Signed,
};

/// Num trait used in GMX.
pub trait Num:
    num_traits::Num
    + CheckedAdd
    + CheckedMul
    + CheckedSub
    + CheckedNeg
    + CheckedDiv
    + Clone
    + Ord
    + FromPrimitive
    + fmt::Debug
    + fmt::Display
{
}

impl<
        T: num_traits::Num
            + CheckedAdd
            + CheckedMul
            + CheckedSub
            + CheckedNeg
            + CheckedDiv
            + Clone
            + Ord
            + FromPrimitive
            + fmt::Debug
            + fmt::Display,
    > Num for T
{
}

/// Unsigned value that cannot be negative.
pub trait Unsigned: num_traits::Unsigned {
    /// The signed type.
    type Signed: TryFrom<Self> + UnsignedAbs<Unsigned = Self> + CheckedNeg;

    /// Convert to a signed value
    fn to_signed(&self) -> crate::Result<Self::Signed>
    where
        Self: Clone,
    {
        self.clone().try_into().map_err(|_| crate::Error::Convert)
    }

    /// Convert to a signed value with the given sign.
    fn to_signed_with_sign(&self, negative: bool) -> crate::Result<Self::Signed>
    where
        Self: Clone,
        Self::Signed: CheckedSub,
    {
        if negative {
            self.to_opposite_signed()
        } else {
            self.to_signed()
        }
    }

    /// Convert to opposite signed.
    fn to_opposite_signed(&self) -> crate::Result<Self::Signed>
    where
        Self: Clone,
        Self::Signed: CheckedSub,
    {
        self.to_signed()?
            .checked_neg()
            .ok_or(crate::Error::Computation("to opposite signed"))
    }

    /// Compute the absolute difference of two values.
    fn diff(self, other: Self) -> Self;

    /// Compute signed `self - other`.
    fn checked_signed_sub(self, other: Self) -> crate::Result<Self::Signed>
    where
        Self: Ord + Clone,
        Self::Signed: CheckedSub,
    {
        if self >= other {
            self.diff(other).to_signed()
        } else {
            self.diff(other).to_opposite_signed()
        }
    }

    /// Checked signed add.
    fn checked_add_with_signed(&self, other: &Self::Signed) -> Option<Self>
    where
        Self: CheckedAdd + CheckedSub,
    {
        let value = other.unsigned_abs();
        if other.is_positive() {
            self.checked_add(&value)
        } else {
            self.checked_sub(&value)
        }
    }

    /// Checked signed sub.
    fn checked_sub_with_signed(&self, other: &Self::Signed) -> Option<Self>
    where
        Self: CheckedAdd + CheckedSub,
    {
        let value = other.unsigned_abs();
        if other.is_positive() {
            self.checked_sub(&value)
        } else {
            self.checked_add(&value)
        }
    }

    /// Checked signed mul.
    fn checked_mul_with_signed(&self, other: &Self::Signed) -> Option<Self::Signed>
    where
        Self: CheckedMul,
    {
        let value = other.unsigned_abs();
        if other.is_negative() {
            Some(
                Self::Signed::try_from(self.checked_mul(&value)?)
                    .ok()?
                    .checked_neg()?,
            )
        } else {
            self.checked_mul(&value)?.try_into().ok()
        }
    }

    /// As divisor to checked divide other and round up magnitude.
    fn as_divisor_to_round_up_magnitude_div(&self, dividend: &Self::Signed) -> Option<Self::Signed>
    where
        Self: Clone,
        Self::Signed: CheckedSub + CheckedAdd + CheckedDiv,
    {
        if self.is_zero() {
            return None;
        }
        let divisor: Self::Signed = self.clone().try_into().ok()?;
        if dividend.is_negative() {
            dividend
                .checked_sub(&divisor)?
                .checked_add(&One::one())?
                .checked_div(&divisor)
        } else {
            dividend
                .checked_add(&divisor)?
                .checked_sub(&One::one())?
                .checked_div(&divisor)
        }
    }

    /// Checked round up division.
    fn checked_round_up_div(&self, divisor: &Self) -> Option<Self>
    where
        Self: CheckedAdd + CheckedSub + Clone + CheckedDiv,
    {
        if divisor.is_zero() {
            return None;
        }
        self.checked_add(divisor)?
            .checked_sub(&One::one())?
            .checked_div(divisor)
    }

    /// Bound the magnitude of a signed value.
    ///
    /// # Errors
    /// Return error if
    /// - `min > max`
    /// - `min` is greater than the maximum value representable by `Self::Signed`
    ///
    /// # Examples
    ///
    /// This method can be used to bound the magnitude of a signed value:
    /// ```
    /// # use gmsol_model::num::Unsigned;
    /// let a = -123i64;
    /// // Original value within bounds
    /// assert_eq!(Unsigned::bound_magnitude(&a, &0, &124u64).unwrap(), -123);
    /// // Value clamped to max magnitude
    /// assert_eq!(Unsigned::bound_magnitude(&a, &0, &120u64).unwrap(), -120);
    /// // Value clamped to min magnitude
    /// assert_eq!(Unsigned::bound_magnitude(&a, &124, &256u64).unwrap(), -124);
    ///
    /// let b = 123i64;
    /// // Original value within bounds
    /// assert_eq!(Unsigned::bound_magnitude(&b, &0, &124u64).unwrap(), 123);
    /// // Value clamped to max magnitude
    /// assert_eq!(Unsigned::bound_magnitude(&b, &0, &120u64).unwrap(), 120);
    /// // Value clamped to min magnitude
    /// assert_eq!(Unsigned::bound_magnitude(&b, &124, &256u64).unwrap(), 124);
    /// ```
    ///
    /// Returns an error if `min > max`:
    /// ```
    /// # use gmsol_model::num::Unsigned;
    /// let result = Unsigned::bound_magnitude(&0, &1u64, &0);
    /// assert!(result.is_err());
    /// ```
    ///
    /// Returns an error if `min` is greater than the maximum value representable by `Self::Signed`:
    /// ```
    /// # use gmsol_model::num::Unsigned;
    /// let result = Unsigned::bound_magnitude(&0, &(u64::MAX / 2 + 1), &u64::MAX);
    /// assert!(result.is_err());
    /// ```
    fn bound_magnitude(value: &Self::Signed, min: &Self, max: &Self) -> crate::Result<Self::Signed>
    where
        Self: Ord + Clone,
        Self::Signed: Clone + CheckedSub,
    {
        if min > max {
            return Err(crate::Error::InvalidArgument("min > max"));
        }
        let magnitude = value.unsigned_abs();
        let negative = value.is_negative();
        if magnitude < *min {
            min.to_signed_with_sign(negative)
        } else if magnitude > *max {
            max.to_signed_with_sign(negative)
        } else {
            Ok(value.clone())
        }
    }
}

/// Convert signed value to unsigned.
pub trait UnsignedAbs: Signed {
    /// Unsigned type.
    type Unsigned;

    /// Computes the absolute value and returns as an unsigned value.
    fn unsigned_abs(&self) -> Self::Unsigned;
}

/// Perform Mul-Div calculation with bigger range num type.
pub trait MulDiv: Unsigned {
    /// Calculates floor(self * numerator / denominator) with full precision.
    ///
    /// Returns `None` if the `denominator` is zero or overflow.
    fn checked_mul_div(&self, numerator: &Self, denominator: &Self) -> Option<Self>;

    /// Calculates ceil(self * numerator / denominator) with full precision.
    ///
    /// Returns `None` if the `denominator` is zero or overflow.
    fn checked_mul_div_ceil(&self, numerator: &Self, denominator: &Self) -> Option<Self>;

    /// Calculates floor(self * numerator / denominator) with full precision,
    /// where `numerator` is signed.
    ///
    /// Returns `None` if the `denominator` is zero or overflow.
    fn checked_mul_div_with_signed_numerator(
        &self,
        numerator: &Self::Signed,
        denominator: &Self,
    ) -> Option<Self::Signed> {
        let ans = self
            .checked_mul_div(&numerator.unsigned_abs(), denominator)?
            .try_into()
            .ok()?;
        if numerator.is_positive() {
            Some(ans)
        } else {
            ans.checked_neg()
        }
    }
}

impl Unsigned for u64 {
    type Signed = i64;

    fn diff(self, other: Self) -> Self {
        self.abs_diff(other)
    }
}

impl MulDiv for u64 {
    #[allow(clippy::arithmetic_side_effects)]
    fn checked_mul_div(&self, numerator: &Self, denominator: &Self) -> Option<Self> {
        if *denominator == 0 {
            return None;
        }
        let x = *self as u128;
        let numerator = *numerator as u128;
        let denominator = *denominator as u128;
        let ans = x * numerator / denominator;
        ans.try_into().ok()
    }

    #[allow(clippy::arithmetic_side_effects)]
    fn checked_mul_div_ceil(&self, numerator: &Self, denominator: &Self) -> Option<Self> {
        if *denominator == 0 {
            return None;
        }
        let x = *self as u128;
        let numerator = *numerator as u128;
        let denominator = *denominator as u128;
        let ans = (x * numerator).div_ceil(denominator);
        ans.try_into().ok()
    }
}

impl UnsignedAbs for i64 {
    type Unsigned = u64;

    fn unsigned_abs(&self) -> u64 {
        (*self).unsigned_abs()
    }
}

#[cfg(feature = "u128")]
/// Add support to `u128`.
mod u128 {
    use super::{MulDiv, Unsigned, UnsignedAbs};
    use ruint::aliases::U256;

    impl Unsigned for u128 {
        type Signed = i128;

        fn diff(self, other: Self) -> Self {
            self.abs_diff(other)
        }
    }

    impl UnsignedAbs for i128 {
        type Unsigned = u128;

        fn unsigned_abs(&self) -> u128 {
            (*self).unsigned_abs()
        }
    }

    impl MulDiv for u128 {
        #[allow(clippy::arithmetic_side_effects)]
        fn checked_mul_div(&self, numerator: &Self, denominator: &Self) -> Option<Self> {
            if *denominator == 0 {
                return None;
            }
            let x = U256::from(*self);
            let numerator = U256::from(*numerator);
            let denominator = U256::from(*denominator);
            let ans = x * numerator / denominator;
            ans.try_into().ok()
        }

        #[allow(clippy::arithmetic_side_effects)]
        fn checked_mul_div_ceil(&self, numerator: &Self, denominator: &Self) -> Option<Self> {
            if *denominator == 0 {
                return None;
            }
            let x = U256::from(*self);
            let numerator = U256::from(*numerator);
            let denominator = U256::from(*denominator);
            let ans = (x * numerator).div_ceil(denominator);
            ans.try_into().ok()
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn round_up_magnitude_division() {
        let b = 3u64;
        let positive = 1i64;
        let negative = -1i64;

        assert_eq!(b.as_divisor_to_round_up_magnitude_div(&positive), Some(1));
        assert_eq!(b.as_divisor_to_round_up_magnitude_div(&negative), Some(-1));
    }

    #[test]
    fn round_up_division() {
        let b = 3u64;
        let a = 1u64;
        assert_eq!(a.checked_round_up_div(&b), Some(1));
    }

    #[test]
    fn mul_div_ceil() {
        let a = 650_406_504u64;
        let a2 = 650_406_505u64;
        let b = 40_000_000_000u64;
        let c = 80_000_000_000u64;
        assert_eq!(a.checked_mul_div_ceil(&b, &c).unwrap(), 325_203_252);
        assert_eq!(a2.checked_mul_div_ceil(&b, &c).unwrap(), 325_203_253);
    }

    #[cfg(feature = "u128")]
    #[test]
    fn mul_div_ceil_u128() {
        let a = 650_406_504u128;
        let a2 = 650_406_505u128;
        let b = 40_000_000_000u128;
        let c = 80_000_000_000u128;
        assert_eq!(a.checked_mul_div_ceil(&b, &c).unwrap(), 325_203_252);
        assert_eq!(a2.checked_mul_div_ceil(&b, &c).unwrap(), 325_203_253);
    }

    #[test]
    fn bound_magnitude() {
        let a = -123i64;
        assert_eq!(Unsigned::bound_magnitude(&a, &0, &124u64).unwrap(), -123);
        assert_eq!(Unsigned::bound_magnitude(&a, &0, &120u64).unwrap(), -120);
        assert_eq!(Unsigned::bound_magnitude(&a, &124, &256u64).unwrap(), -124);
        assert_eq!(Unsigned::bound_magnitude(&a, &125, &125u64).unwrap(), -125);

        let b = 123i64;
        assert_eq!(Unsigned::bound_magnitude(&b, &0, &124u64).unwrap(), 123);
        assert_eq!(Unsigned::bound_magnitude(&b, &0, &120u64).unwrap(), 120);
        assert_eq!(Unsigned::bound_magnitude(&b, &124, &256u64).unwrap(), 124);
        assert_eq!(Unsigned::bound_magnitude(&b, &125, &125u64).unwrap(), 125);

        let c = 0i64;
        assert_eq!(Unsigned::bound_magnitude(&c, &1, &124u64).unwrap(), 1);

        let d = -0i64;
        assert_eq!(Unsigned::bound_magnitude(&d, &1, &124u64).unwrap(), 1);

        let result = Unsigned::bound_magnitude(&0, &u64::MAX, &u64::MAX);
        assert!(result.is_err());
    }
}