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
pub mod client;
pub mod cosmos;
pub mod counterparty;
pub mod endpoint;
pub mod handle;
pub mod requests;
pub mod runtime;
pub mod tracking;

#[cfg(test)]
pub mod mock;

use serde::{de::Error, Deserialize, Serialize};

// NOTE(new): When adding a variant to `ChainType`, make sure to update
//            the `Deserialize` implementation below and the tests.
//            See the NOTE(new) comments below.

#[derive(Copy, Clone, Debug, Serialize)]
/// Types of chains the relayer can relay to and from
pub enum ChainType {
    /// Chains based on the Cosmos SDK
    CosmosSdk,

    /// Mock chain used for testing
    #[cfg(test)]
    Mock,
}

impl<'de> Deserialize<'de> for ChainType {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let original = String::deserialize(deserializer)?;
        let s = original.to_ascii_lowercase().replace('-', "");

        match s.as_str() {
            "cosmossdk" => Ok(Self::CosmosSdk),

            #[cfg(test)]
            "mock" => Ok(Self::Mock),

            // NOTE(new): Add a case here
            _ => Err(D::Error::unknown_variant(&original, &["cosmos-sdk"])), // NOTE(new): mention the new variant here
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Copy, Clone, Debug, Serialize, Deserialize)]
    pub struct Config {
        tpe: ChainType,
    }

    fn parse(variant: &str) -> Result<ChainType, toml::de::Error> {
        toml::from_str::<Config>(&format!("tpe = '{variant}'")).map(|e| e.tpe)
    }

    #[test]
    fn deserialize() {
        use ChainType::*;

        assert!(matches!(parse("CosmosSdk"), Ok(CosmosSdk)));
        assert!(matches!(parse("cosmossdk"), Ok(CosmosSdk)));
        assert!(matches!(parse("cosmos-sdk"), Ok(CosmosSdk)));
        assert!(matches!(parse("mock"), Ok(Mock)));

        // NOTE(new): Add tests here

        assert!(matches!(parse("hello-world"), Err(_)));
    }
}