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
// include!("gen/mod.rs");

#[allow(clippy::all)]
mod gen;
pub use gen::*;

pub mod prelude {
    use core::fmt;
    use std::str::FromStr;

    use crate::cosmos::base::v1beta1::DecCoin;

    use super::*;
    use alloy_primitives::U256;

    use cosmos::base::v1beta1::Coin;
    use tonic::metadata::{Ascii, MetadataValue};

    pub const HEIGHT_METADATA_KEY: &str = "x-cosmos-block-height";

    pub trait CoinExt<'a> {
        fn get_denom(&'a self, denom: impl Into<String>) -> Option<&'a str>;
    }

    // impl<'a, I> CoinOptionExt<'a> for I
    // where
    //     I: AsRef<[Coin]>,
    // {
    //     fn get_denom(&'a self, denom: impl Into<String>) -> Option<&'a Coin> {
    //         let denom = denom.into();
    //         self.as_ref().iter().find(move |c| c.denom == denom)
    //     }
    // }

    impl<'a> CoinExt<'a> for Option<Coin> {
        fn get_denom(&'a self, denom: impl Into<String>) -> Option<&'a str> {
            self.as_ref()
                .filter(|c| c.denom == denom.into())
                .map(|c| c.amount.as_str())
        }
    }

    impl<'a> CoinExt<'a> for Vec<Coin> {
        fn get_denom(&'a self, denom: impl Into<String>) -> Option<&'a str> {
            let denom = denom.into();
            for coin in self.iter() {
                if coin.denom == denom {
                    return Some(coin.amount.as_str());
                }
            }
            None
        }
    }

    impl<'a> CoinExt<'a> for Vec<DecCoin> {
        fn get_denom(&'a self, denom: impl Into<String>) -> Option<&'a str> {
            let denom = denom.into();
            for coin in self.iter() {
                if coin.denom == denom {
                    return Some(coin.amount.as_str());
                }
            }
            None
        }
    }

    pub trait AmountExt {
        fn to_u256(&self) -> Result<U256, alloy_primitives::ruint::ParseError>;
    }

    impl AmountExt for String {
        fn to_u256(&self) -> Result<U256, alloy_primitives::ruint::ParseError> {
            U256::from_str(self)
        }
    }

    impl<'a> AmountExt for &'a str {
        fn to_u256(&self) -> Result<U256, alloy_primitives::ruint::ParseError> {
            U256::from_str(self)
        }
    }

    impl AmountExt for Coin {
        fn to_u256(&self) -> Result<U256, alloy_primitives::ruint::ParseError> {
            self.amount.to_u256()
        }
    }

    #[derive(Clone, Debug, PartialEq)]
    #[allow(non_camel_case_types)]
    pub enum Denom {
        aISLM,
        ISLM,
        Other(String),
    }

    impl Denom {
        pub fn conversion_pair(&self) -> Option<(Self, U256, U256)> {
            match self {
                Self::aISLM => Some((
                    Self::ISLM,
                    U256::from(1),
                    U256::pow(U256::from(10), U256::from(18)),
                )),
                Self::ISLM => Some((
                    Self::aISLM,
                    U256::pow(U256::from(10), U256::from(18)),
                    U256::from(1),
                )),
                Self::Other(_) => None,
            }
        }
    }

    impl fmt::Display for Denom {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                Self::aISLM => write!(f, "aISLM"),
                Self::ISLM => write!(f, "ISLM"),
                Denom::Other(d) => write!(f, "{}", d),
            }
        }
    }

    pub trait CosmosMessage {
        fn with_height(self, height: MetadataValue<Ascii>) -> tonic::Request<Self>
        where
            Self: Sized,
        {
            let mut req = tonic::Request::new(self);
            req.metadata_mut().insert(HEIGHT_METADATA_KEY, height);
            req
        }

        fn with_height_num(self, height: u64) -> tonic::Request<Self>
        where
            Self: Sized,
        {
            let height = MetadataValue::from_str(&height.to_string()).unwrap();
            self.with_height(height)
        }
    }

    impl<T> CosmosMessage for T {}

    pub trait CosmosResponse<T> {
        fn get_height(&self) -> Option<&MetadataValue<Ascii>>;
    }

    impl<T> CosmosResponse<T> for tonic::Response<T> {
        fn get_height(&self) -> Option<&MetadataValue<Ascii>> {
            self.metadata().get(HEIGHT_METADATA_KEY)
        }
    }
}

#[cfg(test)]
mod test {
    use super::cosmos::base::v1beta1::Coin;
    use super::prelude::*;
    use alloy_primitives::U256;
    use std::str::FromStr;

    #[test]
    fn denom() {
        let oneislm_in_aislm =
            U256::from_str(&format!("1{}", (0..18).map(|_| "0").collect::<String>())).unwrap();
        let oneislm_in_islm = U256::from_str("1").unwrap();

        let (denom, mul, div) = Denom::aISLM.conversion_pair().unwrap();
        assert_eq!(denom, Denom::ISLM);
        assert_eq!(oneislm_in_islm, oneislm_in_aislm * mul / div);

        let (denom, mul, div) = Denom::ISLM.conversion_pair().unwrap();
        assert_eq!(denom, Denom::aISLM);
        assert_eq!(oneislm_in_aislm, oneislm_in_islm * mul / div);
    }

    #[test]
    fn coin_option_ext() {
        let coin = Coin {
            denom: "aISLM".to_string(),
            amount: "0".to_string(),
        };

        assert!(vec![coin.clone()].get_denom("aISLM").is_some());
        assert_eq!(Some(coin).get_denom("aISLM"), Some("0"));
    }

    #[test]
    fn coin_ext() {
        let mut coin = Coin {
            denom: "ISLM".to_string(),
            amount: "1.2345".to_string(),
        };

        assert!(coin.to_u256().is_err());

        coin.amount = "12345".to_string();
        assert_eq!(coin.to_u256().unwrap(), U256::from_str("12345").unwrap());

        assert_eq!(
            "12345".to_string().to_u256().unwrap(),
            U256::from_str("12345").unwrap()
        );
        assert_eq!("12345".to_u256().unwrap(), U256::from_str("12345").unwrap());
    }
}