ckb_client/
network_type.rs

1use std::fmt;
2
3use serde::{Deserialize, Serialize};
4
5use super::constant::{
6    NETWORK_DEV, NETWORK_MAINNET, NETWORK_STAGING, NETWORK_TESTNET, PREFIX_MAINNET, PREFIX_TESTNET,
7};
8
9#[derive(Hash, Eq, PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
10pub enum NetworkType {
11    Mainnet,
12    Testnet,
13    Staging,
14    Dev,
15}
16
17impl NetworkType {
18    pub fn from_prefix(value: &str) -> Option<NetworkType> {
19        match value {
20            PREFIX_MAINNET => Some(NetworkType::Mainnet),
21            PREFIX_TESTNET => Some(NetworkType::Testnet),
22            _ => None,
23        }
24    }
25
26    pub fn to_prefix(self) -> &'static str {
27        match self {
28            NetworkType::Mainnet => PREFIX_MAINNET,
29            NetworkType::Testnet => PREFIX_TESTNET,
30            NetworkType::Staging => PREFIX_TESTNET,
31            NetworkType::Dev => PREFIX_TESTNET,
32        }
33    }
34
35    pub fn from_raw_str(value: &str) -> Option<NetworkType> {
36        match value.to_ascii_lowercase().as_str() {
37            NETWORK_MAINNET|"main"|"mainnet"|"mirana" => Some(NetworkType::Mainnet),
38            NETWORK_TESTNET|"test"|"testnet"|"pudge" => Some(NetworkType::Testnet),
39            NETWORK_STAGING => Some(NetworkType::Staging),
40            NETWORK_DEV => Some(NetworkType::Dev),
41            _ => None,
42        }
43    }
44
45    pub fn to_str(self) -> &'static str {
46        match self {
47            NetworkType::Mainnet => NETWORK_MAINNET,
48            NetworkType::Testnet => NETWORK_TESTNET,
49            NetworkType::Staging => NETWORK_STAGING,
50            NetworkType::Dev => NETWORK_DEV,
51        }
52    }
53}
54
55impl fmt::Display for NetworkType {
56    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
57        write!(f, "{}", self.to_str())
58    }
59}
60
61#[derive(Debug, Clone)]
62pub struct NetworkInfo {
63    pub network_type: NetworkType,
64    pub url: String,
65}
66
67impl NetworkInfo {
68    pub fn new(network_type: NetworkType, url: String) -> Self {
69        Self { network_type, url }
70    }
71    pub fn from_network_type(network_type: NetworkType) -> Option<Self> {
72        match network_type {
73            NetworkType::Mainnet => Some(Self::mainnet()),
74            NetworkType::Testnet => Some(Self::testnet()),
75            NetworkType::Staging => None,
76            NetworkType::Dev => None,
77        }
78    }
79    pub fn mainnet() -> Self {
80        Self {
81            network_type: NetworkType::Mainnet,
82            url: "https://mainnet.ckb.dev".to_string(),
83        }
84    }
85    pub fn testnet() -> Self {
86        Self {
87            network_type: NetworkType::Testnet,
88            url: "https://testnet.ckb.dev".to_string(),
89        }
90    }
91}