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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
use crate::{Cluster, PoseidonResult, RpcTxError, SendTxResponse, Transaction};
use borsh::{BorshDeserialize, BorshSerialize};
use json::JsonValue;
use serde::{Deserialize, Serialize};

#[derive(Debug)]
pub struct RpcClient {
    cluster: Cluster,
    headers: Vec<(String, String)>,
    body: JsonValue,
}

impl RpcClient {
    pub fn new() -> Self {
        RpcClient {
            cluster: Cluster::default(),
            headers: vec![("Content-Type".to_owned(), "application/json".to_owned())],
            body: JsonValue::Null,
        }
    }

    pub fn add_header(&mut self, key: &str, value: &str) -> &mut Self {
        self.headers.push((key.to_owned(), value.to_owned()));

        self
    }

    pub fn add_body(&mut self, body: JsonValue) -> &mut Self {
        self.body = body;

        self
    }

    pub fn common_methods(&mut self, body: JsonValue) -> &mut Self {
        self.add_body(body);

        self
    }

    pub fn prepare_transaction(&mut self, transaction: &Transaction) -> PoseidonResult<&mut Self> {
        let body = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "sendTransaction",
            params: json::array![
                transaction.to_base58()?
            ]
        };

        self.body = body;

        Ok(self)
    }

    pub fn send(&self) -> smol::Task<PoseidonResult<minreq::Response>> {
        let cluster_url = self.cluster.url();
        let body = self.body.clone().to_string();
        let headers = self.headers.clone();

        smol::spawn(async move {
            let mut request = minreq::post(cluster_url).with_body(body);

            for header in headers {
                request = request.with_header(&header.0, &header.1);
            }

            Ok(request.send()?)
        })
    }
}

#[derive(Debug, Clone)]
pub enum TxSendOutcome {
    Success(SendTxResponse),
    Failure(RpcTxError),
}

impl TxSendOutcome {
    pub fn parse_tx(response: minreq::Response) -> PoseidonResult<TxSendOutcome> {
        let first_response = serde_json::from_str::<SendTxResponse>(&response.as_str()?);

        match first_response {
            Ok(value) => Ok(TxSendOutcome::Success(value)),
            Err(first_error) => {
                let err_response = serde_json::from_str::<RpcTxError>(&response.as_str()?);
                match err_response {
                    Ok(value) => Ok(TxSendOutcome::Failure(value)),
                    Err(_) => Err(first_error.into()),
                }
            }
        }
    }
}

#[derive(Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[serde(rename = "camelCase")]
pub struct RpcResponse<T> {
    pub jsonrpc: String,
    pub id: u8,
    pub result: T,
}

#[derive(Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[serde(rename = "camelCase")]
pub struct RpcResponseWithResult<T> {
    pub jsonrpc: String,
    pub id: u8,
    pub result: RpcResult<T>,
}

#[derive(Debug, Serialize, Deserialize, BorshSerialize, BorshDeserialize)]
#[serde(rename = "camelCase")]
pub struct RpcResult<T> {
    pub context: Context,
    pub value: T,
}

#[derive(
    Debug,
    PartialEq,
    Eq,
    Ord,
    PartialOrd,
    Clone,
    Deserialize,
    Serialize,
    BorshSerialize,
    BorshDeserialize,
)]
#[serde(rename_all = "camelCase")]
pub struct Context {
    pub slot: u64,
}

pub(crate) async fn request<T: serde::de::DeserializeOwned>(
    body: json::JsonValue,
) -> PoseidonResult<RpcResponse<T>> {
    let mut rpc = RpcClient::new();
    rpc.common_methods(body);
    let response = rpc.send().await?;
    let deser_response: RpcResponse<T> = serde_json::from_str(response.as_str()?)?;

    Ok(deser_response)
}

pub(crate) async fn request_with_result<T: serde::de::DeserializeOwned>(
    body: json::JsonValue,
) -> PoseidonResult<RpcResponseWithResult<T>> {
    let mut rpc = RpcClient::new();
    rpc.common_methods(body);
    let response = rpc.send().await?;
    let deser_response: RpcResponseWithResult<T> = serde_json::from_str(response.as_str()?)?;

    Ok(deser_response)
}