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