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
use std::{
    cmp::Ordering,
    ops::{Deref, Div, DivAssign, Mul, MulAssign},
};

use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Decimal, Fraction, StdResult, Uint128};

use crate::querier::KujiraQuerier;

pub const REFERENCE_DECIMAL_PLACES: u8 = 6;

/// `HumanPrice` is returned from the oracle querier and is a decimal value
/// representing the exchange rate of the given denom, *without any normalization*.
///
/// # NOTE
/// Denominations with different decimals will have `value = amount * price.normalize(decimals)`
/// So do NOT use this value directly for calculations, but rather use the `NormalizedPrice`
#[cw_serde]
#[derive(Copy, Eq, PartialOrd, Ord)]
pub struct HumanPrice(Decimal);

impl HumanPrice {
    pub fn normalize(&self, decimals: u8) -> NormalizedPrice {
        NormalizedPrice::from_raw(self.0, decimals)
    }
}

impl From<Decimal> for HumanPrice {
    fn from(value: Decimal) -> Self {
        HumanPrice(value)
    }
}

impl From<HumanPrice> for Decimal {
    fn from(value: HumanPrice) -> Self {
        value.0
    }
}

/// `NormalizedPrice` should be used in all operations involving
/// calculating the value of coins given the oracle price.
/// **When comparing values of non-standard denominations, failing
/// to normalize the price can cause unexpected and incorrect results.**
///
/// Standard denominations have 6 decimal places, so we use that as
/// the reference point.
#[cw_serde]
#[derive(Copy, Eq, PartialOrd, Ord)]
pub struct NormalizedPrice(Decimal);

impl NormalizedPrice {
    /// This is unsafe because it does not check that the price is
    /// normalized to the reference decimal places.
    /// Most likely during testing.
    pub fn unsafe_unchecked(price: Decimal) -> Self {
        Self(price)
    }

    pub fn from_raw(price: Decimal, decimals: u8) -> Self {
        // delta is i16 because we subtract two u8s
        let delta: i16 = i16::from(REFERENCE_DECIMAL_PLACES) - i16::from(decimals);
        Self::from_delta(price, delta)
    }

    pub fn from_delta(price: Decimal, delta: i16) -> Self {
        match delta.cmp(&0) {
            Ordering::Equal => Self(price),
            Ordering::Greater => Self(Decimal::from_ratio(
                price.numerator() * Uint128::from(10u128.pow(u32::from(delta.unsigned_abs()))),
                price.denominator(),
            )),
            Ordering::Less => Self(Decimal::from_ratio(
                price.numerator(),
                price.denominator() * Uint128::from(10u128.pow(u32::from(delta.unsigned_abs()))),
            )),
        }
    }

    pub fn from_oracle<T: Into<String>>(
        querier: &KujiraQuerier,
        denom: T,
        decimals: u8,
    ) -> StdResult<Self> {
        querier
            .query_exchange_rate(denom)
            .map(|price| price.normalize(decimals))
    }

    pub fn inner(&self) -> Decimal {
        self.0
    }
}

impl Deref for NormalizedPrice {
    type Target = Decimal;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<NormalizedPrice> for Decimal {
    fn from(price: NormalizedPrice) -> Self {
        price.0
    }
}

impl Mul<NormalizedPrice> for NormalizedPrice {
    type Output = NormalizedPrice;

    fn mul(self, rhs: NormalizedPrice) -> Self::Output {
        NormalizedPrice(self.0 * rhs.0)
    }
}

impl MulAssign<NormalizedPrice> for NormalizedPrice {
    fn mul_assign(&mut self, rhs: NormalizedPrice) {
        self.0 *= rhs.0
    }
}

impl Div<NormalizedPrice> for NormalizedPrice {
    type Output = NormalizedPrice;

    fn div(self, rhs: NormalizedPrice) -> Self::Output {
        NormalizedPrice(self.0 / rhs.0)
    }
}

impl DivAssign<NormalizedPrice> for NormalizedPrice {
    fn div_assign(&mut self, rhs: NormalizedPrice) {
        self.0 /= rhs.0
    }
}

impl Mul<Uint128> for NormalizedPrice {
    type Output = Uint128;

    fn mul(self, rhs: Uint128) -> Self::Output {
        self.0 * rhs
    }
}

impl Mul<NormalizedPrice> for Uint128 {
    type Output = Uint128;

    fn mul(self, rhs: NormalizedPrice) -> Self::Output {
        rhs.0 * self
    }
}

impl MulAssign<NormalizedPrice> for Uint128 {
    fn mul_assign(&mut self, rhs: NormalizedPrice) {
        *self = *self * rhs.0
    }
}

impl Div<Uint128> for NormalizedPrice {
    type Output = Option<Uint128>;

    fn div(self, rhs: Uint128) -> Self::Output {
        self.0.inv().map(|inv| inv * rhs)
    }
}

impl Div<NormalizedPrice> for Uint128 {
    type Output = Option<Uint128>;

    fn div(self, rhs: NormalizedPrice) -> Self::Output {
        rhs.0.inv().map(|inv| inv * self)
    }
}
#[cfg(test)]
mod tests {
    use cosmwasm_std::Decimal;

    use super::{HumanPrice, NormalizedPrice};

    #[test]
    fn serialize_human_price() {
        let price = HumanPrice(Decimal::percent(459));
        let serialized = serde_json::to_string(&price).unwrap();
        assert_eq!(serialized, r#""4.59""#);
    }

    #[test]
    fn deserialize_human_price() {
        let price = HumanPrice(Decimal::percent(459));
        let deserialized: HumanPrice = serde_json::from_str(r#""4.59""#).unwrap();
        assert_eq!(price, deserialized);
    }

    #[test]
    fn serialize_normalized_price() {
        let price = NormalizedPrice(Decimal::percent(459));
        let serialized = serde_json::to_string(&price).unwrap();
        assert_eq!(serialized, r#""4.59""#);
    }

    #[test]
    fn deserialize_normalized_price() {
        let price = NormalizedPrice(Decimal::percent(459));
        let deserialized: NormalizedPrice = serde_json::from_str(r#""4.59""#).unwrap();
        assert_eq!(price, deserialized);
    }
}