1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::fmt::Debug;

use serde::Deserialize;

use crate::rpc::JsonRPCClient;

#[derive(Debug)]
pub struct Client(jsonrpc::Client);

pub struct JsonRPCConfig {
    pub url: String,
    pub user: Option<String>,
    pub pass: Option<String>,
}

impl Client {
    pub fn new(url: String) -> Self {
        let client =
            jsonrpc::Client::simple_http(&url, None, None).expect("Failed to create client");
        Self(client)
    }

    pub fn new_with_config(config: JsonRPCConfig) -> Self {
        let client =
            jsonrpc::Client::simple_http(&config.url, config.user.clone(), config.pass.clone())
                .expect("Failed to create client");

        Self(client)
    }

    pub fn rpc_call<Response>(
        &self,
        method: &str,
        params: &[serde_json::Value],
    ) -> Result<Response, crate::rpc_types::Error>
    where
        Response: for<'a> serde::de::Deserialize<'a> + Debug,
    {
        let raw = serde_json::value::to_raw_value(params)?;
        let req = self.0.build_request(method, Some(&*raw));
        let resp = self
            .0
            .send_request(req)
            .map_err(crate::rpc_types::Error::from);

        Ok(resp?.result()?)
    }
}

impl JsonRPCClient for Client {
    fn call<T: for<'a> serde::de::Deserialize<'a> + Debug>(
        &self,
        method: &str,
        params: &[serde_json::Value],
    ) -> Result<T, crate::rpc_types::Error> {
        self.rpc_call(method, params)
    }
}

#[derive(Debug, Deserialize)]
pub struct JsonRpcResponse<Res> {
    pub jsonrpc: String,
    pub id: u64,
    pub result: Option<Res>,
    pub error: Option<serde_json::Value>,
}