bscscan 0.5.1

BSC (Binance Smart Chain) non-async API in Rust
Documentation
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
use crate::prelude::*;
use crate::types::bsc_types::*;
use crate::environ::Context;

use isahc::prelude::*;
use url::Url;

/// Accounts namespace containing related APIs about accounts
pub struct Accounts;

impl Accounts {
    /// Get list of normal transactions
    ///
    /// # Arguments
    /// * `ctx` - context instance
    /// * `address` - target wallet or contract address to get list of normal transactions
    pub fn get_list_normal_transactions(&self, ctx: &Context, address: &str) -> Result<Vec::<BSCNormalTransactionResponseSuccessVariantResult>, BscError>
    {
        type ResultType = BSCNormalTransactionResponseSuccessVariantResult;
        type JsonType = BSCTransactionResponse::<ResultType>;

        self.get_list_transactions::<ResultType, JsonType>(ctx, BSCApiResponseType::NormalTransaction, address)
    }

    /// Get list of internal transactions
    ///
    /// # Arguments
    /// * `ctx` - context instance
    /// * `address` - target wallet or contract address to get list of internal transactions
    pub fn get_list_internal_transactions(&self, ctx: &Context, address: &str) -> Result<Vec::<BSCInternalTransactionResponseSuccessVariantResult>, BscError>
    {
        type ResultType = BSCInternalTransactionResponseSuccessVariantResult;
        type JsonType = BSCTransactionResponse::<ResultType>;

        self.get_list_transactions::<ResultType, JsonType>(ctx, BSCApiResponseType::InternalTransaction, address)
    }

    /// Internal generic function supporting to get list of transactions for both
    /// normal and internal ones.
    ///
    /// __NOTE__: Get normal and internal transaction APIs are limited to maximum of
    /// 10,000 transactions per-se page * offset must be less than or equal to 10,000.
    /// So it doesn't make sense to use this API for address which has more than
    /// 10,000 transactions.
    fn get_list_transactions<R, J>(&self, ctx: &Context, api_req_type: BSCApiResponseType, address: &str) -> Result<Vec::<R>, BscError>
    where
        R: serde::de::DeserializeOwned,
        J: CompatibleTransactionResponse::<R> + serde::de::DeserializeOwned
    {
        let mut page_number = 1usize;
        let mut is_need_next_page = true;

        // with this number, we would max out at 5 pages
        // which is reasonable as the free rate limit is 5 requests per seconds.
        // It has high chance that < 5 requests will be made per seconds.
        const OFFSET: usize = 2000;

        // rate limit for free tier
        // See https://docs.bscscan.com/support/rate-limits
        const RATE_LIMIT: usize = 10_000;

        let mut ret_txs: Vec::<R> = Vec::new();

        while is_need_next_page {
            if page_number * OFFSET > RATE_LIMIT {
                eprintln!("{}", format!("WARNING: Address has more than {txs_limit} txs limit!", txs_limit=RATE_LIMIT));
                break;
            }

            // beware to always use fully qualified here for type of api_req_type
            let action = match &api_req_type {
                BSCApiResponseType::NormalTransaction => "txlist",
                BSCApiResponseType::InternalTransaction => "txlistinternal"
            };
            let raw_url_str = format!("https://api.bscscan.com/api?module=account&action={action}&address={target_address}&startblock=0&endblock=99999999&page={page}&offset={offset}&sort=asc&apikey={api_key}", action=action, target_address=address, api_key=ctx.api_key, page=page_number, offset=OFFSET);

            let url = match Url::parse(&raw_url_str) {
                Ok(res) => res,
                Err(_) => return Err(BscError::ErrorInternalUrlParsing),
            };

            let request = match isahc::Request::get(url.as_str())
                .version_negotiation(isahc::config::VersionNegotiation::http2())
                .body(()) {
                Ok(res) => res,
                Err(e) => return Err(BscError::ErrorInternalGeneric(Some(format!("Error creating a HTTP request; err={}", e)))),
            };

            match isahc::send(request) {
                Ok(mut res) => {
                    // early return for non-200 HTTP returned code
                    if res.status() != 200 {
                        return Err(BscError::ErrorApiResponse(format!("Error API resonse, with HTTP {code} returned", code=res.status().as_str())));
                    }

                    // use the commented line, or just use what isahc provides conveniently
                    match res.json::<J>() {
                        Ok(json) => {
                            if json.status() == "1" {
                                // NOTE: unfortunate, we need to extract value from within enum
                                // https://stackoverflow.com/questions/34953711/unwrap-inner-type-when-enum-variant-is-known
                                match json.result() {
                                    GenericBSCTransactionResponseResult::Success(mut c) => {
                                        if c.len() == 0 {
                                            is_need_next_page = false;
                                        }
                                        else if c.len() > 0 && c.len() < OFFSET {
                                            ret_txs.append(&mut c);
                                            is_need_next_page = false;
                                        }
                                        else {
                                            ret_txs.append(&mut c);
                                        }
                                    },
                                    // this case should not happen
                                    GenericBSCTransactionResponseResult::Failed(msg_opt) => {
                                        match msg_opt {
                                            Some(msg) => {
                                                return Err(BscError::ErrorApiResponse(format!("un-expected error for success case ({msg})", msg=msg)));
                                            },
                                            None => {
                                                return Err(BscError::ErrorApiResponse(format!("un-expected error for success case")));
                                            }
                                        }
                                    }
                                }
                            }
                            else {
                                // exact text as returned when empty "result" is returned
                                if json.message() == "No transactions found" {
                                    break;
                                }
                                else {
                                    return Err(BscError::ErrorApiResponse(format!("'{message}'", message=json.message())));
                                }
                            }
                        },
                        Err(e) => {
                            eprintln!("{:?}", e);
                            return Err(BscError::ErrorJsonParsing(None));
                        }
                    }
                },
                Err(e) => {
                    let err_msg = format!("{}", e);
                    return Err(BscError::ErrorSendingHttpRequest(Some(err_msg)));
                }
            }

            if is_need_next_page {
                page_number = page_number + 1;
            }
            else {
                break;
            }
        }

        Ok(ret_txs)
    }

    /// Get balance of specified address.
    ///
    /// # Arguments
    /// * `ctx` - context instance
    /// * `address` - target wallet or contract address to get balance of
    pub fn get_balance_address(&self, ctx: &Context, address: &str) -> Result<U256, BscError> {
        let raw_url_str = format!("https://api.bscscan.com/api?module=account&action=balance&address={target_address}&apikey={api_key}", target_address=address, api_key=ctx.api_key);

        let url = match Url::parse(&raw_url_str) {
            Ok(res) => res,
            Err(_) => return Err(BscError::ErrorInternalUrlParsing),
        };

        let request = match isahc::Request::get(url.as_str())
            .version_negotiation(isahc::config::VersionNegotiation::http2())
            .body(()) {
            Ok(res) => res,
            Err(e) => return Err(BscError::ErrorInternalGeneric(Some(format!("Error creating a HTTP request; err={}", e)))),
        };

        match isahc::send(request) {
            Ok(mut res) => {
                // early return for non-200 HTTP returned code
                if res.status() != 200 {
                    return Err(BscError::ErrorApiResponse(format!("Error API resonse, with HTTP {code} returned", code=res.status().as_str())));
                }

                match res.json::<BSCBnbBalanceResponse>() {
                    Ok(json) => {
                        if json.status == "1" {
                            match json.result {
                                GenericBSCBnbBalanceResponseResult::Success(bal) => Ok(bal),
                                GenericBSCBnbBalanceResponseResult::Failed(result_msg) => {
                                    return Err(BscError::ErrorApiResponse(format!("un-expected error for success case ({msg})", msg=result_msg)));
                                }
                            }
                        }
                        else {
                            // safely get text from "result" field
                            // this will ensure that the type of `json.result` is
                            // actually GenericBSCBnbBalanceRespnseResult which is
                            // the failed case.
                            let result_text = match json.result {
                                GenericBSCBnbBalanceResponseResult::Failed(txt) => Some(txt),
                                _ => None,
                            };

                            match result_text {
                                Some(txt) => {
                                    return Err(BscError::ErrorApiResponse(format!("message:{}, result:{}", json.message, txt)));
                                },
                                None => {
                                    return Err(BscError::ErrorApiResponse(format!("message:{}", json.message)));
                                },
                            }
                        }
                    },
                    Err(e) => {
                        eprintln!("{:?}", e);
                        return Err(BscError::ErrorJsonParsing(None));
                    }
                }
            },
            Err(e) => {
                let err_msg = format!("{}", e);
                return Err(BscError::ErrorSendingHttpRequest(Some(err_msg)));
            }
        }
    }

    /// Get balance from multiple addresses.
    /// It has internal check and will return `Err` accordingly if length of
    /// specified `addresses` slice is 0 or more than 20.
    ///
    /// It's better to error out instead of process only up to 20 to notify user
    /// using this function that the input might not be as expected.
    ///
    /// # Arguments
    /// * `ctx` - context instance
    /// * `addresses` - slice of literal string addresses.
    pub fn get_balance_addresses_multi(&self, ctx: &Context, addresses: &[&str]) -> Result<Vec<BSCBnbBalanceMulti>, BscError> {
        let addrs_len = addresses.len();

        if addrs_len == 0 {
            return Err(BscError::ErrorParameter(Some("'count' needs to be more than 0".to_owned())));
        }
        if addrs_len > 20 {
            return Err(BscError::ErrorParameter(Some("'count' cannot be more than 20".to_owned())));
        }

        // build string of addresses, up to 20 addresses
        let mut addresses_str: String = String::new(); 
        for i in 1..addrs_len {
            addresses_str.push_str(addresses[i-1]);
            addresses_str.push(',');
        }
        addresses_str.push_str(addresses[addrs_len-1]);

        let raw_url_str = format!("https://api.bscscan.com/api?module=account&action=balancemulti&address={addresses_str}&tag=latest&apikey={api_key}", addresses_str=&addresses_str, api_key=ctx.api_key);

        let url = match Url::parse(&raw_url_str) {
            Ok(res) => res,
            Err(_) => return Err(BscError::ErrorInternalUrlParsing),
        };

        let request = match isahc::Request::get(url.as_str())
            .version_negotiation(isahc::config::VersionNegotiation::http2())
            .body(()) {
            Ok(res) => res,
            Err(e) => return Err(BscError::ErrorInternalGeneric(Some(format!("Error creating a HTTP request; err={}", e)))),
        };

        match isahc::send(request) {
            Ok(mut res) => {
                // early return for non-200 HTTP returned code
                if res.status() != 200 {
                    return Err(BscError::ErrorApiResponse(format!("Error API resonse, with HTTP {code} returned", code=res.status().as_str())));
                }

                match res.json::<BSCBnbBalanceMultiResponse>() {
                    Ok(json) => {
                        if json.status == "1" {
                            match json.result {
                                GenericBSCBnbBalanceMultiResponseResult::Success(bal_records) => Ok(bal_records),
                                GenericBSCBnbBalanceMultiResponseResult::Failed(result_msg) => Err(BscError::ErrorApiResponse(format!("un-expected error for success case ({msg})", msg=result_msg)))
                            }
                        }
                        else {
                            // safely get text from "result" field
                            // this will ensure that the type of `json.result` is
                            // actually GenericBSCBnbBalanceRespnseResult which is
                            // the failed case.
                            let result_text = match json.result {
                                GenericBSCBnbBalanceMultiResponseResult::Failed(txt) => Some(txt),
                                _ => None,
                            };

                            match result_text {
                                Some(txt) => {
                                    return Err(BscError::ErrorApiResponse(format!("message:{}, result:{}", json.message, txt)));
                                },
                                None => {
                                    return Err(BscError::ErrorApiResponse(format!("message:{}", json.message)));
                                },
                            }
                        }
                    },
                    Err(e) => {
                        eprintln!("{:?}", e);
                        return Err(BscError::ErrorJsonParsing(None));
                    }
                }
            },
            Err(e) => {
                let err_msg = format!("{}", e);
                return Err(BscError::ErrorSendingHttpRequest(Some(err_msg)));
            }
        }
    }

    /// Get BEP-20 transfer events for `address` API request.
    /// This will return only records of transfer from `address`.
    ///
    /// **NOTE**: This function **doesn't** internally check whether the specified address is
    /// in fact EOA address, and not contract address. Thus it will return error
    /// instead.
    ///
    /// # Arguments
    /// * `ctx` - context instance
    /// * `address` - target wallet address. It should not be contract address as
    ///               internally it use `address` parameter to make a request.
    pub fn get_bep20_transfer_events_a(&self, ctx: &Context, address: &str) -> Result<Vec::<BSCBep20TokenTransferEventResponseSuccessVariantResult>, BscError> {
        let mut page_number = 1u8;
        let mut is_need_next_page = true;
        const OFFSET: usize = 2000;

        let mut ret_txs: Vec::<BSCBep20TokenTransferEventResponseSuccessVariantResult> = Vec::new();
     
        while is_need_next_page {
            let raw_url_str = format!("https://api.bscscan.com/api?module=account&action=tokentx&address={target_address}&page={page}&offset={offset}&startblock=0&endblock=999999999&sort=asc&apikey={api_key}", target_address=address, page={page_number}, offset=OFFSET, api_key=ctx.api_key);

            let url = match Url::parse(&raw_url_str) {
                Ok(res) => res,
                Err(_) => return Err(BscError::ErrorInternalUrlParsing),
            };

            let request = match isahc::Request::get(url.as_str())
                .version_negotiation(isahc::config::VersionNegotiation::http2())
                .body(()) {
                Ok(res) => res,
                Err(e) => return Err(BscError::ErrorInternalGeneric(Some(format!("Error creating a HTTP request; err={}", e)))),
            };

            match isahc::send(request) {
                Ok(mut res) => {
                    // early return for non-200 HTTP returned code
                    if res.status() != 200 {
                        return Err(BscError::ErrorApiResponse(format!("Error API resonse, with HTTP {code} returned", code=res.status().as_str())));
                    }

                    match res.json::<BSCBep20TokenTransferEventResponse>() {
                        Ok(json) => {
                            if json.status == "1" {
                                match json.result {
                                    GenericBSCBep20TokenTransferEventResponseResult::Success(mut c) => {
                                        if c.len() == 0 {
                                            is_need_next_page = false;
                                        }
                                        else if c.len() > 0 && c.len() < OFFSET {
                                            ret_txs.append(&mut c);
                                            is_need_next_page = false;
                                        }
                                        else {
                                            ret_txs.append(&mut c);
                                        }
                                    },
                                    // this case should not happen
                                    GenericBSCBep20TokenTransferEventResponseResult::Failed(msg) => {
                                        return Err(BscError::ErrorApiResponse(format!("un-expected error for success case ({msg})", msg=msg)));
                                    }
                                }
                            }
                            else {
                                // exact text as returned when empty "result" is returned
                                if json.message == "No transactions found" {
                                    break;
                                }
                                else {
                                    return Err(BscError::ErrorApiResponse(format!("'{message}'", message=json.message)));
                                }
                            }
                        },
                        Err(e) => {
                            eprintln!("{:?}", e);
                            return Err(BscError::ErrorJsonParsing(None));
                        }
                    }
                },
                Err(e) => {
                    let err_msg = format!("{}", e);
                    return Err(BscError::ErrorSendingHttpRequest(Some(err_msg)));
                }
            }

            if is_need_next_page {
                page_number = page_number + 1;
            }
            else {
                break;
            }
        }

        Ok(ret_txs)
    }
}