1use std::cmp;
2
3use pyra_types::SpotMarket;
4
5use crate::error::{MathError, MathResult};
6
7pub const SPOT_WEIGHT_PRECISION: u128 = 10_000;
9pub const SPOT_IMF_PRECISION: u128 = 1_000_000;
11pub const AMM_RESERVE_PRECISION: u128 = 1_000_000_000;
13
14fn isqrt(n: u128) -> u128 {
16 if n < 2 {
17 return n;
18 }
19 let mut x = 1u128 << ((128u32.saturating_sub(n.leading_zeros()).saturating_add(1)) / 2);
20 let mut y = x.checked_add(n.checked_div(x).unwrap_or(0)).unwrap_or(x) / 2;
21 while y < x {
22 x = y;
23 y = x.checked_add(n.checked_div(x).unwrap_or(0)).unwrap_or(x) / 2;
24 }
25 x
26}
27
28pub fn to_amm_precision(balance: u128, token_decimals: u32) -> MathResult<u128> {
30 let size_precision = 10u128
31 .checked_pow(token_decimals)
32 .ok_or(MathError::Overflow)?;
33
34 if size_precision > AMM_RESERVE_PRECISION {
35 let scale = size_precision
36 .checked_div(AMM_RESERVE_PRECISION)
37 .ok_or(MathError::Overflow)?;
38 balance.checked_div(scale).ok_or(MathError::Overflow)
39 } else {
40 balance
41 .checked_mul(AMM_RESERVE_PRECISION)
42 .ok_or(MathError::Overflow)?
43 .checked_div(size_precision)
44 .ok_or(MathError::Overflow)
45 }
46}
47
48pub fn calculate_scaled_initial_asset_weight(
52 spot_market: &SpotMarket,
53 oracle_price: u64,
54) -> MathResult<u128> {
55 let initial_asset_weight = spot_market.initial_asset_weight as u128;
56
57 if spot_market.scale_initial_asset_weight_start == 0 {
58 return Ok(initial_asset_weight);
59 }
60
61 let precision_decrease = 10u128
62 .checked_pow(19u32.saturating_sub(spot_market.decimals))
63 .ok_or(MathError::Overflow)?;
64
65 let deposit_tokens = (spot_market.deposit_balance)
66 .checked_mul(spot_market.cumulative_deposit_interest)
67 .ok_or(MathError::Overflow)?
68 .checked_div(precision_decrease)
69 .ok_or(MathError::Overflow)?;
70
71 let token_precision = 10u128
72 .checked_pow(spot_market.decimals)
73 .ok_or(MathError::Overflow)?;
74
75 let deposits_value = deposit_tokens
76 .checked_mul(oracle_price as u128)
77 .ok_or(MathError::Overflow)?
78 .checked_div(token_precision)
79 .ok_or(MathError::Overflow)?;
80
81 let threshold = spot_market.scale_initial_asset_weight_start as u128;
82 if deposits_value < threshold {
83 return Ok(initial_asset_weight);
84 }
85
86 initial_asset_weight
87 .checked_mul(threshold)
88 .ok_or(MathError::Overflow)?
89 .checked_div(deposits_value)
90 .ok_or(MathError::Overflow)
91}
92
93pub fn calculate_size_discount_asset_weight(
97 size_in_amm: u128,
98 imf_factor: u32,
99 asset_weight: u128,
100) -> MathResult<u128> {
101 if imf_factor == 0 {
102 return Ok(asset_weight);
103 }
104
105 let size_times_10 = size_in_amm
106 .checked_mul(10)
107 .ok_or(MathError::Overflow)?
108 .checked_add(1)
109 .ok_or(MathError::Overflow)?;
110 let size_sqrt = isqrt(size_times_10);
111
112 let imf_numerator: u128 = SPOT_IMF_PRECISION
113 .checked_add(
114 SPOT_IMF_PRECISION
115 .checked_div(10)
116 .ok_or(MathError::Overflow)?,
117 )
118 .ok_or(MathError::Overflow)?;
119
120 let numerator = imf_numerator
121 .checked_mul(SPOT_WEIGHT_PRECISION)
122 .ok_or(MathError::Overflow)?;
123
124 let inner = size_sqrt
125 .checked_mul(imf_factor as u128)
126 .ok_or(MathError::Overflow)?
127 .checked_div(100_000)
128 .ok_or(MathError::Overflow)?;
129 let denominator = SPOT_IMF_PRECISION
130 .checked_add(inner)
131 .ok_or(MathError::Overflow)?;
132
133 let size_discount_weight = numerator
134 .checked_div(denominator)
135 .ok_or(MathError::Overflow)?;
136
137 Ok(cmp::min(asset_weight, size_discount_weight))
138}
139
140pub fn calculate_size_premium_liability_weight(
144 size_in_amm: u128,
145 imf_factor: u32,
146 liability_weight: u128,
147) -> MathResult<u128> {
148 if imf_factor == 0 {
149 return Ok(liability_weight);
150 }
151
152 let size_times_10 = size_in_amm
153 .checked_mul(10)
154 .ok_or(MathError::Overflow)?
155 .checked_add(1)
156 .ok_or(MathError::Overflow)?;
157 let size_sqrt = isqrt(size_times_10);
158
159 let lw_fifth = liability_weight.checked_div(5).ok_or(MathError::Overflow)?;
160 let liability_weight_numerator = liability_weight
161 .checked_sub(lw_fifth)
162 .ok_or(MathError::Overflow)?;
163
164 let denom = 100_000u128
165 .checked_mul(SPOT_IMF_PRECISION)
166 .ok_or(MathError::Overflow)?
167 .checked_div(SPOT_WEIGHT_PRECISION)
168 .ok_or(MathError::Overflow)?;
169
170 let premium_term = size_sqrt
171 .checked_mul(imf_factor as u128)
172 .ok_or(MathError::Overflow)?
173 .checked_div(denom)
174 .ok_or(MathError::Overflow)?;
175
176 let size_premium_weight = liability_weight_numerator
177 .checked_add(premium_term)
178 .ok_or(MathError::Overflow)?;
179
180 Ok(cmp::max(liability_weight, size_premium_weight))
181}
182
183pub fn calculate_asset_weight(
186 token_amount: u128,
187 oracle_price: u64,
188 spot_market: &SpotMarket,
189) -> MathResult<u128> {
190 let scaled_weight = calculate_scaled_initial_asset_weight(spot_market, oracle_price)?;
191 let size_in_amm = to_amm_precision(token_amount, spot_market.decimals)?;
192 calculate_size_discount_asset_weight(size_in_amm, spot_market.imf_factor, scaled_weight)
193}
194
195pub fn calculate_liability_weight(
198 token_amount: u128,
199 spot_market: &SpotMarket,
200) -> MathResult<u128> {
201 let size_in_amm = to_amm_precision(token_amount, spot_market.decimals)?;
202 calculate_size_premium_liability_weight(
203 size_in_amm,
204 spot_market.imf_factor,
205 spot_market.initial_liability_weight as u128,
206 )
207}
208
209pub fn get_strict_price(price_usdc_base_units: u64, twap5min: i64, is_asset: bool) -> u64 {
217 let twap = if twap5min > 0 {
218 twap5min as u64
219 } else {
220 price_usdc_base_units
221 };
222 if is_asset {
223 cmp::min(price_usdc_base_units, twap)
224 } else {
225 cmp::max(price_usdc_base_units, twap)
226 }
227}
228
229#[cfg(test)]
230#[allow(
231 clippy::unwrap_used,
232 clippy::expect_used,
233 clippy::panic,
234 clippy::arithmetic_side_effects
235)]
236mod tests {
237 use super::*;
238
239 #[test]
240 fn isqrt_basic_values() {
241 assert_eq!(isqrt(0), 0);
242 assert_eq!(isqrt(1), 1);
243 assert_eq!(isqrt(4), 2);
244 assert_eq!(isqrt(9), 3);
245 assert_eq!(isqrt(10), 3);
246 assert_eq!(isqrt(100), 10);
247 assert_eq!(isqrt(10_000_000_000), 100_000);
248 }
249
250 #[test]
251 fn size_discount_asset_weight_no_imf() {
252 let result = calculate_size_discount_asset_weight(1_000_000_000, 0, 8_000).unwrap();
253 assert_eq!(result, 8_000);
254 }
255
256 #[test]
257 fn size_discount_asset_weight_with_imf() {
258 let result = calculate_size_discount_asset_weight(1_000_000_000, 1000, 8_000).unwrap();
259 assert_eq!(result, 8_000);
260
261 let result =
262 calculate_size_discount_asset_weight(1_000_000_000_000_000, 1000, 8_000).unwrap();
263 assert!(result < 8_000, "Large position should have reduced weight");
264 }
265
266 #[test]
267 fn size_premium_liability_weight_no_imf() {
268 let result = calculate_size_premium_liability_weight(1_000_000_000, 0, 12_000).unwrap();
269 assert_eq!(result, 12_000);
270 }
271
272 #[test]
273 fn size_premium_liability_weight_with_imf() {
274 let result = calculate_size_premium_liability_weight(1_000_000_000, 1000, 12_000).unwrap();
275 assert_eq!(result, 12_000);
276
277 let result =
278 calculate_size_premium_liability_weight(1_000_000_000_000_000, 1000, 12_000).unwrap();
279 assert!(
280 result > 12_000,
281 "Large position should have increased weight"
282 );
283 }
284
285 #[test]
286 fn strict_price_asset_uses_min() {
287 assert_eq!(get_strict_price(1_000_000, 900_000, true), 900_000);
288 assert_eq!(get_strict_price(1_000_000, 1_100_000, true), 1_000_000);
289 }
290
291 #[test]
292 fn strict_price_liability_uses_max() {
293 assert_eq!(get_strict_price(1_000_000, 900_000, false), 1_000_000);
294 assert_eq!(get_strict_price(1_000_000, 1_100_000, false), 1_100_000);
295 }
296
297 #[test]
298 fn strict_price_nonpositive_twap_falls_back() {
299 assert_eq!(get_strict_price(1_000_000, 0, true), 1_000_000);
300 assert_eq!(get_strict_price(1_000_000, -500, true), 1_000_000);
301 assert_eq!(get_strict_price(1_000_000, 0, false), 1_000_000);
302 }
303
304 fn make_weight_market(
305 initial_asset_weight: u32,
306 scale_start: u64,
307 decimals: u32,
308 deposit_interest: u128,
309 deposit_balance: u128,
310 ) -> SpotMarket {
311 SpotMarket {
312 pubkey: vec![],
313 market_index: 0,
314 initial_asset_weight,
315 initial_liability_weight: 0,
316 imf_factor: 0,
317 scale_initial_asset_weight_start: scale_start,
318 decimals,
319 cumulative_deposit_interest: deposit_interest,
320 cumulative_borrow_interest: 0,
321 deposit_balance,
322 borrow_balance: 0,
323 optimal_utilization: 0,
324 optimal_borrow_rate: 0,
325 max_borrow_rate: 0,
326 min_borrow_rate: 0,
327 insurance_fund: Default::default(),
328 historical_oracle_data: Default::default(),
329 oracle: None,
330 }
331 }
332
333 #[test]
334 fn scaled_initial_asset_weight_no_scaling() {
335 let market = make_weight_market(8_000, 0, 0, 0, 0);
336 let result = calculate_scaled_initial_asset_weight(&market, 1_000_000).unwrap();
337 assert_eq!(result, 8_000);
338 }
339
340 #[test]
341 fn scaled_initial_asset_weight_below_threshold() {
342 let decimals = 6u32;
343 let precision_decrease = 10u128.pow(19 - decimals);
344 let market = make_weight_market(
345 8_000,
346 1_000_000_000_000,
347 decimals,
348 precision_decrease,
349 500_000_000_000,
350 );
351 let result = calculate_scaled_initial_asset_weight(&market, 1_000_000).unwrap();
352 assert_eq!(result, 8_000);
353 }
354
355 #[test]
356 fn scaled_initial_asset_weight_above_threshold() {
357 let decimals = 6u32;
358 let precision_decrease = 10u128.pow(19 - decimals);
359 let market = make_weight_market(
360 8_000,
361 500_000_000_000,
362 decimals,
363 precision_decrease,
364 1_000_000_000_000,
365 );
366 let result = calculate_scaled_initial_asset_weight(&market, 1_000_000).unwrap();
367 assert_eq!(result, 4_000);
368 }
369
370 #[test]
371 fn to_amm_precision_decimals_6() {
372 let result = to_amm_precision(1_000_000, 6).unwrap();
373 assert_eq!(result, 1_000_000_000);
374 }
375
376 #[test]
377 fn to_amm_precision_decimals_9() {
378 let result = to_amm_precision(1_000_000_000, 9).unwrap();
379 assert_eq!(result, 1_000_000_000);
380 }
381
382 #[test]
383 fn to_amm_precision_decimals_18() {
384 let result = to_amm_precision(1_000_000_000_000_000_000, 18).unwrap();
385 assert_eq!(result, 1_000_000_000);
386 }
387}
388
389#[cfg(test)]
390#[allow(
391 clippy::unwrap_used,
392 clippy::expect_used,
393 clippy::panic,
394 clippy::arithmetic_side_effects
395)]
396mod proptests {
397 use super::*;
398 use proptest::prelude::*;
399
400 proptest! {
401 #[test]
402 fn isqrt_correct(n in 0u128..=1_000_000_000_000_000_000u128) {
403 let root = isqrt(n);
404 prop_assert!(root.checked_mul(root).unwrap() <= n);
406 let next = root + 1;
408 prop_assert!(next.checked_mul(next).unwrap() > n);
409 }
410
411 #[test]
412 fn size_discount_weight_le_base(
413 size in 0u128..=1_000_000_000_000_000_000u128,
414 imf in 0u32..=100_000u32,
415 base_weight in 1u128..=20_000u128,
416 ) {
417 let result = calculate_size_discount_asset_weight(size, imf, base_weight).unwrap();
418 prop_assert!(result <= base_weight, "discount weight {} > base {}", result, base_weight);
419 }
420
421 #[test]
422 fn size_premium_weight_ge_base(
423 size in 0u128..=1_000_000_000_000_000_000u128,
424 imf in 0u32..=100_000u32,
425 base_weight in 5u128..=20_000u128,
426 ) {
427 let result = calculate_size_premium_liability_weight(size, imf, base_weight).unwrap();
428 prop_assert!(result >= base_weight, "premium weight {} < base {}", result, base_weight);
429 }
430
431 #[test]
432 fn strict_price_asset_le_oracle(price in 1u64..=u64::MAX / 2, twap in 1i64..=i64::MAX / 2) {
433 let result = get_strict_price(price, twap, true);
434 prop_assert!(result <= price);
435 prop_assert!(result <= twap as u64);
436 }
437
438 #[test]
439 fn strict_price_liability_ge_oracle(price in 1u64..=u64::MAX / 2, twap in 1i64..=i64::MAX / 2) {
440 let result = get_strict_price(price, twap, false);
441 prop_assert!(result >= price && result >= twap as u64);
442 }
443 }
444}