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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
use async_trait::async_trait;
use std::marker::PhantomData;

use rust_decimal::Decimal;

use crate::utils::types::IntoDecimal;
use crate::{
    client::CryptoBot,
    error::{CryptoBotError, CryptoBotResult, ValidationErrorKind},
    models::{
        APIEndpoint, APIMethod, CreateInvoiceParams, CryptoCurrencyCode, CurrencyType, DeleteInvoiceParams,
        FiatCurrencyCode, GetInvoicesParams, GetInvoicesResponse, Invoice, InvoiceStatus, Method, Missing,
        PayButtonName, Set, SwapToAssets,
    },
    validation::{validate_amount, validate_count, ContextValidate, FieldValidate, ValidationContext},
};

use super::ExchangeRateAPI;
use super::InvoiceAPI;

pub struct DeleteInvoiceBuilder<'a> {
    client: &'a CryptoBot,
    invoice_id: u64,
}

impl<'a> DeleteInvoiceBuilder<'a> {
    pub fn new(client: &'a CryptoBot, invoice_id: u64) -> Self {
        Self { client, invoice_id }
    }

    /// Executes the request to delete the invoice
    pub async fn execute(self) -> CryptoBotResult<bool> {
        let params = DeleteInvoiceParams {
            invoice_id: self.invoice_id,
        };
        self.client
            .make_request(
                &APIMethod {
                    endpoint: APIEndpoint::DeleteInvoice,
                    method: Method::DELETE,
                },
                Some(&params),
            )
            .await
    }
}

pub struct GetInvoicesBuilder<'a> {
    client: &'a CryptoBot,
    params: GetInvoicesParams,
}

impl<'a> GetInvoicesBuilder<'a> {
    pub fn new(client: &'a CryptoBot) -> Self {
        Self {
            client,
            params: GetInvoicesParams::default(),
        }
    }

    /// Set the asset for the invoices.
    /// Optional. Defaults to all currencies.
    pub fn asset(mut self, asset: CryptoCurrencyCode) -> Self {
        self.params.asset = Some(asset);
        self
    }

    /// Set the fiat for the invoices.
    /// Optional. Defaults to all currencies.
    pub fn fiat(mut self, fiat: FiatCurrencyCode) -> Self {
        self.params.fiat = Some(fiat);
        self
    }

    /// Set the invoice IDs for the invoices.
    pub fn invoice_ids(mut self, invoice_ids: Vec<u64>) -> Self {
        self.params.invoice_ids = Some(invoice_ids);
        self
    }

    /// Set the status for the invoices.
    /// Optional. Defaults to all statuses.
    pub fn status(mut self, status: InvoiceStatus) -> Self {
        self.params.status = Some(status);
        self
    }

    /// Set the offset for the invoices.
    /// Optional. Offset needed to return a specific subset of invoices.
    /// Defaults to 0.
    pub fn offset(mut self, offset: u32) -> Self {
        self.params.offset = Some(offset);
        self
    }

    /// Set the count for the invoices.
    /// Optional. Number of invoices to be returned. Values between 1-1000 are accepted.
    /// Defaults to 100.
    pub fn count(mut self, count: u16) -> Self {
        self.params.count = Some(count);
        self
    }

    /// Executes the request to get invoices
    pub async fn execute(self) -> CryptoBotResult<Vec<Invoice>> {
        if let Some(count) = self.params.count {
            validate_count(count)?;
        }

        let response: GetInvoicesResponse = self
            .client
            .make_request(
                &APIMethod {
                    endpoint: APIEndpoint::GetInvoices,
                    method: Method::GET,
                },
                Some(&self.params),
            )
            .await?;

        Ok(response.items)
    }
}

pub struct CreateInvoiceBuilder<'a, A = Missing, C = Missing, P = Missing, U = Missing> {
    client: &'a CryptoBot,
    currency_type: Option<CurrencyType>,
    asset: Option<CryptoCurrencyCode>,
    fiat: Option<FiatCurrencyCode>,
    accept_asset: Option<Vec<CryptoCurrencyCode>>,
    amount: Decimal,
    description: Option<String>,
    hidden_message: Option<String>,
    paid_btn_name: Option<PayButtonName>,
    paid_btn_url: Option<String>,
    swap_to: Option<SwapToAssets>,
    payload: Option<String>,
    allow_comments: Option<bool>,
    allow_anonymous: Option<bool>,
    expires_in: Option<u32>,
    _state: PhantomData<(A, C, P, U)>,
}

impl<'a> CreateInvoiceBuilder<'a, Missing, Missing, Missing, Missing> {
    pub fn new(client: &'a CryptoBot) -> Self {
        Self {
            client,
            currency_type: Some(CurrencyType::Crypto),
            asset: None,
            fiat: None,
            accept_asset: None,
            amount: Decimal::ZERO,
            description: None,
            hidden_message: None,
            paid_btn_name: None,
            paid_btn_url: None,
            swap_to: None,
            payload: None,
            allow_comments: None,
            allow_anonymous: None,
            expires_in: None,
            _state: PhantomData,
        }
    }
}

impl<'a, C, P, U> CreateInvoiceBuilder<'a, Missing, C, P, U> {
    /// Set the amount for the invoice.
    pub fn amount(mut self, amount: impl IntoDecimal) -> CreateInvoiceBuilder<'a, Set, C, P, U> {
        self.amount = amount.into_decimal();
        self.transform()
    }
}

impl<'a, A, P, U> CreateInvoiceBuilder<'a, A, Missing, P, U> {
    /// Set the asset for the invoice, if the currency type is crypto.
    pub fn asset(mut self, asset: CryptoCurrencyCode) -> CreateInvoiceBuilder<'a, A, Set, P, U> {
        self.currency_type = Some(CurrencyType::Crypto);
        self.asset = Some(asset);
        self.transform()
    }

    /// Set the fiat for the invoice, if the currency type is fiat.
    pub fn fiat(mut self, fiat: FiatCurrencyCode) -> CreateInvoiceBuilder<'a, A, Set, P, U> {
        self.currency_type = Some(CurrencyType::Fiat);
        self.fiat = Some(fiat);
        self.transform()
    }
}

impl<'a, A, C, U> CreateInvoiceBuilder<'a, A, C, Missing, U> {
    /// Set the paid button name for the invoice.
    pub fn paid_btn_name(mut self, paid_btn_name: PayButtonName) -> CreateInvoiceBuilder<'a, A, C, Set, U> {
        self.paid_btn_name = Some(paid_btn_name);
        self.transform()
    }
}

impl<'a, A, C> CreateInvoiceBuilder<'a, A, C, Set, Missing> {
    /// Set the paid button URL for the invoice.
    pub fn paid_btn_url(mut self, paid_btn_url: impl Into<String>) -> CreateInvoiceBuilder<'a, A, C, Set, Set> {
        self.paid_btn_url = Some(paid_btn_url.into());
        self.transform()
    }
}

impl<'a, A, C, P, U> CreateInvoiceBuilder<'a, A, C, P, U> {
    /// Set the accepted assets for the invoice.
    pub fn accept_asset(mut self, accept_asset: Vec<CryptoCurrencyCode>) -> Self {
        self.accept_asset = Some(accept_asset);
        self
    }

    /// Set the description for the invoice.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Set the hidden message for the invoice.
    pub fn hidden_message(mut self, hidden_message: impl Into<String>) -> Self {
        self.hidden_message = Some(hidden_message.into());
        self
    }

    /// Set the payload for the invoice.
    pub fn payload(mut self, payload: impl Into<String>) -> Self {
        self.payload = Some(payload.into());
        self
    }

    /// Set the allow comments for the invoice.
    pub fn allow_comments(mut self, allow_comments: bool) -> Self {
        self.allow_comments = Some(allow_comments);
        self
    }

    /// Set the allow anonymous for the invoice.
    pub fn allow_anonymous(mut self, allow_anonymous: bool) -> Self {
        self.allow_anonymous = Some(allow_anonymous);
        self
    }

    /// Set the expiration time for the invoice.
    pub fn expires_in(mut self, expires_in: u32) -> Self {
        self.expires_in = Some(expires_in);
        self
    }

    fn transform<A2, C2, P2, U2>(self) -> CreateInvoiceBuilder<'a, A2, C2, P2, U2> {
        CreateInvoiceBuilder {
            client: self.client,
            currency_type: self.currency_type,
            asset: self.asset,
            fiat: self.fiat,
            accept_asset: self.accept_asset,
            amount: self.amount,
            description: self.description,
            hidden_message: self.hidden_message,
            paid_btn_name: self.paid_btn_name,
            paid_btn_url: self.paid_btn_url,
            swap_to: self.swap_to,
            payload: self.payload,
            allow_comments: self.allow_comments,
            allow_anonymous: self.allow_anonymous,
            expires_in: self.expires_in,
            _state: PhantomData,
        }
    }
}

impl<'a, A, C, P, U> FieldValidate for CreateInvoiceBuilder<'a, A, C, P, U> {
    fn validate(&self) -> CryptoBotResult<()> {
        if self.amount <= Decimal::ZERO {
            return Err(CryptoBotError::ValidationError {
                kind: ValidationErrorKind::Range,
                message: "Amount must be greater than 0".to_string(),
                field: Some("amount".to_string()),
            });
        }

        if let Some(desc) = &self.description {
            if desc.chars().count() > 1024 {
                return Err(CryptoBotError::ValidationError {
                    kind: ValidationErrorKind::Range,
                    message: "description too long".to_string(),
                    field: Some("description".to_string()),
                });
            }
        }

        if let Some(msg) = &self.hidden_message {
            if msg.chars().count() > 2048 {
                return Err(CryptoBotError::ValidationError {
                    kind: ValidationErrorKind::Range,
                    message: "hidden_message_too_long".to_string(),
                    field: Some("hidden_message".to_string()),
                });
            }
        }

        if let Some(payload) = &self.payload {
            if payload.chars().count() > 4096 {
                return Err(CryptoBotError::ValidationError {
                    kind: ValidationErrorKind::Range,
                    message: "payload_too_long".to_string(),
                    field: Some("payload".to_string()),
                });
            }
        }

        if let Some(expires_in) = &self.expires_in {
            if !(1..=2_678_400u32).contains(expires_in) {
                return Err(CryptoBotError::ValidationError {
                    kind: ValidationErrorKind::Range,
                    message: "expires_in_invalid".to_string(),
                    field: Some("expires_in".to_string()),
                });
            }
        }
        Ok(())
    }
}

#[async_trait]
impl<'a, C: Sync, P: Sync, U: Sync> ContextValidate for CreateInvoiceBuilder<'a, Set, C, P, U> {
    async fn validate_with_context(&self, ctx: &ValidationContext) -> CryptoBotResult<()> {
        if let Some(asset) = &self.asset {
            validate_amount(&self.amount, asset, ctx).await?;
        }
        Ok(())
    }
}

impl<'a> CreateInvoiceBuilder<'a, Set, Set, Missing, Missing> {
    /// Executes the request to create the invoice
    pub async fn execute(self) -> CryptoBotResult<Invoice> {
        self.validate()?;

        let exchange_rates = self.client.get_exchange_rates().execute().await?;
        let ctx = ValidationContext { exchange_rates };
        self.validate_with_context(&ctx).await?;

        let params = CreateInvoiceParams {
            currency_type: self.currency_type,
            asset: self.asset,
            fiat: self.fiat,
            accept_asset: self.accept_asset,
            amount: self.amount,
            description: self.description,
            hidden_message: self.hidden_message,
            paid_btn_name: self.paid_btn_name,
            paid_btn_url: self.paid_btn_url,
            swap_to: self.swap_to,
            payload: self.payload,
            allow_comments: self.allow_comments,
            allow_anonymous: self.allow_anonymous,
            expires_in: self.expires_in,
        };
        self.client
            .make_request(
                &APIMethod {
                    endpoint: APIEndpoint::CreateInvoice,
                    method: Method::POST,
                },
                Some(&params),
            )
            .await
    }
}

impl<'a> CreateInvoiceBuilder<'a, Set, Set, Set, Set> {
    /// Executes the request to create the invoice
    pub async fn execute(self) -> CryptoBotResult<Invoice> {
        self.validate()?;

        if let Some(url) = &self.paid_btn_url {
            if !url.starts_with("https://") && !url.starts_with("http://") {
                return Err(CryptoBotError::ValidationError {
                    kind: ValidationErrorKind::Format,
                    message: "paid_btn_url_invalid".to_string(),
                    field: Some("paid_btn_url".to_string()),
                });
            }
        }

        let exchange_rates = self.client.get_exchange_rates().execute().await?;
        let ctx = ValidationContext { exchange_rates };
        self.validate_with_context(&ctx).await?;

        let params = CreateInvoiceParams {
            currency_type: self.currency_type,
            asset: self.asset,
            fiat: self.fiat,
            accept_asset: self.accept_asset,
            amount: self.amount,
            description: self.description,
            hidden_message: self.hidden_message,
            paid_btn_name: self.paid_btn_name,
            paid_btn_url: self.paid_btn_url,
            swap_to: self.swap_to,
            payload: self.payload,
            allow_comments: self.allow_comments,
            allow_anonymous: self.allow_anonymous,
            expires_in: self.expires_in,
        };

        self.client
            .make_request(
                &APIMethod {
                    endpoint: APIEndpoint::CreateInvoice,
                    method: Method::POST,
                },
                Some(&params),
            )
            .await
    }
}

#[async_trait]
impl InvoiceAPI for CryptoBot {
    /// Creates a new cryptocurrency invoice
    ///
    /// An invoice is a request for cryptocurrency payment with a specific amount
    /// and currency. Once created, the invoice can be paid by any user.
    ///
    /// # Returns
    /// * `CreateInvoiceBuilder` - A builder to construct the invoice parameters
    fn create_invoice(&self) -> CreateInvoiceBuilder<'_> {
        CreateInvoiceBuilder::new(self)
    }

    fn delete_invoice(&self, invoice_id: u64) -> DeleteInvoiceBuilder<'_> {
        DeleteInvoiceBuilder::new(self, invoice_id)
    }

    /// Gets a list of invoices with optional filtering
    ///
    /// Retrieves all invoices matching the specified filter parameters.
    /// If no parameters are provided, returns all invoices.
    ///
    /// # Returns
    /// * `GetInvoicesBuilder` - A builder to construct the filter parameters
    fn get_invoices(&self) -> GetInvoicesBuilder<'_> {
        GetInvoicesBuilder::new(self)
    }
}

#[cfg(test)]
mod tests {
    use futures::executor::block_on;
    use mockito::{Matcher, Mock};
    use rust_decimal_macros::dec;
    use serde_json::json;

    use super::*;
    use crate::models::{CryptoCurrencyCode, PayButtonName, SwapToAssets};
    use crate::utils::test_utils::TestContext;

    impl TestContext {
        pub fn mock_create_invoice_response(&mut self) -> Mock {
            self.server
                .mock("POST", "/createInvoice")
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(
                    json!({
                        "ok": true,
                        "result": {
                            "invoice_id": 528890,
                            "hash": "IVDoTcNBYEfk",
                            "currency_type": "crypto",
                            "asset": "TON",
                            "amount": "10.5",
                            "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                            "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                            "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                            "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                            "description": "Test invoice",
                            "status": "active",
                            "created_at": "2025-02-08T12:11:01.341Z",
                            "allow_comments": true,
                            "allow_anonymous": true
                        }
                    })
                    .to_string(),
                )
                .create()
        }

        pub fn mock_get_invoices_response(&mut self) -> Mock {
            self.server
                .mock("GET", "/getInvoices")
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(json!({
                    "ok": true,
                    "result": {
                        "items": [
                            {
                                "invoice_id": 528890,
                                "hash": "IVDoTcNBYEfk",
                                "currency_type": "crypto",
                                "asset": "TON",
                                "amount": "10.5",
                                "pay_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVDoTcNBYEfk",
                                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVDoTcNBYEfk",
                                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVDoTcNBYEfk",
                                "description": "Test invoice",
                                "status": "active",
                                "created_at": "2025-02-08T12:11:01.341Z",
                                "allow_comments": true,
                                "allow_anonymous": true
                            },
                        ]
                    }
                })
                .to_string(),
            )
            .create()
        }

        pub fn mock_get_invoices_response_with_invoice_ids(&mut self) -> Mock {
            self.server
                .mock("GET", "/getInvoices")
                .match_body(json!({ "invoice_ids": "530195"}).to_string().as_str())
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(json!({
                    "ok": true,
                    "result": {
                        "items": [
                            {
                                "invoice_id": 530195,
                                "hash": "IVcKhSGh244v",
                                "currency_type": "crypto",
                                "asset": "BTC",
                                "amount": "0.5",
                                "pay_url": "https://t.me/CryptoTestnetBot?start=IVcKhSGh244v",
                                "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=IVcKhSGh244v",
                                "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-IVcKhSGh244v",
                                "web_app_invoice_url": "https://testnet-app.send.tg/invoices/IVcKhSGh244v",
                                "status": "active",
                                "created_at": "2025-02-09T03:46:07.811Z",
                                "allow_comments": true,
                                "allow_anonymous": true
                            }
                        ]
                    }
                })
                .to_string(),
            )
            .create()
        }

        pub fn mock_delete_invoice_response(&mut self) -> Mock {
            self.server
                .mock("DELETE", "/deleteInvoice")
                .match_body(Matcher::JsonString(
                    json!({
                        "invoice_id": 528890
                    })
                    .to_string(),
                ))
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(
                    json!({
                        "ok": true,
                        "result": true
                    })
                    .to_string(),
                )
                .create()
        }

        pub fn mock_create_invoice_with_accept_asset_response(&mut self) -> Mock {
            self.server
                .mock("POST", "/createInvoice")
                .match_body(Matcher::JsonString(
                    json!({
                        "currency_type": "crypto",
                        "asset": "TON",
                        "amount": "2",
                        "accept_asset": ["TON", "USDT"],
                        "payload": "payload",
                        "hidden_message": "Hidden",
                        "allow_comments": false,
                        "allow_anonymous": true,
                        "expires_in": 120
                    })
                    .to_string(),
                ))
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(
                    json!({
                        "ok": true,
                        "result": {
                            "invoice_id": 42,
                            "hash": "hash",
                            "currency_type": "crypto",
                            "asset": "TON",
                            "amount": "2",
                            "pay_url": "https://t.me/CryptoTestnetBot?start=hash",
                            "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=hash",
                            "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-hash",
                            "web_app_invoice_url": "https://testnet-app.send.tg/invoices/hash",
                            "status": "active",
                            "created_at": "2025-02-08T12:11:01.341Z",
                            "allow_comments": false,
                            "allow_anonymous": true
                        }
                    })
                    .to_string(),
                )
                .create()
        }

        pub fn mock_get_invoices_response_with_filters(&mut self) -> Mock {
            self.server
                .mock("GET", "/getInvoices")
                .match_body(Matcher::JsonString(
                    json!({
                        "asset": "TON",
                        "fiat": "USD",
                        "invoice_ids": "1,2",
                        "status": "paid",
                        "offset": 3,
                        "count": 4
                    })
                    .to_string(),
                ))
                .with_header("content-type", "application/json")
                .with_header("Crypto-Pay-API-Token", "test_token")
                .with_body(
                    json!({
                        "ok": true,
                        "result": {
                            "items": [
                                {
                                    "invoice_id": 1,
                                    "hash": "hash",
                                    "currency_type": "crypto",
                                    "asset": "TON",
                                    "amount": "1",
                                    "pay_url": "https://t.me/CryptoTestnetBot?start=hash",
                                    "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=hash",
                                    "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-hash",
                                    "web_app_invoice_url": "https://testnet-app.send.tg/invoices/hash",
                                    "status": "paid",
                                    "created_at": "2025-02-08T12:11:01.341Z",
                                    "allow_comments": true,
                                    "allow_anonymous": true
                                }
                            ]
                        }
                    })
                    .to_string(),
                )
                .create()
        }
    }

    #[test]
    fn test_create_invoice() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_exchange_rates_response();
        let _m = ctx.mock_create_invoice_response();

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

        let result = ctx.run(async {
            client
                .create_invoice()
                .asset(CryptoCurrencyCode::Ton)
                .amount(dec!(10.5))
                .description("Test invoice".to_string())
                .expires_in(3600)
                .execute()
                .await
        });

        println!("result: {:?}", result);
        assert!(result.is_ok());

        let invoice = result.unwrap();
        assert_eq!(invoice.amount, dec!(10.5));
        assert_eq!(invoice.asset, Some(CryptoCurrencyCode::Ton));
        assert_eq!(invoice.description, Some("Test invoice".to_string()));
    }

    #[test]
    fn test_get_invoices_without_params() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_get_invoices_response();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();
        let result = ctx.run(async { client.get_invoices().execute().await });

        println!("result:{:?}", result);

        assert!(result.is_ok());

        let invoices = result.unwrap();
        assert!(!invoices.is_empty());
        assert_eq!(invoices.len(), 1);
    }

    #[test]
    fn test_get_invoices_with_params() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_get_invoices_response_with_invoice_ids();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_invoices().invoice_ids(vec![530195]).execute().await });

        println!("result: {:?}", result);

        assert!(result.is_ok());

        let invoices = result.unwrap();
        assert!(!invoices.is_empty());
        assert_eq!(invoices.len(), 1);
        assert_eq!(invoices[0].invoice_id, 530195);
    }

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

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

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

        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_get_invoices_with_all_params() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_get_invoices_response();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async {
            client
                .get_invoices()
                .asset(CryptoCurrencyCode::Ton)
                .fiat(FiatCurrencyCode::Usd)
                .status(InvoiceStatus::Paid)
                .offset(10)
                .count(50)
                .execute()
                .await
        });

        assert!(result.is_ok());
    }

    #[test]
    fn test_get_invoices_invalid_count() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async { client.get_invoices().count(0).execute().await });

        assert!(result.is_err());
        match result {
            Err(CryptoBotError::ValidationError { kind, .. }) => {
                assert_eq!(kind, ValidationErrorKind::Range);
            }
            _ => panic!("Expected ValidationError"),
        }
    }

    #[test]
    fn test_create_invoice_with_all_optional_params() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_exchange_rates_response();
        let _m = ctx.mock_create_invoice_response();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async {
            client
                .create_invoice()
                .asset(CryptoCurrencyCode::Ton)
                .amount(dec!(10.5))
                .description("Test".to_string())
                .hidden_message("Hidden".to_string())
                .paid_btn_name(PayButtonName::ViewItem)
                .paid_btn_url("https://example.com".to_string())
                .payload("payload".to_string())
                .allow_comments(true)
                .allow_anonymous(false)
                .expires_in(3600)
                .execute()
                .await
        });

        assert!(result.is_ok());
    }

    #[test]
    fn test_swap_to_assets_serialization() {
        let serialized = serde_json::to_string(&SwapToAssets::Ton).unwrap();
        assert_eq!(serialized, "\"TON\"");

        let deserialized: SwapToAssets = serde_json::from_str("\"USDT\"").unwrap();
        assert_eq!(deserialized, SwapToAssets::Usdt);
    }

    #[test]
    fn test_invoice_swap_fields_serialization() {
        let invoice: Invoice = serde_json::from_value(json!({
            "invoice_id": 123,
            "hash": "hash-value",
            "currency_type": "crypto",
            "asset": "TON",
            "amount": "10.00",
            "bot_invoice_url": "https://t.me/CryptoTestnetBot?start=hash-value",
            "mini_app_invoice_url": "https://t.me/CryptoTestnetBot/app?startapp=invoice-hash-value",
            "web_app_invoice_url": "https://testnet-app.send.tg/invoices/hash-value",
            "status": "paid",
            "allow_comments": true,
            "allow_anonymous": false,
            "created_at": "2025-02-08T12:11:01.341Z",
            "swap_to": "USDT",
            "is_swapped": "true",
            "swapped_uid": "swap-uid",
            "swapped_to": "USDT",
            "swapped_rate": "1.50",
            "swapped_output": "100.00",
            "swapped_usd_amount": "1500.00",
            "swapped_usd_rate": "1.50"
        }))
        .unwrap();

        assert_eq!(invoice.swapped_usd_amount, Some(dec!(1500.00))); // 1500.00
        assert_eq!(invoice.swapped_usd_rate, Some(dec!(1.50))); // 1.50
        assert_eq!(invoice.swap_to, Some(SwapToAssets::Usdt));
        assert_eq!(invoice.swapped_to, Some(SwapToAssets::Usdt));
    }

    #[test]
    fn test_create_invoice_rejects_negative_amount() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let builder = client.create_invoice().asset(CryptoCurrencyCode::Ton).amount(dec!(-1));

        let result = builder.validate();
        assert!(result.is_err());
        match result {
            Err(CryptoBotError::ValidationError { field, .. }) => assert_eq!(field, Some("amount".to_string())),
            _ => panic!("Expected validation error for negative amount"),
        }
    }

    #[test]
    fn test_create_invoice_rejects_description_too_long() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let long_description = "a".repeat(1_025);
        let builder = client
            .create_invoice()
            .asset(CryptoCurrencyCode::Ton)
            .amount(dec!(1))
            .description(long_description);

        let result = builder.validate();
        assert!(result.is_err());
        match result {
            Err(CryptoBotError::ValidationError { field, .. }) => {
                assert_eq!(field, Some("description".to_string()))
            }
            _ => panic!("Expected validation error for long description"),
        }
    }

    #[test]
    fn test_create_invoice_invalid_paid_button_url() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let result = ctx.run(async {
            client
                .create_invoice()
                .asset(CryptoCurrencyCode::Ton)
                .amount(dec!(5))
                .paid_btn_name(PayButtonName::ViewItem)
                .paid_btn_url("ftp://example.com")
                .execute()
                .await
        });

        assert!(result.is_err());
        match result {
            Err(CryptoBotError::ValidationError { field, .. }) => assert_eq!(field, Some("paid_btn_url".to_string())),
            _ => panic!("Expected validation error for invalid paid_btn_url"),
        }
    }

    #[test]
    fn test_create_invoice_rejects_hidden_message_too_long() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let message = "a".repeat(2_049);
        let builder = client
            .create_invoice()
            .asset(CryptoCurrencyCode::Ton)
            .amount(dec!(1))
            .hidden_message(message);

        let result = builder.validate();
        assert!(matches!(
            result,
            Err(CryptoBotError::ValidationError {
                field,
                kind: ValidationErrorKind::Range,
                ..
            }) if field == Some("hidden_message".to_string())
        ));
    }

    #[test]
    fn test_create_invoice_rejects_payload_too_long() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let payload = "a".repeat(4_097);
        let builder = client
            .create_invoice()
            .asset(CryptoCurrencyCode::Ton)
            .amount(dec!(1))
            .payload(payload);

        let result = builder.validate();
        assert!(matches!(
            result,
            Err(CryptoBotError::ValidationError {
                field,
                kind: ValidationErrorKind::Range,
                ..
            }) if field == Some("payload".to_string())
        ));
    }

    #[test]
    fn test_create_invoice_rejects_invalid_expires_in() {
        let ctx = TestContext::new();
        let client = CryptoBot::builder()
            .api_token("test_token")
            .base_url(ctx.server.url())
            .build()
            .unwrap();

        let builder = client
            .create_invoice()
            .asset(CryptoCurrencyCode::Ton)
            .amount(dec!(1))
            .expires_in(0);

        let result = builder.validate();
        assert!(matches!(
            result,
            Err(CryptoBotError::ValidationError {
                field,
                kind: ValidationErrorKind::Range,
                ..
            }) if field == Some("expires_in".to_string())
        ));
    }

    #[test]
    fn test_create_invoice_with_accept_asset_and_flags() {
        let mut ctx = TestContext::new();
        let _m = ctx.mock_exchange_rates_response();
        let _m = ctx.mock_create_invoice_with_accept_asset_response();

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

        let result = ctx.run(async {
            client
                .create_invoice()
                .asset(CryptoCurrencyCode::Ton)
                .amount(dec!(2))
                .accept_asset(vec![CryptoCurrencyCode::Ton, CryptoCurrencyCode::Usdt])
                .payload("payload")
                .hidden_message("Hidden")
                .allow_comments(false)
                .allow_anonymous(true)
                .expires_in(120)
                .execute()
                .await
        });

        assert!(result.is_ok());
        let invoice = result.unwrap();
        assert_eq!(invoice.invoice_id, 42);
        assert!(!invoice.allow_comments);
    }

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

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

        let result = ctx.run(async {
            client
                .get_invoices()
                .asset(CryptoCurrencyCode::Ton)
                .fiat(FiatCurrencyCode::Usd)
                .invoice_ids(vec![1, 2])
                .status(InvoiceStatus::Paid)
                .offset(3)
                .count(4)
                .execute()
                .await
        });

        assert!(result.is_ok());
        let invoices = result.unwrap();
        assert_eq!(invoices.len(), 1);
        assert_eq!(invoices[0].invoice_id, 1);
    }

    #[test]
    fn test_invoice_validate_with_context_crypto_amount() {
        let client = CryptoBot::test_client();
        let builder = client.create_invoice().asset(CryptoCurrencyCode::Ton).amount(dec!(5));
        let ctx = ValidationContext {
            exchange_rates: crate::utils::test_utils::TestContext::mock_exchange_rates(),
        };

        let result = block_on(async { builder.validate_with_context(&ctx).await });
        assert!(result.is_ok());
    }

    #[test]
    fn test_invoice_validate_with_context_fiat_skips_amount_check() {
        let client = CryptoBot::test_client();
        let builder = client.create_invoice().fiat(FiatCurrencyCode::Usd).amount(dec!(5));
        let ctx = ValidationContext {
            exchange_rates: crate::utils::test_utils::TestContext::mock_exchange_rates(),
        };

        let result = block_on(async { builder.validate_with_context(&ctx).await });
        assert!(result.is_ok());
    }
}