templar_common/
price.rs

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
use std::marker::PhantomData;

use primitive_types::U256;

use crate::{
    asset::{AssetClass, BorrowAsset, CollateralAsset, FungibleAssetAmount},
    number::Decimal,
    oracle::pyth,
};

#[derive(Clone, Debug)]
pub struct Price<T: AssetClass> {
    _asset: PhantomData<T>,
    price: u128,
    confidence: u128,
    exponent: i32,
}

pub mod error {
    use thiserror::Error;

    #[derive(Clone, Debug, Error)]
    #[error("Bad price data: {0}")]
    pub enum PriceDataError {
        #[error("Reported negative price")]
        NegativePrice,
        #[error("Confidence interval too large")]
        ConfidenceIntervalTooLarge,
        #[error("Exponent out of bounds")]
        ExponentOutOfBounds,
    }
}

fn from_pyth_price<T: AssetClass>(
    pyth_price: &pyth::Price,
    decimals: i32,
) -> Result<Price<T>, error::PriceDataError> {
    let Ok(price) = u64::try_from(pyth_price.price.0) else {
        return Err(error::PriceDataError::NegativePrice);
    };

    if pyth_price.conf.0 >= price {
        return Err(error::PriceDataError::ConfidenceIntervalTooLarge);
    }

    let Some(exponent) = pyth_price.expo.checked_sub(decimals) else {
        return Err(error::PriceDataError::ExponentOutOfBounds);
    };

    Ok(Price {
        _asset: PhantomData,
        price: u128::from(price),
        confidence: u128::from(pyth_price.conf.0),
        exponent,
    })
}

#[derive(Clone, Debug)]
pub struct PricePair {
    pub collateral: Price<CollateralAsset>,
    pub borrow: Price<BorrowAsset>,
}

impl PricePair {
    /// # Errors
    ///
    /// - If the price data are invalid.
    pub fn new(
        collateral_price: &pyth::Price,
        collateral_decimals: i32,
        borrow_price: &pyth::Price,
        borrow_decimals: i32,
    ) -> Result<Self, error::PriceDataError> {
        Ok(Self {
            collateral: from_pyth_price(collateral_price, collateral_decimals)?,
            borrow: from_pyth_price(borrow_price, borrow_decimals)?,
        })
    }
}

pub trait Appraise<T: AssetClass> {
    fn valuation(&self, amount: FungibleAssetAmount<T>) -> Valuation;
}

pub trait Convert<T: AssetClass, U: AssetClass> {
    fn convert(&self, amount: FungibleAssetAmount<T>) -> Decimal;
}

impl Appraise<BorrowAsset> for PricePair {
    fn valuation(&self, amount: FungibleAssetAmount<BorrowAsset>) -> Valuation {
        Valuation::optimistic(amount, &self.borrow)
    }
}

impl Convert<BorrowAsset, CollateralAsset> for PricePair {
    fn convert(&self, amount: FungibleAssetAmount<BorrowAsset>) -> Decimal {
        #[allow(clippy::unwrap_used, reason = "not div0")]
        self.valuation(amount)
            .ratio(self.valuation(FungibleAssetAmount::<CollateralAsset>::new(1)))
            .unwrap()
    }
}

impl Appraise<CollateralAsset> for PricePair {
    fn valuation(&self, amount: FungibleAssetAmount<CollateralAsset>) -> Valuation {
        Valuation::pessimistic(amount, &self.collateral)
    }
}

impl Convert<CollateralAsset, BorrowAsset> for PricePair {
    fn convert(&self, amount: FungibleAssetAmount<CollateralAsset>) -> Decimal {
        #[allow(clippy::unwrap_used, reason = "not div0")]
        self.valuation(amount)
            .ratio(self.valuation(FungibleAssetAmount::<BorrowAsset>::new(1)))
            .unwrap()
    }
}

#[derive(Debug, Clone, Copy)]
pub struct Valuation {
    coefficient: primitive_types::U256,
    exponent: i32,
}

impl Valuation {
    pub fn optimistic<T: AssetClass>(amount: FungibleAssetAmount<T>, price: &Price<T>) -> Self {
        Self {
            coefficient: U256::from(u128::from(amount))
                * U256::from(price.price + price.confidence), // guaranteed not to overflow
            exponent: price.exponent,
        }
    }

    pub fn pessimistic<T: AssetClass>(amount: FungibleAssetAmount<T>, price: &Price<T>) -> Self {
        Self {
            coefficient: U256::from(u128::from(amount))
                * U256::from(price.price - price.confidence), // guaranteed not to overflow
            exponent: price.exponent,
        }
    }

    /// Returns the ratio between this and another `Valuation`.
    /// When the two `Valuation`s are within a few orders of magnitude of each
    /// other, the ratio will be as accurate as `Decimal` can represent.
    /// Otherwise, it will return a power of two close to the correct ratio.
    /// If the ratio is outside the representable range of `Decimal`, it will
    /// return `Decimal::MAX` if the ratio is too large, and `Decimal::MIN`
    /// (zero) if the ratio is too small.
    #[allow(clippy::cast_possible_wrap)]
    pub fn ratio(self, rhs: Self) -> Option<Decimal> {
        if rhs.coefficient.is_zero() {
            // div0
            return None;
        }

        if let Some(combined_exponents) = self
            .exponent
            .checked_sub(rhs.exponent)
            .and_then(|pow| Decimal::from(self.coefficient).mul_pow10(pow))
        {
            return Some(combined_exponents / Decimal::from(rhs.coefficient));
        }

        // Exact value calculation failed. This can happen when the difference
        // in exponents is extremely large, or when `self.coefficient` is
        // extremely small or extremely large.
        //
        // Approximate by logarithm instead.
        //
        // 345_060_773 / 103_873_643 (=3.321928094887362) is a close approximation of log2(10) (=3.32192809488736234...)
        let self_log2 =
            i64::from(self.exponent) * 345_060_773 / 103_873_643 + self.coefficient.bits() as i64;
        let rhs_log2 =
            i64::from(rhs.exponent) * 345_060_773 / 103_873_643 + rhs.coefficient.bits() as i64;

        let result_log2 = self_log2 - rhs_log2;

        Some(if result_log2 >= 0 {
            u32::try_from(result_log2)
                .ok()
                .and_then(Decimal::pow2_int)
                .unwrap_or(Decimal::MAX)
        } else {
            result_log2
                .checked_neg()
                .and_then(|n| u32::try_from(n).ok())
                .and_then(Decimal::pow2_int)
                .map_or(Decimal::MIN, |r| Decimal::ONE / r)
        })
    }
}

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

    use crate::dec;

    use super::*;

    #[test]
    fn valuation_eq() {
        let o = Valuation::optimistic(
            1000u128.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: 250,
                confidence: 12,
                exponent: -5,
            },
        );

        assert_eq!(o.coefficient, U256::from(1000 * (250 + 12)));
        assert_eq!(o.exponent, -5);

        let p = Valuation::pessimistic(
            1000u128.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: 250,
                confidence: 12,
                exponent: -5,
            },
        );

        assert_eq!(p.coefficient, U256::from(1000 * (250 - 12)));
        assert_eq!(p.exponent, -5);
    }

    #[test]
    fn valuation_ratio_equal() {
        let first = Valuation::optimistic(
            600u128.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: 100,
                confidence: 0,
                exponent: 4,
            },
        );
        let second = Valuation::pessimistic(
            60u128.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: 1000,
                confidence: 0,
                exponent: 4,
            },
        );

        assert_eq!(first.ratio(second).unwrap(), Decimal::ONE);
    }

    #[rstest]
    #[case(8, 1, 8, 0,      dec!("1"))]
    #[case(1, 25, 1, -2,    dec!("4"))]
    #[case(0, 1, 1, 0,      dec!("0"))]
    #[case(800, 2, 4, 2,    dec!("1"))]
    #[case(u128::MAX, 1, 1, i32::MIN, Decimal::MAX)]
    #[case(1, 1, 1, i32::MAX, Decimal::MIN)]
    // The following case returns a power of 2. Whereas the *correct* answer is
    // 1e+115, the approximation 2^382 is about 9.85e+114. Keep in mind Decimal
    // only supports a total of 115 whole decimal digits.
    #[case(u128::MAX, u128::MAX, 1, -115, Decimal::pow2_int(382).unwrap())]
    #[case(1, 1, 1, 39, Decimal::ZERO)]
    #[test]
    fn valuation_ratios(
        #[case] value: u128,
        #[case] divisor_value: u128,
        #[case] divisor_price: u128,
        #[case] divisor_exponent: i32,
        #[case] expected_result: impl Into<Decimal>,
    ) {
        let dividend = Valuation::optimistic(
            value.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: 1,
                confidence: 0,
                exponent: 0,
            },
        );

        let divisor = Valuation::optimistic(
            divisor_value.into(),
            &Price::<BorrowAsset> {
                _asset: PhantomData,
                price: divisor_price,
                confidence: 0,
                exponent: divisor_exponent,
            },
        );

        println!("{dividend:?}");
        println!("{divisor:?}");

        assert_eq!(dividend.ratio(divisor).unwrap(), expected_result.into());
    }
}