rust_v4v/
lib.rs

1use thiserror::Error;
2
3pub mod boostagram;
4
5#[derive(Error, Debug)]
6pub enum Error {
7    #[error("serde_json error: {0}")]
8    DeserializingError(#[from] serde_json::Error),
9
10    #[error("b64 decoding error: {0}")]
11    B64DecodeError(#[from] base64::DecodeError),
12
13    #[error("buidling error: {0}")]
14    BuildingError(String),
15
16    #[error("Parameter invalid: {0}")]
17    ParameterInvalid(String),
18}
19
20pub fn calculate_splits(splits: Vec<(u64, bool)>, amt: u64) -> Result<Vec<u64>, Error> {
21    let (split_sum, fee_sum) =
22        splits
23            .iter()
24            .rfold((0, 0), |(split_sum, fee_sum), (split, is_fee)| {
25                if *is_fee {
26                    (split_sum, fee_sum + split)
27                } else {
28                    (split_sum + split, fee_sum)
29                }
30            });
31
32    if fee_sum > 100 {
33        return Err(Error::ParameterInvalid(String::from(
34            "Fee sum greater than 100",
35        )));
36    }
37
38    let rest_percentage = 100 - fee_sum;
39
40    Ok(splits
41        .into_iter()
42        .map(|(split, fee)| {
43            if fee {
44                amt * split / 100
45            } else if split_sum == 0 {
46                0
47            } else {
48                (split * rest_percentage * amt) / (split_sum * 100)
49            }
50        })
51        .collect())
52}