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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
use crate::{
    request, request_with_result, BorrowedBase58PublicKey, Commitment, PoseidonError,
    PoseidonResult, PublicKey, RpcResponse, RpcResponseWithResult,
};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

pub const LAMPORT: u64 = 1_000_000_000;

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct GetLatestBlockhash {
    pub blockhash: String,
    pub last_valid_block_height: u64,
}

impl GetLatestBlockhash {
    pub async fn process(
        commitment: Commitment,
    ) -> PoseidonResult<RpcResponseWithResult<GetLatestBlockhash>> {
        let commitment: &str = commitment.into();
        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "getLatestBlockhash",
            params: json::array![json::object!{
                commitment: commitment,
            }]
        };

        Ok(request_with_result::<GetLatestBlockhash>(body).await?)
    }

    pub fn get_hash(response: RpcResponseWithResult<GetLatestBlockhash>) -> GetLatestBlockhash {
        response.result.value
    }

    pub async fn as_bytes(commitment: Commitment) -> PoseidonResult<[u8; 32]> {
        let response = GetLatestBlockhash::process(commitment).await?;
        let blockhash = GetLatestBlockhash::get_hash(response).blockhash;

        let decoded = bs58::decode(&blockhash).into_vec()?;
        match decoded.try_into() {
            Ok(blockhash) => Ok(blockhash),
            Err(_) => Err(PoseidonError::ErrorConvertingToU832),
        }
    }

    pub fn to_bytes(&self) -> PoseidonResult<[u8; 32]> {
        let decoded = bs58::decode(&self.blockhash).into_vec()?;
        match decoded.try_into() {
            Ok(blockhash) => Ok(blockhash),
            Err(_) => Err(PoseidonError::ErrorConvertingToU832),
        }
    }
}

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct GetFees {
    pub blockhash: String,
    pub fee_calculator: FeeCalculator,
    pub last_valid_block_height: u64,
    pub last_valid_slot: u64,
}

impl GetFees {
    pub async fn process() -> PoseidonResult<RpcResponseWithResult<GetFees>> {
        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "getFees",
        };

        Ok(request_with_result::<GetFees>(body).await?)
    }
}

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestAirdrop {
    public_key: PublicKey,
    lamports: u8,
    commitment: Commitment,
}

impl RequestAirdrop {
    pub fn new(public_key: PublicKey) -> Self {
        RequestAirdrop {
            public_key,
            lamports: 2,
            commitment: Commitment::Finalized,
        }
    }

    pub fn add_lamports(&mut self, lamports: u8) -> &mut Self {
        self.lamports = lamports;

        self
    }

    pub fn change_commitment(&mut self, commitment: Commitment) -> &mut Self {
        self.commitment = commitment;

        self
    }

    pub async fn process(&self) -> PoseidonResult<RpcResponse<String>> {
        let public_key = bs58::encode(&self.public_key).into_string();
        let lamports = self.lamports as u64 * LAMPORT;

        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "requestAirdrop",
            params: json::array![public_key, lamports]
        };

        Ok(request::<String>(body).await?)
    }
}

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct FeeCalculator {
    pub lamports_per_signature: u64,
}

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct GetMinimumBalanceForRentExemption;

impl GetMinimumBalanceForRentExemption {
    pub async fn process<T>() -> PoseidonResult<RpcResponse<u64>> {
        let size = core::mem::size_of::<T>() as u64;

        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "getMinimumBalanceForRentExemption",
            params: json::array![
                size
            ]
        };

        Ok(request::<u64>(body).await?)
    }
    pub async fn process_precalculated(size: usize) -> PoseidonResult<RpcResponse<u64>> {
        let size = size as u64;

        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "getMinimumBalanceForRentExemption",
            params: json::array![
                size
            ]
        };

        Ok(request::<u64>(body).await?)
    }
}

#[derive(Debug, Serialize, Deserialize, BorshDeserialize, BorshSerialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAccountInfo {
    data: (String, String), // (PublicKey String, encoding)
    executable: bool,
    lamports: u64,
    owner: String, // Base58 formatted PublicKey
    rent_epoch: u64,
}

impl GetAccountInfo {
    pub async fn process<'pn>(
        public_key: BorrowedBase58PublicKey<'pn>,
    ) -> PoseidonResult<RpcResponseWithResult<GetAccountInfo>> {
        let body: json::JsonValue = json::object! {
            jsonrpc: "2.0",
            id: 1u8,
            method: "getAccountInfo",
            params: [
                public_key,
                {
                    "encoding": "base58"
                }
            ]
        };

        Ok(request_with_result::<GetAccountInfo>(body).await?)
    }
}