cardano_sdk/cardano/
network.rs1use crate::{NetworkId, ProtocolParameters, cbor, cbor as minicbor};
2use anyhow::anyhow;
3use std::fmt;
4
5#[cfg_attr(feature = "clap", derive(clap::ValueEnum))]
6#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
7#[cfg_attr(feature = "serde", serde(into = "String", try_from = "&str"))]
8#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, cbor::Encode, cbor::Decode)]
9pub enum Network {
10 #[n(0)]
11 Mainnet,
12 #[n(1)]
13 Preprod,
14 #[n(2)]
15 Preview,
16}
17
18impl Network {
19 pub const MAINNET_MAGIC: u64 = 764824073;
20 pub const PREPROD_MAGIC: u64 = 1;
21 pub const PREVIEW_MAGIC: u64 = 2;
22}
23
24impl fmt::Display for Network {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
26 f.write_str(match self {
27 Self::Mainnet => "mainnet",
28 Self::Preprod => "preprod",
29 Self::Preview => "preview",
30 })
31 }
32}
33
34impl From<Network> for u64 {
35 fn from(network: Network) -> Self {
36 match network {
37 Network::Mainnet => Network::MAINNET_MAGIC,
38 Network::Preprod => Network::PREPROD_MAGIC,
39 Network::Preview => Network::PREVIEW_MAGIC,
40 }
41 }
42}
43
44impl From<Network> for ProtocolParameters {
45 fn from(network: Network) -> ProtocolParameters {
46 match network {
47 Network::Mainnet => Self::mainnet(),
48 Network::Preprod => Self::preprod(),
49 Network::Preview => Self::preview(),
50 }
51 }
52}
53
54impl From<Network> for NetworkId {
55 fn from(network: Network) -> NetworkId {
56 match network {
57 Network::Mainnet => NetworkId::MAINNET,
58 _ => NetworkId::TESTNET,
59 }
60 }
61}
62
63impl From<Network> for String {
64 fn from(network: Network) -> Self {
65 network.to_string()
66 }
67}
68
69impl TryFrom<&str> for Network {
70 type Error = anyhow::Error;
71
72 fn try_from(text: &str) -> anyhow::Result<Self> {
73 fn match_str(candidate: &str, target: Network) -> bool {
74 candidate.to_lowercase() == target.to_string()
75 }
76
77 match text {
78 mainnet if match_str(mainnet, Self::Mainnet) => Ok(Self::Mainnet),
79 preprod if match_str(preprod, Self::Preprod) => Ok(Self::Preprod),
80 preview if match_str(preview, Self::Preview) => Ok(Self::Preview),
81 _ => Err(anyhow!(
82 "unsupported network: {text}; should be one of {}, {}, {}",
83 Self::Mainnet,
84 Self::Preprod,
85 Self::Preview
86 )),
87 }
88 }
89}
90
91impl Network {
94 pub fn is_mainnet(&self) -> bool {
95 self == &Network::Mainnet
96 }
97
98 pub fn is_testnet(&self) -> bool {
99 !self.is_mainnet()
100 }
101}