abstract_core/objects/
chain_name.rs

1use std::str::FromStr;
2
3use cosmwasm_schema::cw_serde;
4use cosmwasm_std::{Env, StdResult};
5use cw_storage_plus::{Key, KeyDeserialize, Prefixer, PrimaryKey};
6
7use crate::{AbstractError, AbstractResult};
8
9pub const MAX_CHAIN_NAME_LENGTH: usize = 20;
10pub const MIN_CHAIN_NAME_LENGTH: usize = 3;
11
12#[cw_serde]
13#[derive(Eq, PartialOrd, Ord)]
14/// The name of a chain, aka the chain-id without the post-fix number.
15/// ex. `cosmoshub-4` -> `cosmoshub`, `juno-1` -> `juno`
16pub struct ChainName(String);
17
18impl ChainName {
19    // Construct the chain name from the environment (chain-id)
20    pub fn new(env: &Env) -> Self {
21        let chain_id = &env.block.chain_id;
22        Self::from_chain_id(chain_id)
23    }
24
25    // Construct the chain name from the chain id
26    pub fn from_chain_id(chain_id: &str) -> Self {
27        // split on the last -
28        // `cosmos-testnet-53159`
29        // -> `cosmos-testnet` and `53159`
30        let parts: Vec<&str> = chain_id.rsplitn(2, '-').collect();
31        // the parts vector should look like [53159, cosmos-tesnet], because we are using rsplitn
32        Self(parts[1].to_string())
33    }
34
35    pub fn from_string(value: String) -> AbstractResult<Self> {
36        let chain_name = Self(value);
37        chain_name.verify()?;
38        Ok(chain_name)
39    }
40
41    /// verify the formatting of the chain name
42    pub fn verify(&self) -> AbstractResult<()> {
43        // check length
44        if self.0.is_empty()
45            || self.0.len() < MIN_CHAIN_NAME_LENGTH
46            || self.0.len() > MAX_CHAIN_NAME_LENGTH
47        {
48            return Err(AbstractError::FormattingError {
49                object: "chain-seq".into(),
50                expected: format!("between {MIN_CHAIN_NAME_LENGTH} and {MAX_CHAIN_NAME_LENGTH}"),
51                actual: self.0.len().to_string(),
52            });
53        // check character set
54        } else if !self.0.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
55            return Err(crate::AbstractError::FormattingError {
56                object: "chain_name".into(),
57                expected: "chain-name".into(),
58                actual: self.0.clone(),
59            });
60        }
61        Ok(())
62    }
63
64    pub fn as_str(&self) -> &str {
65        self.0.as_str()
66    }
67
68    // used for key implementation
69    pub(crate) fn str_ref(&self) -> &String {
70        &self.0
71    }
72
73    pub fn into_string(self) -> String {
74        self.0
75    }
76
77    /// Only use this if you are sure that the string is valid (e.g. from storage)
78    pub(crate) fn _from_str(value: &str) -> Self {
79        Self(value.to_string())
80    }
81
82    /// Only use this if you are sure that the string is valid (e.g. from storage)
83    pub(crate) fn _from_string(value: String) -> Self {
84        Self(value)
85    }
86}
87
88impl ToString for ChainName {
89    fn to_string(&self) -> String {
90        self.0.clone()
91    }
92}
93
94impl FromStr for ChainName {
95    type Err = AbstractError;
96    fn from_str(value: &str) -> AbstractResult<Self> {
97        let chain_name = Self(value.to_string());
98        chain_name.verify()?;
99        Ok(chain_name)
100    }
101}
102
103impl<'a> PrimaryKey<'a> for &ChainName {
104    type Prefix = ();
105
106    type SubPrefix = ();
107
108    type Suffix = Self;
109
110    type SuperSuffix = Self;
111
112    fn key(&self) -> Vec<cw_storage_plus::Key> {
113        self.0.key()
114    }
115}
116
117impl<'a> Prefixer<'a> for &ChainName {
118    fn prefix(&self) -> Vec<Key> {
119        self.0.prefix()
120    }
121}
122
123impl KeyDeserialize for &ChainName {
124    type Output = ChainName;
125
126    #[inline(always)]
127    fn from_vec(value: Vec<u8>) -> StdResult<Self::Output> {
128        Ok(ChainName(String::from_vec(value)?))
129    }
130}
131
132#[cfg(test)]
133mod test {
134    use cosmwasm_std::testing::mock_env;
135    use speculoos::prelude::*;
136
137    use super::*;
138
139    #[test]
140    fn test_namespace() {
141        let namespace = ChainName::new(&mock_env());
142        assert_that!(namespace.as_str()).is_equal_to("cosmos-testnet");
143    }
144
145    #[test]
146    fn test_from_string() {
147        let namespace = ChainName::from_string("test-me".to_string()).unwrap();
148        assert_that!(namespace.as_str()).is_equal_to("test-me");
149    }
150
151    #[test]
152    fn test_from_str() {
153        let namespace = ChainName::from_str("test-too").unwrap();
154        assert_that!(namespace.as_str()).is_equal_to("test-too");
155    }
156
157    #[test]
158    fn test_to_string() {
159        let namespace = ChainName::from_str("test").unwrap();
160        assert_that!(namespace.to_string()).is_equal_to("test".to_string());
161    }
162
163    #[test]
164    fn test_from_str_long() {
165        let namespace = ChainName::from_str("test-a-b-c-d-e-f").unwrap();
166        assert_that!(namespace.as_str()).is_equal_to("test-a-b-c-d-e-f");
167    }
168
169    #[test]
170    fn string_key_works() {
171        let k = &ChainName::from_str("test-abc").unwrap();
172        let path = k.key();
173        assert_eq!(1, path.len());
174        assert_eq!(b"test-abc", path[0].as_ref());
175
176        let joined = k.joined_key();
177        assert_eq!(joined, b"test-abc")
178    }
179
180    // Failures
181
182    #[test]
183    fn local_empty_fails() {
184        ChainName::from_str("").unwrap_err();
185    }
186
187    #[test]
188    fn local_too_short_fails() {
189        ChainName::from_str("a").unwrap_err();
190    }
191
192    #[test]
193    fn local_too_long_fails() {
194        ChainName::from_str(&"a".repeat(MAX_CHAIN_NAME_LENGTH + 1)).unwrap_err();
195    }
196
197    #[test]
198    fn local_uppercase_fails() {
199        ChainName::from_str("AAAAA").unwrap_err();
200    }
201
202    #[test]
203    fn local_non_alphanumeric_fails() {
204        ChainName::from_str("a_aoeuoau").unwrap_err();
205    }
206}