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
use crate::error::ContractError;
use cosmwasm_std::{Decimal, DecimalRangeExceeded, Fraction, Uint128};
use cosmwasm_std::{Deps, StdError};
use forward_ref::{forward_ref_binop, forward_ref_op_assign};
use schemars::JsonSchema;
use sei_cosmwasm::SeiQueryWrapper;
use semver::Version;
use serde::{Deserialize, Serialize};
use std::cmp::Ordering;
use std::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};
use std::{fmt, ops::BitXor};

#[derive(Copy, Clone, Serialize, Deserialize, PartialEq, JsonSchema, Debug, Eq)]
pub struct SignedDecimal {
    pub decimal: Decimal,
    pub negative: bool,
}

impl SignedDecimal {
    pub const fn zero() -> Self {
        SignedDecimal {
            decimal: Decimal::zero(),
            negative: false,
        }
    }
    pub const fn one() -> Self {
        SignedDecimal {
            decimal: Decimal::one(),
            negative: false,
        }
    }

    pub const fn new(decimal: Decimal) -> Self {
        SignedDecimal {
            decimal: decimal,
            negative: false,
        }
    }

    pub const fn new_from_ptr(decimal: &Decimal) -> Self {
        SignedDecimal {
            decimal: *decimal,
            negative: false,
        }
    }

    pub const fn new_negative(decimal: Decimal) -> Self {
        SignedDecimal {
            decimal: decimal,
            negative: true,
        }
    }

    pub const fn new_signed(decimal: Decimal, negative: bool) -> Self {
        SignedDecimal {
            decimal: decimal,
            negative: negative,
        }
    }

    pub fn from_atomics(
        atomics: impl Into<Uint128>,
        decimal_places: u32,
        negative: bool,
    ) -> Result<Self, DecimalRangeExceeded> {
        match Decimal::from_atomics(atomics, decimal_places) {
            Ok(decimal) => Result::Ok(SignedDecimal {
                decimal: decimal,
                negative: negative,
            }),
            Err(err) => Result::Err(err),
        }
    }

    pub fn negation(&self) -> Self {
        if self.decimal == Decimal::zero() {
            return *self;
        }
        return SignedDecimal {
            decimal: self.decimal,
            negative: !self.negative,
        };
    }

    pub fn is_zero(&self) -> bool {
        self.decimal == Decimal::zero()
    }

    pub fn positive_part(&self) -> SignedDecimal {
        if self.negative {
            return SignedDecimal::zero();
        }
        *self
    }
}

impl Ord for SignedDecimal {
    fn cmp(&self, other: &SignedDecimal) -> Ordering {
        if self.negative && other.negative {
            if self.decimal > other.decimal {
                Ordering::Less
            } else if self.decimal == other.decimal {
                Ordering::Equal
            } else {
                Ordering::Greater
            }
        } else if !self.negative && !other.negative {
            if self.decimal < other.decimal {
                Ordering::Less
            } else if self.decimal == other.decimal {
                Ordering::Equal
            } else {
                Ordering::Greater
            }
        } else if !self.negative && other.negative {
            Ordering::Greater
        } else {
            Ordering::Less
        }
    }
}

impl PartialOrd for SignedDecimal {
    fn partial_cmp(&self, other: &SignedDecimal) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Add for SignedDecimal {
    type Output = Self;

    fn add(self, other: Self) -> Self {
        if self.negative && other.negative {
            SignedDecimal {
                decimal: self.decimal + other.decimal,
                negative: true,
            }
        } else if self.negative && !other.negative {
            if self.decimal > other.decimal {
                SignedDecimal {
                    decimal: self.decimal - other.decimal,
                    negative: true,
                }
            } else {
                SignedDecimal {
                    decimal: other.decimal - self.decimal,
                    negative: false,
                }
            }
        } else if !self.negative && other.negative {
            if self.decimal >= other.decimal {
                SignedDecimal {
                    decimal: self.decimal - other.decimal,
                    negative: false,
                }
            } else {
                SignedDecimal {
                    decimal: other.decimal - self.decimal,
                    negative: true,
                }
            }
        } else {
            assert_eq!(!self.negative && !other.negative, true);
            SignedDecimal {
                decimal: self.decimal + other.decimal,
                negative: false,
            }
        }
    }
}
forward_ref_binop!(impl Add, add for SignedDecimal, SignedDecimal);

impl AddAssign for SignedDecimal {
    fn add_assign(&mut self, rhs: SignedDecimal) {
        *self = *self + rhs;
    }
}
forward_ref_op_assign!(impl AddAssign, add_assign for SignedDecimal, SignedDecimal);

impl Sub for SignedDecimal {
    type Output = Self;

    fn sub(self, other: Self) -> Self {
        if other.decimal == Decimal::zero() {
            return self;
        }
        self + SignedDecimal {
            decimal: other.decimal,
            negative: !other.negative,
        }
    }
}
forward_ref_binop!(impl Sub, sub for SignedDecimal, SignedDecimal);

impl SubAssign for SignedDecimal {
    fn sub_assign(&mut self, rhs: SignedDecimal) {
        *self = *self - rhs;
    }
}
forward_ref_op_assign!(impl SubAssign, sub_assign for SignedDecimal, SignedDecimal);

impl Mul for SignedDecimal {
    type Output = Self;

    #[allow(clippy::suspicious_arithmetic_impl)]
    fn mul(self, other: Self) -> Self {
        if (self.negative && other.negative) || (!self.negative && !other.negative) {
            SignedDecimal {
                decimal: self.decimal * other.decimal,
                negative: false,
            }
        } else {
            let mut is_result_negative = true;
            if self.decimal == Decimal::zero() || other.decimal == Decimal::zero() {
                is_result_negative = false
            }
            SignedDecimal {
                decimal: self.decimal * other.decimal,
                negative: is_result_negative,
            }
        }
    }
}

impl Fraction<Uint128> for SignedDecimal {
    #[inline]
    fn numerator(&self) -> Uint128 {
        self.decimal.numerator()
    }

    #[inline]
    fn denominator(&self) -> Uint128 {
        self.decimal.denominator()
    }

    /// Returns the multiplicative inverse `1/d` for decimal `d`.
    ///
    /// If `d` is zero, none is returned.
    fn inv(&self) -> Option<Self> {
        self.decimal.inv().map(|d| SignedDecimal {
            decimal: d,
            negative: self.negative,
        })
    }
}

/// SignedDecimal / SignedDecimal
impl Div for SignedDecimal {
    // The division of signeddecimal is a closed operation.
    type Output = Self;

    fn div(self, rhs: Self) -> Self::Output {
        if rhs.decimal.is_zero() {
            panic!("Cannot divide by zero-valued `SignedDecimal`!");
        }
        let reciprocal = rhs.decimal.inv().unwrap();
        let decimal_res = match reciprocal.checked_mul(self.decimal) {
            Ok(res) => res,
            Err(e) => panic!("{}", e),
        };
        match self.negative.bitxor(rhs.negative) {
            true => Self::new_negative(decimal_res),
            false => Self::new(decimal_res),
        }
    }
}

impl fmt::Display for SignedDecimal {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.negative {
            write!(f, "-{}", self.decimal)
        } else {
            write!(f, "{}", self.decimal)
        }
    }
}

fn epsilon() -> Decimal {
    Decimal::from_atomics(1u128, 8).unwrap()
}

pub fn roughly_equal(d1: Decimal, d2: Decimal) -> bool {
    roughly_equal_signed(SignedDecimal::new(d1), SignedDecimal::new(d2))
}

pub fn roughly_equal_signed(d1: SignedDecimal, d2: SignedDecimal) -> bool {
    (d1 - d2).decimal < epsilon()
}

// convert decimal to uint128, conservative round down
pub fn decimal2uint128_floor(d: Decimal) -> Uint128 {
    let base: u64 = 10; // to avoid overflow with 10^18
    let atomics = d.atomics();
    let decimal_places = d.decimal_places();
    atomics / Uint128::new(base.pow(decimal_places) as u128)
}

pub fn decimal2u128_floor(d: Decimal) -> u128 {
    let base: u64 = 10; // to avoid overflow with 10^18
    let atomics = d.atomics();
    let decimal_places = d.decimal_places();
    atomics.u128() / base.pow(decimal_places) as u128
}

pub fn decimal2u128_ceiling(d: Decimal) -> u128 {
    let base: u64 = 10; // to avoid overflow with 10^18
    let atomics = d.atomics();
    let decimal_places = d.decimal_places();
    let divisor = base.pow(decimal_places) as u128;
    (atomics.u128() + divisor - 1) / divisor
}

pub fn validate_migration(
    deps: Deps<SeiQueryWrapper>,
    contract_name: &str,
    contract_version: &str,
) -> Result<(), ContractError> {
    let ver = cw2::get_contract_version(deps.storage)?;
    // ensure we are migrating from an allowed contract
    if ver.contract != contract_name {
        return Err(StdError::generic_err("Can only upgrade from same type").into());
    }

    let storage_version: Version = ver.version.parse()?;
    let version: Version = contract_version.parse()?;
    if storage_version >= version {
        return Err(StdError::generic_err("Cannot upgrade from a newer version").into());
    }
    Ok(())
}