web3_rpc/
client.rs

1use crate::model::JsonRpcError;
2use anyhow::bail;
3use reqwest::{Response, StatusCode};
4use serde_json::Value;
5use std::collections::HashMap;
6
7#[derive(Clone)]
8pub struct Client {
9    pub url: String,
10    pub client: reqwest::Client,
11}
12
13impl Client {
14    pub fn new(url: String) -> Self {
15        Client {
16            url: url,
17            client: reqwest::Client::new(),
18        }
19    }
20
21    pub async fn post(&self, payload: Value) -> anyhow::Result<String> {
22        let response = reqwest::Client::new()
23            .post(&self.url)
24            .json(&payload)
25            .send()
26            .await?;
27
28        self.handler(response).await
29    }
30
31    async fn handler(&self, response: Response) -> anyhow::Result<String> {
32        match response.status() {
33            StatusCode::OK => {
34                let text = response.text().await?.as_str().to_string();
35                if text.find("error") != None {
36                    let e: JsonRpcError<HashMap<String, String>> =
37                        serde_json::from_str(text.as_str())?;
38                    bail!(e.error.message)
39                }
40                return Ok(text);
41            }
42            StatusCode::INTERNAL_SERVER_ERROR => {
43                bail!("Internal Server Error");
44            }
45            StatusCode::SERVICE_UNAVAILABLE => {
46                bail!("Service Unavailable");
47            }
48            StatusCode::UNAUTHORIZED => {
49                bail!("Unauthorized");
50            }
51            StatusCode::BAD_REQUEST => {
52                bail!(format!("Bad Request: {:?}", response));
53            }
54            s => {
55                bail!(format!("Received response: {:?}", s));
56            }
57        };
58    }
59}