rust_conflux_sdk/
network.rs

1use once_cell::sync::Lazy;
2use parking_lot::lock_api::Mutex;
3use parking_lot::RawMutex;
4use std::sync::atomic::AtomicU16;
5use std::sync::atomic::Ordering;
6
7pub static NETWORK_ID: AtomicU16 = AtomicU16::new(70);
8
9static CUSTOM_NETWORK: Lazy<Mutex<RawMutex, String>> = Lazy::new(|| Mutex::new(String::new()));
10
11pub fn set_network(network_id: Network, custom_network: Option<&str>) {
12    NETWORK_ID.store(network_id.get_network_id(), Ordering::Relaxed);
13    let mut lock = CUSTOM_NETWORK.lock();
14    *lock = custom_network.unwrap_or("").to_owned()
15}
16
17pub static CONFLUX_NETWORK: Lazy<String> = Lazy::new(|| {
18    let lock = CUSTOM_NETWORK.lock();
19    if lock.as_str() != "" {
20        lock.to_string()
21    } else {
22        let network = Network::new(NETWORK_ID.load(Ordering::Relaxed));
23        network.get_network_url()
24    }
25});
26
27pub static CONFLUX_ENV: Lazy<String> = Lazy::new(|| {
28    let env = Env::new(NETWORK_ID.load(Ordering::Relaxed));
29    env.get_env()
30});
31
32pub enum Env {
33    CFX,
34    ETH,
35}
36
37impl Env {
38    pub fn new(network_id: u16) -> Self {
39        match network_id {
40            70 | 1029 => Env::CFX,
41            71 | 1030 => Env::ETH,
42            _ => Env::CFX,
43        }
44    }
45
46    pub fn get_env(&self) -> String {
47        match self {
48            Env::CFX => String::from("cfx"),
49            Env::ETH => String::from("eth"),
50        }
51    }
52}
53
54#[repr(u16)]
55pub enum Network {
56    CfxTest = 70,
57    CfxMain = 1029,
58    EthTest = 71,
59    EthMain = 1030,
60}
61
62impl Network {
63    pub fn new(network_id: u16) -> Self {
64        match network_id {
65            70 => Network::CfxTest,
66            1029 => Network::CfxMain,
67            71 => Network::EthTest,
68            1030 => Network::EthMain,
69            _ => Network::CfxTest,
70        }
71    }
72
73    pub fn get_network_url(&self) -> String {
74        match self {
75            Network::CfxTest => String::from("https://test.confluxrpc.com"),
76            Network::CfxMain => String::from("https://main.confluxrpc.com"),
77            Network::EthTest => String::from("https://evmtestnet.confluxrpc.com"),
78            Network::EthMain => String::from("https://evm.confluxrpc.com"),
79        }
80    }
81
82    pub fn get_network_id(&self) -> u16 {
83        match self {
84            Network::CfxTest => 70,
85            Network::CfxMain => 1029,
86            Network::EthTest => 71,
87            Network::EthMain => 1030,
88        }
89    }
90}