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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
//! # The Solscan Wrapper
//! This represent a wrapper for the SolscanAPI

use reqwest::{Client, Error, StatusCode};
use serde::de::DeserializeOwned;

use crate::enums::solscan_endpoints::SolscanEndpoints;
use crate::enums::solscan_errors::SolscanError;
use crate::r#const::SOLSCANBASEURL;
use crate::structs::account_info::AccountInfo;
use crate::structs::block_result::BlockResult;
use crate::structs::chain_info::ChainInfo;
use crate::structs::sol_transfer::SolTransferList;
use crate::structs::spl_transfer::SplTransfer;
use crate::structs::token::Token;
use crate::structs::token_holder::TokenHolders;
use crate::structs::token_market_item::TokenMarketItem;
use crate::structs::token_meta::TokenMeta;
use crate::structs::transaction::Transaction;
use crate::structs::transaction_last::TransactionLast;
use crate::structs::transaction_list_item::TransactionListItem;

/// `SolscanAPI` is a struct that contains a `String` for the SolscanURL and a `Client` which is the instance.
///
/// Properties:
///
/// A doc comment.
/// A doc comment.
/// A doc comment.
/// * `base_url`: The base URL for the Solscan API.
/// * `client`: This is the HTTP client that will be used to make requests to the Solscan API.
pub struct SolscanAPI {
    base_url: String,
    client: Client,
}


/// Creating a default implementation for the SolscanAPI struct.
impl Default for SolscanAPI {
    /// It creates a new instance of the SolscanAPI struct.
    ///
    /// Returns:
    ///
    /// A new instance of the SolscanAPI struct.
    fn default() -> Self {
        SolscanAPI::new()
    }
}


/// Implementation of the struct called SolscanAPI.
impl SolscanAPI {
    /// It creates a new instance of the SolscanAPI struct.
    ///
    /// Returns:
    ///
    /// A new instance of the SolscanAPI struct.
    pub fn new() -> SolscanAPI {
        SolscanAPI {
            base_url: SOLSCANBASEURL.parse().unwrap(),
            client: Client::new(),
        }
    }
    /// > This function creates a new instance of the SolscanAPI struct, which is used to make
    /// custom requests to the Solscan API (mostly useful for mockups)
    ///
    /// Arguments:
    ///
    /// * `solscan_url`: The URL of the Solscan API.
    ///
    /// Returns:
    ///
    /// A new instance of the SolscanAPI struct.
    pub fn new_with_url(solscan_url: String) -> SolscanAPI {
        SolscanAPI {
            base_url: solscan_url,
            client: Client::new(),
        }
    }

    //region private functions
    /// It takes a string, appends it to the base url, makes a get request, checks the status code, and
    /// returns the text of the response.
    /// Represents the actual GET request.
    ///
    /// Arguments:
    ///
    /// * `url_path`: The path to the API endpoint you want to call.
    ///
    /// Returns:
    ///
    /// A Result<String, SolscanError>
    async fn fetch(&self, url_path: String) -> Result<String, SolscanError> {
        println!("{:?}", self.base_url.to_string() + url_path.as_str());
        match {
            self.client.get(self.base_url.to_string() + url_path.as_str())
                .header("User-Agent", "Mozilla/5.0")
                .send()
                .await
        } {
            Ok(response) => {
                if response.status() == 200 {
                    match response.text().await {
                        Ok(text) => { Ok(text) }
                        Err(e) => {
                            println!("{:?}", e);
                            Err(SolscanError::APICConversionError)
                        }
                    }
                } else {
                    println!("API-Status Code is: {:?}", response.status());
                    Err(SolscanError::APIWrongStatusCode)
                }
            }
            Err(e) => {
                println!("{:?}", e);
                Err(SolscanError::APIError)
            }
        }
    }

    /// It chooses which endpoint to use to fetch data from the Solscan API.
    ///
    /// Arguments:
    ///
    /// * `endpoint`: SolscanEndpoints - This is the endpoint you want to use.
    /// * `url_endpoint`: The endpoint to be appended to the base url.
    ///
    /// Returns:
    ///
    /// A Result<T, SolscanError>
    async fn solscan_fetch<T: DeserializeOwned>(&self, endpoint: SolscanEndpoints, url_endpoint: &str) -> Result<T, SolscanError> {
        match {
            self.fetch(
                match endpoint {
                    SolscanEndpoints::BlockLast => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::BlockTransactions => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::Block => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::TransactionLast => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::Transaction => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::AccountTokens => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::AccountTransaction => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::AccountStakeAccounts => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::AccountSPLTransfers => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::AccountSolTransfers => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::Account => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::TokenHolders => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::TokenMeta => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::MarketToken => endpoint.value().to_owned() + url_endpoint,
                    SolscanEndpoints::ChainInfo => endpoint.value().to_owned() + url_endpoint,
                    _ => { "none".to_string() }
                }
            ).await
        } {
            Ok(api_data) => {
                match serde_json::from_str::<T>(api_data.as_str()) {
                    Ok(api_data) => {
                        Ok(api_data)
                    }
                    Err(e) => {
                        println!("{:?}", e);
                        Err(SolscanError::SerializeError)
                    }
                }
            }
            Err(e) => {
                println!("{:?}", e);
                Err(SolscanError::APIError)
            }
        }
    }
    //endregion

    //region public functions

    //region Ping
    /// It checks the status of the endpoint.
    ///
    /// Arguments:
    ///
    /// * `endpoint`: The endpoint to ping. If none is provided, the base url will be used.
    ///
    /// Returns:
    ///
    /// A Result<StatusCode, Error>
    pub async fn ping_status(&self, endpoint: Option<String>) -> Result<StatusCode, Error> {
        Ok(self.client.get(self.base_url.to_string() + endpoint.unwrap_or_default().as_str()).header("User-Agent", "Mozilla/5.0").send().await?.status())
    }
    //endregion

    //region Block
    /// It gets the last block
    ///
    /// Arguments:
    ///
    /// * `limit`: The number of blocks to return.
    ///
    /// Returns:
    ///
    /// A Result<Vec<BlockResult>, SolscanError>
    pub async fn get_block_last(&self, limit: Option<i64>) -> Result<Vec<BlockResult>, SolscanError> {
        let mut url_endpoint: String = "".to_string();
        if limit.is_some() {
            url_endpoint += &*format!("?limit={}", limit.unwrap());
        }
        self.solscan_fetch::<Vec<BlockResult>>(SolscanEndpoints::BlockLast, url_endpoint.as_str()).await
    }
    /// It gets the transactions for a block.
    ///
    /// Arguments:
    ///
    /// * `block`: The block number to get transactions for.
    /// * `offset`: The offset of the first transaction to return.
    /// * `limit`: The number of transactions to return.
    ///
    /// Returns:
    ///
    /// A Result<Vec<TransactionLast>, SolscanError>
    pub async fn get_block_transactions(&self, block: i64, offset: Option<i64>, limit: Option<i64>) -> Result<Vec<TransactionLast>, SolscanError> {
        let mut url_endpoint: String = format!("?block={}", block);
        if offset.is_some() {
            url_endpoint += &*format!("&offset={}", offset.unwrap());
        }
        if limit.is_some() {
            url_endpoint += &*format!("&limit={}", limit.unwrap());
        }
        self.solscan_fetch::<Vec<TransactionLast>>(SolscanEndpoints::BlockTransactions, url_endpoint.as_str()).await
    }
    /// It gets the block information for a given block number.
    ///
    /// Arguments:
    ///
    /// * `block`: The block number you want to query
    ///
    /// Returns:
    ///
    /// A Result<BlockResult, SolscanError>
    pub async fn get_block_block(&self, block: i64) -> Result<BlockResult, SolscanError> {
        let url_endpoint: String = format!("/{}", block);
        self.solscan_fetch::<BlockResult>(SolscanEndpoints::Block, url_endpoint.as_str()).await
    }
    //endregion

    //region Transaction
    /// It gets the last transactions from the blockchain.
    ///
    /// Arguments:
    ///
    /// * `limit`: The number of transactions to return.
    ///
    /// Returns:
    ///
    /// A  Result<Vec<TransactionLast>, SolscanError>
    pub async fn get_transaction_last(&self, limit: Option<i64>) -> Result<Vec<TransactionLast>, SolscanError> {
        let mut url_endpoint: String = "".to_string();
        if limit.is_some() {
            url_endpoint += &*format!("?limit={}", limit.unwrap())
        }
        self.solscan_fetch::<Vec<TransactionLast>>(SolscanEndpoints::TransactionLast, url_endpoint.as_str()).await
    }
    /// It fetches a transaction from the blockchain.
    ///
    /// Arguments:
    ///
    /// * `signature`: The transaction hash
    ///
    /// Returns:
    ///
    /// A Result<Transaction, SolscanError>
    pub async fn get_transaction(&self, signature: &str) -> Result<Transaction, SolscanError> {
        let url_endpoint: String = format!("/{}", signature);
        self.solscan_fetch::<Transaction>(SolscanEndpoints::Transaction, url_endpoint.as_str()).await
    }
    //endregion

    //region Transaction
    /// It fetches the tokens associated with an account.
    ///
    /// Arguments:
    ///
    /// * `account`: The address of the account you want to get the tokens for.
    ///
    /// Returns:
    ///
    /// A Result<Vec<Token>, SolscanError>
    pub async fn get_account_tokens(&self, account: &str) -> Result<Vec<Token>, SolscanError> {
        let url_endpoint: String = format!("?account={}", account);
        self.solscan_fetch::<Vec<Token>>(SolscanEndpoints::AccountTokens, url_endpoint.as_str()).await
    }
    /// It gets the transactions for a given account.
    ///
    /// Arguments:
    ///
    /// * `account`: The address of the account you want to get the transactions for.
    /// * `before_hash`: The hash of the transaction you want to start from.
    /// * `limit`: The number of transactions to return.
    ///
    /// Returns:
    ///
    /// A Result<Vec<TransactionListItem>, SolscanError>
    pub async fn get_account_transactions(&self, account: &str, before_hash: Option<String>, limit: Option<i64>) -> Result<Vec<TransactionListItem>, SolscanError> {
        let mut url_endpoint: String = format!("?account={}", account);
        if before_hash.is_some() {
            url_endpoint += &*format!("&beforeHash={}", before_hash.unwrap())
        }
        if limit.is_some() {
            url_endpoint += &*format!("&limit={}", limit.unwrap())
        }
        self.solscan_fetch::<Vec<TransactionListItem>>(SolscanEndpoints::AccountTransaction, url_endpoint.as_str()).await
    }
    /// It returns a list of accounts that have staked to the given account.
    ///
    /// Arguments:
    ///
    /// * `account`: The account address to query
    ///
    /// Returns:
    ///
    /// A Result<Vec<Token>, SolscanError>
    pub async fn get_account_stake_accounts(&self, account: &str) -> Result<Vec<Token>, SolscanError> {
        let url_endpoint: String = format!("?account={}", account);
        self.solscan_fetch::<Vec<Token>>(SolscanEndpoints::AccountStakeAccounts, url_endpoint.as_str()).await
    }
    /// It fetches the account spl transfer data from the solscan api.
    ///
    /// Arguments:
    ///
    /// * `account`: The account address to query
    /// * `form_time`: The start time of the query.
    /// * `to_time`: The time to end the search at.
    /// * `offset`: The offset of the first result to return.
    /// * `limit`: The number of results to return.
    ///
    /// Returns:
    ///
    /// A Result<SplTransfer, SolscanError>
    pub async fn get_account_spl_transfer(&self, account: &str, form_time: Option<u64>, to_time: Option<u64>, offset: Option<i64>, limit: Option<i64>) -> Result<SplTransfer, SolscanError> {
        let mut url_endpoint: String = format!("?account={}", account);
        if form_time.is_some() {
            url_endpoint += &*format!("&form_time={}", form_time.unwrap())
        }
        if to_time.is_some() {
            url_endpoint += &*format!("&to_time={}", to_time.unwrap())
        }
        if offset.is_some() {
            url_endpoint += &*format!("&offset={}", offset.unwrap())
        }
        if limit.is_some() {
            url_endpoint += &*format!("&limit={}", limit.unwrap())
        }
        self.solscan_fetch::<SplTransfer>(SolscanEndpoints::AccountSPLTransfers, url_endpoint.as_str()).await
    }
    /// It gets the SOL transfers for a given account.
    ///
    /// Arguments:
    ///
    /// * `account`: The account address to query
    /// * `form_time`: The start time of the query.
    /// * `to_time`: The timestamp of the last block you want to include in the results.
    /// * `offset`: The offset of the first result to return.
    /// * `limit`: The number of results to return.
    ///
    /// Returns:
    ///
    /// A Result<SolTransferList, SolscanError>
    pub async fn get_account_sol_transfer(&self, account: &str, form_time: Option<u64>, to_time: Option<u64>, offset: Option<i64>, limit: Option<i64>) -> Result<SolTransferList, SolscanError> {
        let mut url_endpoint: String = format!("?account={}", account);
        if form_time.is_some() {
            url_endpoint += &*format!("&form_time={}", form_time.unwrap())
        }
        if to_time.is_some() {
            url_endpoint += &*format!("&to_time={}", to_time.unwrap())
        }
        if offset.is_some() {
            url_endpoint += &*format!("&offset={}", offset.unwrap())
        }
        if limit.is_some() {
            url_endpoint += &*format!("&limit={}", limit.unwrap())
        }
        self.solscan_fetch::<SolTransferList>(SolscanEndpoints::AccountSolTransfers, url_endpoint.as_str()).await
    }
    /// It fetches the account information of the given account.
    ///
    /// Arguments:
    ///
    /// * `account`: The account address to query
    ///
    /// Returns:
    ///
    /// A Result<AccountInfo, SolscanError>
    pub async fn get_account_account(&self, account: &str) -> Result<AccountInfo, SolscanError> {
        let url_endpoint: String = format!("/{}", account);
        self.solscan_fetch::<AccountInfo>(SolscanEndpoints::Account, url_endpoint.as_str()).await
    }
    //endregion

    //region Transaction
    /// It returns a list of token holders for a given token address.
    ///
    /// Arguments:
    ///
    /// * `account`: The address of the token contract
    /// * `offset`: The offset of the first result to return.
    /// * `limit`: The number of results to return.
    ///
    /// Returns:
    ///
    /// A Result<TokenHolders, SolscanError>
    pub async fn get_token_holders(&self, account: &str, offset: Option<i64>, limit: Option<i64>) -> Result<TokenHolders, SolscanError> {
        let mut url_endpoint: String = format!("?tokenAddress={}", account);
        if offset.is_some() {
            url_endpoint += &*format!("&offset={}", offset.unwrap())
        }
        if limit.is_some() {
            url_endpoint += &*format!("&limit={}", limit.unwrap())
        }
        self.solscan_fetch::<TokenHolders>(SolscanEndpoints::TokenHolders, url_endpoint.as_str()).await
    }
    /// It fetches the token meta data for a given token address.
    ///
    /// Arguments:
    ///
    /// * `account`: The address of the token contract
    ///
    /// Returns:
    ///
    /// A Result<TokenMeta, SolscanError>
    pub async fn get_token_meta(&self, account: &str) -> Result<TokenMeta, SolscanError> {
        let url_endpoint: String = format!("?tokenAddress={}", account);
        self.solscan_fetch::<TokenMeta>(SolscanEndpoints::TokenMeta, url_endpoint.as_str()).await
    }
    //endregion

    //region MarketToken
    /// It fetches the token market item for the given account.
    ///
    /// Arguments:
    ///
    /// * `account`: The address of the token contract
    ///
    /// Returns:
    ///
    /// A Result<TokenMarketItem, SolscanError>
    pub async fn get_market_token(&self, account: &str) -> Result<TokenMarketItem, SolscanError> {
        let url_endpoint: String = format!("/{}", account);
        self.solscan_fetch::<TokenMarketItem>(SolscanEndpoints::MarketToken, url_endpoint.as_str()).await
    }
    //endregion

    //region ChainInfo
    /// It gets the chain info from the Solana blockchain.
    ///
    /// Returns:
    ///
    /// A Result<ChainInfo, SolscanError>
    pub async fn get_chain_info(&self) -> Result<ChainInfo, SolscanError> {
        let url_endpoint: String = "/".to_string();
        self.solscan_fetch::<ChainInfo>(SolscanEndpoints::ChainInfo, url_endpoint.as_str()).await
    }
    //endregion
}

#[cfg(test)]
pub mod test_solscan_inner {
    use crate::r#const::SOLSCANBASEURL;
    use crate::solscan::SolscanAPI;

    #[test]
    fn test_init_baseurl() {
        let solscan_api = SolscanAPI::new();
        assert_eq!(solscan_api.base_url, SOLSCANBASEURL);
    }
}