onemoney_protocol/api/chains.rs
1//! Chain-related API operations.
2
3use crate::Result;
4use crate::client::Client;
5use crate::client::config::api_path;
6use crate::client::config::endpoints::chains::CHAIN_ID;
7use crate::responses::ChainIdResponse;
8
9impl Client {
10 /// Get the chain ID for this network.
11 ///
12 /// This method returns the predefined chain ID for the client's network configuration
13 /// without making any network requests. This is fast and always available.
14 ///
15 /// # Returns
16 ///
17 /// The chain ID for this network.
18 ///
19 /// # Example
20 ///
21 /// ```rust
22 /// use onemoney_protocol::Client;
23 ///
24 /// let client = Client::mainnet().unwrap();
25 /// let chain_id = client.get_chain_id();
26 /// assert_eq!(chain_id, 21210);
27 /// ```
28 pub fn get_chain_id(&self) -> u64 {
29 self.network.chain_id()
30 }
31
32 /// Fetch the current chain ID from the network API.
33 ///
34 /// This method makes an HTTP request to fetch the chain ID from the network.
35 /// Use this to verify that the network is responding correctly and matches
36 /// the expected chain ID.
37 ///
38 /// # Returns
39 ///
40 /// The chain ID from the API response.
41 ///
42 /// # Example
43 ///
44 /// ```rust,no_run
45 /// use onemoney_protocol::Client;
46 ///
47 /// #[tokio::main]
48 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
49 /// let client = Client::mainnet()?;
50 ///
51 /// let api_chain_id = client.fetch_chain_id_from_network().await?;
52 /// let expected_chain_id = client.get_chain_id();
53 ///
54 /// assert_eq!(api_chain_id, expected_chain_id);
55 /// println!("Network chain ID matches expected: {}", api_chain_id);
56 ///
57 /// Ok(())
58 /// }
59 /// ```
60 pub async fn fetch_chain_id_from_network(&self) -> Result<u64> {
61 let response: ChainIdResponse = self.get(&api_path(CHAIN_ID)).await?;
62 Ok(response.chain_id)
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use super::*;
69 use crate::Client;
70
71 #[test]
72 fn test_chain_id_response_structure() {
73 // Test that ChainIdResponse can be serialized/deserialized
74 let chain_id_response = ChainIdResponse { chain_id: 1212101 };
75
76 let json = serde_json::to_string(&chain_id_response).expect("Test data should be valid");
77 let deserialized: ChainIdResponse =
78 serde_json::from_str(&json).expect("Test data should be valid");
79
80 assert_eq!(chain_id_response.chain_id, deserialized.chain_id);
81 }
82
83 #[test]
84 fn test_get_chain_id() {
85 // Test get_chain_id method for different client types
86 let mainnet_client = Client::mainnet().expect("Should create mainnet client");
87 let testnet_client = Client::testnet().expect("Should create testnet client");
88 let local_client = Client::local().expect("Should create local client");
89
90 assert_eq!(mainnet_client.get_chain_id(), 21210);
91 assert_eq!(testnet_client.get_chain_id(), 1_212_101);
92 assert_eq!(local_client.get_chain_id(), 1_212_101);
93 }
94}