rust_conflux_sdk/traits/
rpc_req.rs1use crate::error::CfxResult;
2use crate::error::Error::RpcResError;
3use crate::network::{CONFLUX_ENV, CONFLUX_NETWORK};
4use crate::traits::params::CfxParams;
5use async_trait::async_trait;
6use reqwest::Client;
7use serde::de::DeserializeOwned;
8use serde::{Deserialize, Serialize};
9use std::fmt::Debug;
10use std::time::Duration;
11
12const TIMEOUT: Duration = Duration::from_secs(30);
13
14#[derive(Deserialize, Debug, Default)]
15pub struct CfxRes<R> {
16 pub id: Option<String>,
17 pub jsonrpc: String,
18 pub result: Option<R>,
19 pub error: Option<CodeError>,
20}
21
22#[derive(Deserialize, Debug, Default)]
23pub struct CodeError {
24 pub code: i64,
25 pub message: String,
26}
27
28#[async_trait]
29pub trait CommonRpcReq
30where
31 Self: Debug,
32{
33 #[tracing::instrument]
34 async fn post<T, R>(&self, params: &T) -> CfxResult<Option<R>>
35 where
36 T: Serialize + Sync + Debug,
37 R: DeserializeOwned + Debug,
38 {
39 let client = Client::builder()
40 .timeout(TIMEOUT)
41 .build()?
42 .post(CONFLUX_NETWORK.as_str())
43 .header("Content-Type", "application/json")
44 .json(params);
45 let data = client.send().await?.json::<CfxRes<R>>().await?;
46 if data.error.is_some() {
47 let err = data.error.unwrap();
48 return Err(RpcResError(format!(
49 "code: {}, message: {}",
50 err.code, err.message
51 )));
52 }
53 Ok(data.result)
54 }
55
56 async fn gas_price(&self) -> CfxResult<Option<String>> {
65 let params:CfxParams<&str> = CfxParams::new(1, &format!("{}_gasPrice", CONFLUX_ENV.as_str()), None);
66 self.post(¶ms).await
67 }
68}