crypto-pay-api 0.2.1

A Rust client library for Crypto Pay API provided by Telegram CryptoBot
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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
mod builder;

use std::str::FromStr;

use crate::{
    error::{CryptoBotError, CryptoBotResult},
    models::{APIMethod, ApiResponse, Method},
};

#[cfg(test)]
use crate::models::ExchangeRate;

use builder::{ClientBuilder, NoAPIToken};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use serde::{de::DeserializeOwned, Serialize};

pub const DEFAULT_API_URL: &str = "https://pay.crypt.bot/api";
pub const DEFAULT_TIMEOUT: u64 = 30;
pub const DEFAULT_WEBHOOK_EXPIRATION_TIME: u64 = 600;

#[derive(Debug)]
pub struct CryptoBot {
    pub(crate) api_token: String,
    pub(crate) client: reqwest::Client,
    pub(crate) base_url: String,
    pub(crate) headers: Option<Vec<(HeaderName, HeaderValue)>>,
    #[cfg(test)]
    pub(crate) test_rates: Option<Vec<ExchangeRate>>,
}

impl CryptoBot {
    /// Returns a new builder for creating a customized CryptoBot client
    ///
    /// The builder pattern allows you to customize all aspects of the client,
    /// including timeout, base URL and headers settings.
    ///
    /// # Available Settings
    /// * `api_token` - Required, the API token from [@CryptoBot](https://t.me/CryptoBot)
    /// * `base_url` - Optional, defaults to "https://pay.crypt.bot/api"
    /// * `timeout` - Optional, defaults to 30 seconds
    /// * `headers` - Optional, custom headers for all requests
    ///
    /// # Example
    /// ```
    /// use crypto_pay_api::prelude::*;
    /// use std::time::Duration;
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), CryptoBotError> {
    ///     let client = CryptoBot::builder()
    ///         .api_token("YOUR_API_TOKEN")
    ///         .base_url("https://testnet-pay.crypt.bot/api")  // Use testnet
    ///         .timeout(Duration::from_secs(60))               // 60 second timeout
    ///     .headers(vec![(
    ///         HeaderName::from_static("x-custom-header"),
    ///         HeaderValue::from_static("custom_value")
    ///     )])
    ///     .build()?;
    ///
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # See Also
    /// * [`ClientBuilder`](struct.ClientBuilder.html) - The builder type
    pub fn builder() -> ClientBuilder<NoAPIToken> {
        ClientBuilder::new()
    }

    /// Makes a request to the CryptoBot API
    ///
    /// # Arguments
    /// * `method` - The method to call, must be one of the ApiMethod enum values
    /// * `params` - The parameters to pass to the method
    ///
    /// # Returns
    /// * `Ok(R)` - The response from the API
    /// * `Err(CryptoBotError)` - If the request fails or the response is not valid
    pub(crate) async fn make_request<T, R>(&self, method: &APIMethod, params: Option<&T>) -> CryptoBotResult<R>
    where
        T: Serialize + ?Sized,
        R: DeserializeOwned,
    {
        let url = format!("{}/{}", self.base_url, method.endpoint.as_str());

        let mut request_headers = HeaderMap::new();

        let token_header = HeaderName::from_str("Crypto-Pay-Api-Token")?;

        request_headers.insert(token_header, HeaderValue::from_str(&self.api_token)?);

        if let Some(custom_headers) = &self.headers {
            for (name, value) in custom_headers.iter() {
                request_headers.insert(name, value.clone());
            }
        }

        let mut request = match method.method {
            Method::POST => self.client.post(&url).headers(request_headers),
            Method::GET => self.client.get(&url).headers(request_headers),
            Method::DELETE => self.client.delete(&url).headers(request_headers),
        };

        if let Some(params) = params {
            request = request.json(params);
        }

        let response = request.send().await?;

        if !response.status().is_success() {
            return Err(CryptoBotError::HttpError(response.error_for_status().unwrap_err()));
        }

        let text = response.text().await?;

        let api_response: ApiResponse<R> = serde_json::from_str(&text).map_err(|e| CryptoBotError::ApiError {
            code: -1,
            message: "Failed to parse API response".to_string(),
            details: Some(serde_json::json!({ "error": e.to_string() })),
        })?;

        if !api_response.ok {
            return Err(CryptoBotError::ApiError {
                code: api_response.error_code.unwrap_or(0),
                message: api_response.error.unwrap_or_default(),
                details: None,
            });
        }

        api_response.result.ok_or(CryptoBotError::NoResult)
    }

    #[cfg(test)]
    pub fn test_client() -> Self {
        use crate::utils::test_utils::TestContext;

        Self {
            api_token: "test_token".to_string(),
            client: reqwest::Client::new(),
            base_url: "http://test.example.com".to_string(),
            headers: None,
            test_rates: Some(TestContext::mock_exchange_rates()),
        }
    }
}

#[cfg(test)]
mod tests {
    use mockito::{Matcher, Mock};
    use reqwest::header::{HeaderName, HeaderValue};
    use serde::{Deserialize, Serialize};
    use serde_json::json;

    use crate::{
        api::BalanceAPI,
        models::{APIEndpoint, Balance},
        utils::test_utils::TestContext,
    };

    use super::*;

    #[derive(Debug, Serialize)]
    struct DummyPayload {
        value: String,
    }

    #[derive(Debug, Deserialize, PartialEq)]
    struct DummyResponse {
        stored: String,
    }
    #[derive(Debug, Serialize)]
    struct DeletePayload {
        invoice_id: u64,
    }
    impl TestContext {
        pub fn mock_malformed_json_response(&mut self) -> Mock {
            self.server
                .mock("GET", "/getBalance")
                .with_header("content-type", "application/json")
                .with_body("invalid json{")
                .create()
        }
    }

    #[test]
    fn test_malformed_json_response() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_malformed_json_response();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code: -1,
                message,
                details: Some(details)
            }) if message == "Failed to parse API response"
            && details.get("error").is_some()
        ));
    }

    #[test]
    fn test_invalid_response_structure() {
        let mut ctx = TestContext::new();

        let _m = ctx
            .server
            .mock("GET", "/getBalance")
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "ok": true,
                    "result": "not_an_array"
                })
                .to_string(),
            )
            .create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code: -1,
                message,
                details: Some(details)
            }) if message == "Failed to parse API response"
                && details.get("error").is_some()
        ));
    }

    #[test]
    fn test_empty_response() {
        let mut ctx = TestContext::new();

        // Mock empty response
        let _m = ctx
            .server
            .mock("GET", "/getBalance")
            .with_header("content-type", "application/json")
            .with_body("")
            .create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code: -1,
                message,
                details: Some(details)
            }) if message == "Failed to parse API response"
                && details.get("error").is_some()
        ));
    }

    #[test]
    fn test_invalid_api_token_header() {
        let client = CryptoBot {
            api_token: "invalid\u{0000}token".to_string(),
            client: reqwest::Client::new(),
            base_url: "http://test.example.com".to_string(),
            headers: None,
            #[cfg(test)]
            test_rates: None,
        };

        let method = APIMethod {
            endpoint: APIEndpoint::GetBalance,
            method: Method::GET,
        };
        let ctx = TestContext::new();

        let result = ctx.run(async { client.make_request::<(), Vec<Balance>>(&method, None).await });

        assert!(matches!(result, Err(CryptoBotError::InvalidHeaderValue(_))));
    }

    #[test]
    fn test_api_error_response() {
        let mut ctx = TestContext::new();

        // Mock API error response with error code and message
        let _m = ctx
            .server
            .mock("GET", "/getBalance")
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "ok": false,
                    "error": "Test error message",
                    "error_code": 123
                })
                .to_string(),
            )
            .create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code,
                message,
                details,
            }) if code == 123
                && message == "Test error message"
                && details.is_none()
        ));
    }

    #[test]
    fn test_api_error_response_missing_fields() {
        let mut ctx = TestContext::new();

        // Mock API error response without error code and message
        let _m = ctx
            .server
            .mock("GET", "/getBalance")
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "ok": false
                })
                .to_string(),
            )
            .create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code,
                message,
                details,
            }) if code == 0
                && message.is_empty()
                && details.is_none()
        ));
    }

    #[test]
    fn test_api_error_response_partial_fields() {
        let mut ctx = TestContext::new();

        // Mock API error response with only error message
        let _m = ctx
            .server
            .mock("GET", "/getBalance")
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "ok": false,
                    "error": "Test error message"
                })
                .to_string(),
            )
            .create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(
            result,
            Err(CryptoBotError::ApiError {
                code,
                message,
                details,
            }) if code == 0
                && message == "Test error message"
                && details.is_none()
        ));
    }

    #[test]
    fn test_http_error_response() {
        let mut ctx = TestContext::new();
        let _m = ctx.server.mock("GET", "/getBalance").with_status(404).create();

        let client = CryptoBot::builder()
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_balance().execute().await });

        assert!(matches!(result, Err(CryptoBotError::HttpError(_))));
    }

    #[test]
    fn test_make_request_with_custom_headers_and_body() {
        let mut ctx = TestContext::new();

        let _m = ctx
            .server
            .mock("POST", "/createInvoice")
            .match_header("X-Custom-Header", "test-value")
            .match_header("Crypto-Pay-Api-Token", "test")
            .match_body(Matcher::JsonString(
                json!({
                    "value": "payload"
                })
                .to_string(),
            ))
            .with_header("content-type", "application/json")
            .with_body(
                json!({
                    "ok": true,
                    "result": {
                        "stored": "payload"
                    }
                })
                .to_string(),
            )
            .create();

        let client = CryptoBot::builder()
            .headers(vec![(
                HeaderName::from_static("x-custom-header"),
                HeaderValue::from_static("test-value"),
            )])
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let method = APIMethod {
            endpoint: APIEndpoint::CreateInvoice,
            method: Method::POST,
        };

        let payload = DummyPayload {
            value: "payload".to_string(),
        };

        let result: Result<DummyResponse, _> = ctx.run(async { client.make_request(&method, Some(&payload)).await });

        assert_eq!(
            result.unwrap(),
            DummyResponse {
                stored: "payload".to_string()
            }
        );
    }

    #[test]
    fn test_make_request_delete_with_payload_and_headers() {
        let mut ctx = TestContext::new();
        let _m = ctx
            .server
            .mock("DELETE", "/deleteInvoice")
            .match_header("X-Extra", "extra")
            .match_header("Crypto-Pay-Api-Token", "test")
            .match_body(Matcher::JsonString(
                json!({
                    "invoice_id": 7
                })
                .to_string(),
            ))
            .with_header("content-type", "application/json")
            .with_body(json!({"ok": true, "result": true}).to_string())
            .create();

        let client = CryptoBot::builder()
            .headers(vec![(
                HeaderName::from_static("x-extra"),
                HeaderValue::from_static("extra"),
            )])
            .api_token("test")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let method = APIMethod {
            endpoint: APIEndpoint::DeleteInvoice,
            method: Method::DELETE,
        };

        let payload = DeletePayload { invoice_id: 7 };

        let result: Result<bool, _> = ctx.run(async { client.make_request(&method, Some(&payload)).await });
        assert_eq!(result.unwrap(), true);
    }
}