miden_objects/account/account_id/
network_id.rs1use alloc::string::ToString;
2use core::str::FromStr;
3
4use bech32::Hrp;
5
6use crate::errors::NetworkIdError;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
13pub enum NetworkId {
14 Mainnet,
15 Testnet,
16 Devnet,
17 Custom(Hrp),
18}
19
20impl NetworkId {
21 const MAINNET: &str = "mm";
22 const TESTNET: &str = "mtst";
23 const DEVNET: &str = "mdev";
24
25 pub fn new(string: &str) -> Result<Self, NetworkIdError> {
33 Hrp::parse(string)
34 .map(Self::from_hrp)
35 .map_err(|source| NetworkIdError::NetworkIdParseError(source.to_string().into()))
36 }
37
38 pub(crate) fn from_hrp(hrp: Hrp) -> Self {
42 match hrp.as_str() {
43 NetworkId::MAINNET => NetworkId::Mainnet,
44 NetworkId::TESTNET => NetworkId::Testnet,
45 NetworkId::DEVNET => NetworkId::Devnet,
46 _ => NetworkId::Custom(hrp),
47 }
48 }
49
50 pub(crate) fn into_hrp(self) -> Hrp {
54 match self {
55 NetworkId::Mainnet => {
56 Hrp::parse(NetworkId::MAINNET).expect("mainnet hrp should be valid")
57 },
58 NetworkId::Testnet => {
59 Hrp::parse(NetworkId::TESTNET).expect("testnet hrp should be valid")
60 },
61 NetworkId::Devnet => Hrp::parse(NetworkId::DEVNET).expect("devnet hrp should be valid"),
62 NetworkId::Custom(custom) => custom,
63 }
64 }
65
66 pub fn as_str(&self) -> &str {
68 match self {
69 NetworkId::Mainnet => NetworkId::MAINNET,
70 NetworkId::Testnet => NetworkId::TESTNET,
71 NetworkId::Devnet => NetworkId::DEVNET,
72 NetworkId::Custom(custom) => custom.as_str(),
73 }
74 }
75
76 pub fn is_mainnet(&self) -> bool {
78 matches!(self, NetworkId::Mainnet)
79 }
80
81 pub fn is_testnet(&self) -> bool {
83 matches!(self, NetworkId::Testnet)
84 }
85
86 pub fn is_devnet(&self) -> bool {
88 matches!(self, NetworkId::Devnet)
89 }
90}
91
92impl FromStr for NetworkId {
93 type Err = NetworkIdError;
94
95 fn from_str(string: &str) -> Result<Self, Self::Err> {
99 Self::new(string)
100 }
101}
102
103impl core::fmt::Display for NetworkId {
104 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
105 f.write_str(self.as_str())
106 }
107}