1use std::sync::Arc;
20
21use jsonrpsee::core::RpcResult;
22use sc_network::{service::traits::NetworkService, NetworkPeers};
24use sp_api::ProvideRuntimeApi;
25use sp_blockchain::HeaderBackend;
26use sp_runtime::traits::Block as BlockT;
27use fc_rpc_core::{types::PeerCount, NetApiServer};
29use fp_rpc::EthereumRuntimeRPCApi;
30
31use crate::internal_err;
32
33pub struct Net<B: BlockT, C> {
35 client: Arc<C>,
36 network: Arc<dyn NetworkService>,
37 peer_count_as_hex: bool,
38 _phantom_data: std::marker::PhantomData<B>,
39}
40impl<B: BlockT, C> Net<B, C> {
41 pub fn new(client: Arc<C>, network: Arc<dyn NetworkService>, peer_count_as_hex: bool) -> Self {
42 Self {
43 client,
44 network,
45 peer_count_as_hex,
46 _phantom_data: Default::default(),
47 }
48 }
49}
50
51impl<B, C> NetApiServer for Net<B, C>
52where
53 B: BlockT,
54 C: ProvideRuntimeApi<B>,
55 C::Api: EthereumRuntimeRPCApi<B>,
56 C: HeaderBackend<B> + 'static,
57{
58 fn version(&self) -> RpcResult<String> {
59 let hash = self.client.info().best_hash;
60 Ok(self
61 .client
62 .runtime_api()
63 .chain_id(hash)
64 .map_err(|_| internal_err("fetch runtime chain id failed"))?
65 .to_string())
66 }
67
68 fn peer_count(&self) -> RpcResult<PeerCount> {
69 let peer_count = self.network.sync_num_connected();
70 Ok(match self.peer_count_as_hex {
71 true => PeerCount::String(format!("0x{peer_count:x}")),
72 false => PeerCount::U32(peer_count as u32),
73 })
74 }
75
76 fn is_listening(&self) -> RpcResult<bool> {
77 Ok(true)
78 }
79}