injective_math/lib.rs
1pub mod fp_decimal;
2pub mod root_findings;
3pub mod utils;
4pub mod vector;
5
6use cosmwasm_std::{StdResult, Uint128};
7pub use fp_decimal::*;
8pub use root_findings::*;
9use std::str::FromStr;
10pub use utils::*;
11pub use vector::*;
12
13/// ## Description
14///
15/// Calculates the cluster imbalance.
16///
17/// ## Params
18///
19/// - **i** is a reference to an array containing objects of type [`FPDecimal`] which
20/// is the asset inventory.
21///
22/// - **p** is a reference to an array containing objects of type [`FPDecimal`] which
23/// are the prices of the assets.
24///
25/// - **w** is a reference to an array containing objects of type [`FPDecimal`] which
26/// are the target weights of the assets.
27pub fn imbalance(i: &[FPDecimal], p: &[FPDecimal], w: &[FPDecimal]) -> FPDecimal {
28 // Target weights with prices
29 // -- u = elem_mul(targets, prices)
30 let u = mul(w, p);
31 // NAV with target weights instead of inventory
32 // -- wp = dot(targets, prices)
33 let wp = dot(w, p);
34
35 // Suppose
36 // A is the capital allocation
37 // -- A = elem_mul(inventory, prices)
38 // A_opt is the optimal capital allocation
39 // -- A_opt = u * rescale_to_actual_NAV
40 // = u * dot(inventory, prices) / wp
41
42 // Compute imbalance
43 // -- imb = | A_opt - A |
44 // = | u * dot(inventory, prices) / wp - elem_mul(inventory, prices) |
45 // = | u * dot(inventory, prices) - elem_mul(inventory, prices) * wp | / wp
46 let err_portfolio = sub(&mul_const(&u, dot(i, p)), &mul_const(&mul(i, p), wp));
47 sum(&abs(&err_portfolio)) / wp
48}
49
50/// ## Description
51/// Converts an int32 array to a FPDecimal array.
52///
53/// ## Params
54/// - **arr** is a reference to an array containing objects of type [`u32`].
55pub fn int32_vec_to_fpdec(arr: &[u32]) -> Vec<FPDecimal> {
56 arr.iter().map(|val| FPDecimal::from(*val as u128)).collect()
57}
58
59/// ## Description
60/// Converts an Uint128 array to a FPDecimal array.
61///
62/// ## Params
63/// - **arr** is a reference to an array containing objects of type [`Uint128`].
64pub fn int_vec_to_fpdec(arr: &[Uint128]) -> Vec<FPDecimal> {
65 arr.iter().map(|val| FPDecimal::from(val.u128())).collect()
66}
67
68/// ## Description
69/// Converts an String array to a FPDecimal array.
70///
71/// ## Params
72/// - **arr** is a reference to an array containing objects of type [`String`].
73pub fn str_vec_to_fpdec(arr: &[String]) -> StdResult<Vec<FPDecimal>> {
74 arr.iter().map(|val| FPDecimal::from_str(val)).collect::<StdResult<Vec<FPDecimal>>>()
75}