hiero-sdk 0.44.1

The SDK for interacting with Hedera Hashgraph.
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
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
// SPDX-License-Identifier: Apache-2.0

use std::collections::HashMap;
use std::ops::Not;

use hiero_sdk_proto::services;
use hiero_sdk_proto::services::crypto_service_client::CryptoServiceClient;
use tonic::transport::Channel;

use crate::hooks::{
    FungibleHookCall,
    FungibleHookType,
    NftHookCall,
    NftHookType,
};
use crate::ledger_id::RefLedgerId;
use crate::protobuf::FromProtobuf;
use crate::transaction::{
    AnyTransactionData,
    ChunkInfo,
    ToSchedulableTransactionDataProtobuf,
    ToTransactionDataProtobuf,
    TransactionData,
    TransactionExecute,
};
use crate::{
    AccountId,
    BoxGrpcFuture,
    Error,
    Hbar,
    NftId,
    ToProtobuf,
    TokenId,
    TokenNftTransfer,
    Transaction,
    ValidateChecksums,
};

/// Transfers cryptocurrency among two or more accounts by making the desired adjustments to their
/// balances.
///
/// Each transfer list can specify up to 10 adjustments. Each negative amount is withdrawn
/// from the corresponding account (a sender), and each positive one is added to the corresponding
/// account (a receiver). The amounts list must sum to zero.
///
/// All transfers are in the lowest denomination, for `Hbar` that is tinybars (although `Hbar` handles this itself).
///
/// As an example: for a fungible token with `3` decimals (and let's say the symbol is `Æ’`), transferring `1` _always_ transfers `0.001 Æ’`.
pub type TransferTransaction = Transaction<TransferTransactionData>;

#[derive(Debug, Clone, Default)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct TransferTransactionData {
    transfers: Vec<Transfer>,
    token_transfers: Vec<TokenTransfer>,
}

#[derive(Debug, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub(crate) struct Transfer {
    /// The account involved in the transfer.
    pub account_id: AccountId,

    /// The value of the transfer.
    pub amount: i64,

    /// If this is an approved transfer.
    pub is_approval: bool,

    /// Optional fungible hook call for this transfer.
    pub hook_call: Option<FungibleHookCall>,
}

#[derive(Debug, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub(crate) struct TokenTransfer {
    pub token_id: TokenId,

    pub transfers: Vec<Transfer>,

    pub nft_transfers: Vec<TokenNftTransfer>,

    pub expected_decimals: Option<u32>,
}

impl TransferTransaction {
    fn _hbar_transfer(
        &mut self,
        account_id: AccountId,
        amount: Hbar,
        approved: bool,
        hook_call: Option<FungibleHookCall>,
    ) -> &mut Self {
        self.data_mut().transfers.push(Transfer {
            account_id,
            amount: amount.to_tinybars(),
            is_approval: approved,
            hook_call,
        });

        self
    }

    /// Add a non-approved hbar transfer to the transaction.
    pub fn hbar_transfer(&mut self, account_id: AccountId, amount: Hbar) -> &mut Self {
        self._hbar_transfer(account_id, amount, false, None)
    }

    /// Add an approved hbar transfer to the transaction.
    pub fn approved_hbar_transfer(&mut self, account_id: AccountId, amount: Hbar) -> &mut Self {
        self._hbar_transfer(account_id, amount, true, None)
    }

    /// Returns all transfers associated with this transaction.
    pub fn get_hbar_transfers(&self) -> HashMap<AccountId, Hbar> {
        self.data()
            .transfers
            .iter()
            .map(|it| (it.account_id, Hbar::from_tinybars(it.amount)))
            .collect()
    }

    fn _token_transfer(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
        approved: bool,
        expected_decimals: Option<u32>,
        hook_call: Option<FungibleHookCall>,
    ) -> &mut Self {
        let transfer = Transfer { account_id, amount, is_approval: approved, hook_call };
        let data = self.data_mut();

        // First, try to find an existing TokenTransfer with matching token_id
        if let Some(tt) = data.token_transfers.iter_mut().find(|tt| tt.token_id == token_id) {
            // Within that TokenTransfer, look for a transfer with matching account_id and is_approval
            if let Some(existing_transfer) = tt
                .transfers
                .iter_mut()
                .find(|t| t.account_id == account_id && t.is_approval == approved)
            {
                // Found matching transfer - add to the existing amount
                existing_transfer.amount += amount;
                tt.expected_decimals = expected_decimals;
            } else {
                // Found TokenTransfer but no matching account - push new transfer
                tt.transfers.push(transfer.clone());
                tt.expected_decimals = expected_decimals;
            }
        } else {
            // No TokenTransfer found for this token_id - create a new one
            data.token_transfers.push(TokenTransfer {
                token_id,
                expected_decimals,
                nft_transfers: Vec::new(),
                transfers: vec![transfer],
            });
        }

        self
    }

    /// Add a non-approved token transfer to the transaction.
    ///
    /// `amount` is in the lowest denomination for the token (if the token has `2` decimals this would be `0.01` tokens).
    pub fn token_transfer(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
    ) -> &mut Self {
        self._token_transfer(token_id, account_id, amount, false, None, None)
    }

    /// Add an approved token transfer to the transaction.
    ///
    /// `amount` is in the lowest denomination for the token (if the token has `2` decimals this would be `0.01` tokens).
    pub fn approved_token_transfer(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
    ) -> &mut Self {
        self._token_transfer(token_id, account_id, amount, true, None, None)
    }

    // todo: make the examples into code, just not sure how to do that.
    /// Add a non-approved token transfer to the transaction, ensuring that the token has `expected_decimals` decimals.
    ///
    /// `amount` is _still_ in the lowest denomination, however,
    /// you will get an error if the token has a different amount of decimals than `expected_decimals`.
    pub fn token_transfer_with_decimals(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
        expected_decimals: u32,
    ) -> &mut Self {
        self._token_transfer(token_id, account_id, amount, false, Some(expected_decimals), None)
    }

    /// Add an approved token transfer, ensuring that the token has `expected_decimals` decimals.
    ///
    /// `amount` is _still_ in the lowest denomination, however,
    /// you will get an error if the token has a different amount of decimals than `expected_decimals`.
    pub fn approved_token_transfer_with_decimals(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
        expected_decimals: u32,
    ) -> &mut Self {
        self._token_transfer(token_id, account_id, amount, true, Some(expected_decimals), None)
    }

    /// Returns all the token transfers associated associated with this transaction.
    pub fn get_token_transfers(&self) -> HashMap<TokenId, HashMap<AccountId, i64>> {
        use std::collections::hash_map::Entry;

        // note: using fold instead of nested collects on the off chance a token is in here twice.
        self.data().token_transfers.iter().fold(
            HashMap::with_capacity(self.data().token_transfers.len()),
            |mut map, transfer| {
                let iter = transfer.transfers.iter().map(|it| (it.account_id, it.amount));
                match map.entry(transfer.token_id) {
                    Entry::Occupied(mut it) => it.get_mut().extend(iter),
                    Entry::Vacant(it) => {
                        it.insert(iter.collect());
                    }
                }

                map
            },
        )
    }

    /// Returns the decimals associated with each token.
    pub fn get_token_decimals(&self) -> HashMap<TokenId, u32> {
        self.data()
            .token_transfers
            .iter()
            .filter_map(|it| it.expected_decimals.map(|decimals| (it.token_id, decimals)))
            .collect()
    }

    fn _nft_transfer(
        &mut self,
        nft_id: NftId,
        sender_account_id: AccountId,
        receiver_account_id: AccountId,
        approved: bool,
        sender_hook_call: Option<NftHookCall>,
        receiver_hook_call: Option<NftHookCall>,
    ) -> &mut Self {
        let NftId { token_id, serial } = nft_id;
        let transfer = TokenNftTransfer {
            token_id,
            serial,
            sender: sender_account_id,
            receiver: receiver_account_id,
            is_approved: approved,
            sender_hook_call,
            receiver_hook_call,
        };

        let data = self.data_mut();

        if let Some(tt) = data.token_transfers.iter_mut().find(|tt| tt.token_id == token_id) {
            tt.nft_transfers.push(transfer);
        } else {
            data.token_transfers.push(TokenTransfer {
                token_id,
                expected_decimals: None,
                transfers: Vec::new(),
                nft_transfers: vec![transfer],
            });
        }

        self
    }

    /// Add an approved nft transfer to the transaction.
    pub fn approved_nft_transfer(
        &mut self,
        nft_id: impl Into<NftId>,
        sender_account_id: AccountId,
        receiver_account_id: AccountId,
    ) -> &mut Self {
        self._nft_transfer(nft_id.into(), sender_account_id, receiver_account_id, true, None, None)
    }

    /// Add a non-approved nft transfer to the transaction.
    pub fn nft_transfer(
        &mut self,
        nft_id: impl Into<NftId>,
        sender_account_id: AccountId,
        receiver_account_id: AccountId,
    ) -> &mut Self {
        self._nft_transfer(nft_id.into(), sender_account_id, receiver_account_id, false, None, None)
    }

    /// Returns all the NFT transfers associated with this transaction.
    pub fn get_nft_transfers(&self) -> HashMap<TokenId, Vec<TokenNftTransfer>> {
        self.data()
            .token_transfers
            .iter()
            .map(|it| (it.token_id, it.nft_transfers.clone()))
            .collect()
    }

    /// Add a hbar transfer with a fungible hook call.
    pub fn add_hbar_transfer_with_hook(
        &mut self,
        account_id: AccountId,
        amount: Hbar,
        hook_call: FungibleHookCall,
    ) -> &mut Self {
        self._hbar_transfer(account_id, amount, false, Some(hook_call))
    }

    /// Add a token transfer with a fungible hook call.
    pub fn add_token_transfer_with_hook(
        &mut self,
        token_id: TokenId,
        account_id: AccountId,
        amount: i64,
        hook_call: FungibleHookCall,
    ) -> &mut Self {
        self._token_transfer(token_id, account_id, amount, false, None, Some(hook_call))
    }

    /// Add an NFT transfer with optional sender and/or receiver hook calls.
    pub fn add_nft_transfer_with_hook(
        &mut self,
        nft_id: impl Into<NftId>,
        sender: AccountId,
        receiver: AccountId,
        sender_hook_call: Option<NftHookCall>,
        receiver_hook_call: Option<NftHookCall>,
    ) -> &mut Self {
        self._nft_transfer(
            nft_id.into(),
            sender,
            receiver,
            false,
            sender_hook_call,
            receiver_hook_call,
        )
    }
}

impl TransactionExecute for TransferTransactionData {
    // noinspection DuplicatedCode
    fn execute(
        &self,
        channel: Channel,
        request: services::Transaction,
    ) -> BoxGrpcFuture<'_, services::TransactionResponse> {
        Box::pin(async { CryptoServiceClient::new(channel).crypto_transfer(request).await })
    }
}

impl TransactionData for TransferTransactionData {}

impl ValidateChecksums for TransferTransactionData {
    fn validate_checksums(&self, ledger_id: &RefLedgerId) -> Result<(), Error> {
        for transfer in &self.transfers {
            transfer.account_id.validate_checksums(ledger_id)?;
        }
        for token_transfer in &self.token_transfers {
            token_transfer.token_id.validate_checksums(ledger_id)?;
            for transfer in &token_transfer.transfers {
                transfer.account_id.validate_checksums(ledger_id)?;
            }
            for nft_transfer in &token_transfer.nft_transfers {
                nft_transfer.sender.validate_checksums(ledger_id)?;
                nft_transfer.receiver.validate_checksums(ledger_id)?;
            }
        }
        Ok(())
    }
}

impl FromProtobuf<services::AccountAmount> for Transfer {
    fn from_protobuf(pb: services::AccountAmount) -> crate::Result<Self> {
        let hook_call = match pb.hook_call {
            Some(services::account_amount::HookCall::PreTxAllowanceHook(hook)) => {
                Some(FungibleHookCall::from_protobuf_with_type(
                    hook,
                    FungibleHookType::PreTxAllowanceHook,
                )?)
            }
            Some(services::account_amount::HookCall::PrePostTxAllowanceHook(hook)) => {
                Some(FungibleHookCall::from_protobuf_with_type(
                    hook,
                    FungibleHookType::PrePostTxAllowanceHook,
                )?)
            }
            None => None,
        };

        Ok(Self {
            account_id: AccountId::from_protobuf(pb_getf!(pb, account_id)?)?,
            amount: pb.amount,
            is_approval: pb.is_approval,
            hook_call,
        })
    }
}

impl ToProtobuf for Transfer {
    type Protobuf = services::AccountAmount;

    fn to_protobuf(&self) -> Self::Protobuf {
        let hook_call = self.hook_call.as_ref().map(|hook| match hook.hook_type {
            FungibleHookType::PreTxAllowanceHook => {
                services::account_amount::HookCall::PreTxAllowanceHook(hook.to_protobuf())
            }
            FungibleHookType::PrePostTxAllowanceHook => {
                services::account_amount::HookCall::PrePostTxAllowanceHook(hook.to_protobuf())
            }
        });

        services::AccountAmount {
            account_id: Some(self.account_id.to_protobuf()),
            amount: self.amount,
            is_approval: self.is_approval,
            hook_call,
        }
    }
}

impl FromProtobuf<services::TokenTransferList> for TokenTransfer {
    fn from_protobuf(pb: services::TokenTransferList) -> crate::Result<Self> {
        let token_id = TokenId::from_protobuf(pb_getf!(pb, token)?)?;

        Ok(Self {
            token_id,
            transfers: Vec::from_protobuf(pb.transfers)?,
            nft_transfers: pb
                .nft_transfers
                .into_iter()
                .map(|pb| TokenNftTransfer::from_protobuf(pb, token_id))
                .collect::<Result<Vec<_>, _>>()?,
            expected_decimals: pb.expected_decimals,
        })
    }
}

impl ToProtobuf for TokenTransfer {
    type Protobuf = services::TokenTransferList;

    fn to_protobuf(&self) -> Self::Protobuf {
        let transfers = self.transfers.to_protobuf();
        let nft_transfers = self.nft_transfers.to_protobuf();

        services::TokenTransferList {
            token: Some(self.token_id.to_protobuf()),
            transfers,
            nft_transfers,
            expected_decimals: self.expected_decimals,
        }
    }
}

impl ToProtobuf for TokenNftTransfer {
    type Protobuf = services::NftTransfer;

    fn to_protobuf(&self) -> Self::Protobuf {
        // Serialize sender hook call to oneof union
        let sender_allowance_hook_call = self.sender_hook_call.as_ref().map(|hook| {
            match hook.hook_type {
                NftHookType::PreHookSender => {
                    services::nft_transfer::SenderAllowanceHookCall::PreTxSenderAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
                NftHookType::PrePostHookSender => {
                    services::nft_transfer::SenderAllowanceHookCall::PrePostTxSenderAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
                _ => {
                    // This shouldn't happen as sender_hook_call should only have sender types
                    services::nft_transfer::SenderAllowanceHookCall::PreTxSenderAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
            }
        });

        // Serialize receiver hook call to oneof union
        let receiver_allowance_hook_call = self.receiver_hook_call.as_ref().map(|hook| {
            match hook.hook_type {
                NftHookType::PreHookReceiver => {
                    services::nft_transfer::ReceiverAllowanceHookCall::PreTxReceiverAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
                NftHookType::PrePostHookReceiver => {
                    services::nft_transfer::ReceiverAllowanceHookCall::PrePostTxReceiverAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
                _ => {
                    // This shouldn't happen as receiver_hook_call should only have receiver types
                    services::nft_transfer::ReceiverAllowanceHookCall::PreTxReceiverAllowanceHook(
                        hook.to_protobuf(),
                    )
                }
            }
        });

        services::NftTransfer {
            sender_account_id: Some(self.sender.to_protobuf()),
            receiver_account_id: Some(self.receiver.to_protobuf()),
            serial_number: self.serial as i64,
            is_approval: self.is_approved,
            sender_allowance_hook_call,
            receiver_allowance_hook_call,
        }
    }
}

impl ToTransactionDataProtobuf for TransferTransactionData {
    fn to_transaction_data_protobuf(
        &self,
        chunk_info: &ChunkInfo,
    ) -> services::transaction_body::Data {
        let _ = chunk_info.assert_single_transaction();

        services::transaction_body::Data::CryptoTransfer(self.to_protobuf())
    }
}

impl ToSchedulableTransactionDataProtobuf for TransferTransactionData {
    fn to_schedulable_transaction_data_protobuf(
        &self,
    ) -> services::schedulable_transaction_body::Data {
        services::schedulable_transaction_body::Data::CryptoTransfer(self.to_protobuf())
    }
}

impl From<TransferTransactionData> for AnyTransactionData {
    fn from(transaction: TransferTransactionData) -> Self {
        Self::Transfer(transaction)
    }
}

impl FromProtobuf<services::CryptoTransferTransactionBody> for TransferTransactionData {
    fn from_protobuf(pb: services::CryptoTransferTransactionBody) -> crate::Result<Self> {
        let transfers = pb.transfers.map(|it| it.account_amounts);
        let transfers = Option::from_protobuf(transfers)?.unwrap_or_default();

        Ok(Self { transfers, token_transfers: Vec::from_protobuf(pb.token_transfers)? })
    }
}

impl ToProtobuf for TransferTransactionData {
    type Protobuf = services::CryptoTransferTransactionBody;

    fn to_protobuf(&self) -> Self::Protobuf {
        let transfers = self
            .transfers
            .is_empty()
            .not()
            .then(|| services::TransferList { account_amounts: self.transfers.to_protobuf() });

        let token_transfers = self.token_transfers.to_protobuf();

        services::CryptoTransferTransactionBody { transfers, token_transfers }
    }
}

#[cfg(test)]
mod tests {
    use expect_test::expect;

    use crate::transaction::test_helpers::{
        check_body,
        transaction_body,
    };
    use crate::{
        AccountId,
        AnyTransaction,
        Hbar,
        TokenId,
        TransferTransaction,
    };

    fn make_transaction() -> TransferTransaction {
        let mut tx = TransferTransaction::new_for_tests();

        tx.hbar_transfer(AccountId::new(0, 0, 5008), Hbar::from_tinybars(400))
            .hbar_transfer(AccountId::new(0, 0, 5006), Hbar::from_tinybars(800).negated())
            .approved_hbar_transfer(AccountId::new(0, 0, 5007), Hbar::from_tinybars(400))
            .token_transfer(TokenId::new(0, 0, 5), AccountId::new(0, 0, 5008), 400)
            .token_transfer_with_decimals(
                TokenId::new(0, 0, 5),
                AccountId::new(0, 0, 5006),
                -800,
                3,
            )
            .token_transfer_with_decimals(TokenId::new(0, 0, 5), AccountId::new(0, 0, 5007), 400, 3)
            .token_transfer(TokenId::new(0, 0, 4), AccountId::new(0, 0, 5008), 1)
            .approved_token_transfer(TokenId::new(0, 0, 4), AccountId::new(0, 0, 5006), -1)
            .nft_transfer(
                TokenId::new(0, 0, 3).nft(2),
                AccountId::new(0, 0, 5008),
                AccountId::new(0, 0, 5007),
            )
            .approved_nft_transfer(
                TokenId::new(0, 0, 3).nft(1),
                AccountId::new(0, 0, 5008),
                AccountId::new(0, 0, 5007),
            )
            .nft_transfer(
                TokenId::new(0, 0, 3).nft(3),
                AccountId::new(0, 0, 5008),
                AccountId::new(0, 0, 5006),
            )
            .nft_transfer(
                TokenId::new(0, 0, 3).nft(4),
                AccountId::new(0, 0, 5007),
                AccountId::new(0, 0, 5006),
            )
            .nft_transfer(
                TokenId::new(0, 0, 2).nft(4),
                AccountId::new(0, 0, 5007),
                AccountId::new(0, 0, 5006),
            )
            .freeze()
            .unwrap();

        tx
    }

    #[test]
    fn serialize() {
        let tx = make_transaction();

        let tx = transaction_body(tx);

        let tx = check_body(tx);

        expect![[r#"
            CryptoTransfer(
                CryptoTransferTransactionBody {
                    transfers: Some(
                        TransferList {
                            account_amounts: [
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: 400,
                                    is_approval: false,
                                    hook_call: None,
                                },
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: -800,
                                    is_approval: false,
                                    hook_call: None,
                                },
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: 400,
                                    is_approval: true,
                                    hook_call: None,
                                },
                            ],
                        },
                    ),
                    token_transfers: [
                        TokenTransferList {
                            token: Some(
                                TokenId {
                                    shard_num: 0,
                                    realm_num: 0,
                                    token_num: 5,
                                },
                            ),
                            transfers: [
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: 400,
                                    is_approval: false,
                                    hook_call: None,
                                },
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: -800,
                                    is_approval: false,
                                    hook_call: None,
                                },
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: 400,
                                    is_approval: false,
                                    hook_call: None,
                                },
                            ],
                            nft_transfers: [],
                            expected_decimals: Some(
                                3,
                            ),
                        },
                        TokenTransferList {
                            token: Some(
                                TokenId {
                                    shard_num: 0,
                                    realm_num: 0,
                                    token_num: 4,
                                },
                            ),
                            transfers: [
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: 1,
                                    is_approval: false,
                                    hook_call: None,
                                },
                                AccountAmount {
                                    account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    amount: -1,
                                    is_approval: true,
                                    hook_call: None,
                                },
                            ],
                            nft_transfers: [],
                            expected_decimals: None,
                        },
                        TokenTransferList {
                            token: Some(
                                TokenId {
                                    shard_num: 0,
                                    realm_num: 0,
                                    token_num: 3,
                                },
                            ),
                            transfers: [],
                            nft_transfers: [
                                NftTransfer {
                                    sender_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    receiver_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    serial_number: 2,
                                    is_approval: false,
                                    sender_allowance_hook_call: None,
                                    receiver_allowance_hook_call: None,
                                },
                                NftTransfer {
                                    sender_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    receiver_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    serial_number: 1,
                                    is_approval: true,
                                    sender_allowance_hook_call: None,
                                    receiver_allowance_hook_call: None,
                                },
                                NftTransfer {
                                    sender_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5008,
                                                ),
                                            ),
                                        },
                                    ),
                                    receiver_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    serial_number: 3,
                                    is_approval: false,
                                    sender_allowance_hook_call: None,
                                    receiver_allowance_hook_call: None,
                                },
                                NftTransfer {
                                    sender_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    receiver_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    serial_number: 4,
                                    is_approval: false,
                                    sender_allowance_hook_call: None,
                                    receiver_allowance_hook_call: None,
                                },
                            ],
                            expected_decimals: None,
                        },
                        TokenTransferList {
                            token: Some(
                                TokenId {
                                    shard_num: 0,
                                    realm_num: 0,
                                    token_num: 2,
                                },
                            ),
                            transfers: [],
                            nft_transfers: [
                                NftTransfer {
                                    sender_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5007,
                                                ),
                                            ),
                                        },
                                    ),
                                    receiver_account_id: Some(
                                        AccountId {
                                            shard_num: 0,
                                            realm_num: 0,
                                            account: Some(
                                                AccountNum(
                                                    5006,
                                                ),
                                            ),
                                        },
                                    ),
                                    serial_number: 4,
                                    is_approval: false,
                                    sender_allowance_hook_call: None,
                                    receiver_allowance_hook_call: None,
                                },
                            ],
                            expected_decimals: None,
                        },
                    ],
                },
            )
        "#]]
        .assert_debug_eq(&tx)
    }

    #[test]
    fn to_from_bytes() {
        let tx = make_transaction();

        let tx2 = AnyTransaction::from_bytes(&tx.to_bytes().unwrap()).unwrap();

        let tx = transaction_body(tx);

        let tx2 = transaction_body(tx2);

        assert_eq!(tx, tx2);
    }

    #[test]
    fn get_decimals() {
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);

        assert_eq!(tx.get_token_decimals().get(&TOKEN), None);

        tx.token_transfer(TOKEN, AccountId::new(0, 0, 8), 100);
        assert_eq!(tx.get_token_decimals().get(&TOKEN), None);

        tx.token_transfer_with_decimals(TOKEN, AccountId::new(0, 0, 7), -100, 5);
        assert_eq!(tx.get_token_decimals().get(&TOKEN), Some(&5));
    }

    #[test]
    fn token_transfer_aggregation_same_token_and_account() {
        // Test that multiple transfers for the same token + account aggregate amounts
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);
        const ACCOUNT: AccountId = AccountId::new(0, 0, 100);

        // Add multiple transfers for the same token and account
        tx.token_transfer(TOKEN, ACCOUNT, 100);
        tx.token_transfer(TOKEN, ACCOUNT, 200);
        tx.token_transfer(TOKEN, ACCOUNT, 300);

        let transfers = tx.get_token_transfers();
        let account_transfers = transfers.get(&TOKEN).unwrap();

        // Should have only one entry with aggregated amount
        assert_eq!(account_transfers.len(), 1);
        assert_eq!(account_transfers.get(&ACCOUNT), Some(&600));
    }

    #[test]
    fn token_transfer_aggregation_different_accounts() {
        // Test that different accounts create separate entries
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);
        const ACCOUNT1: AccountId = AccountId::new(0, 0, 100);
        const ACCOUNT2: AccountId = AccountId::new(0, 0, 200);

        tx.token_transfer(TOKEN, ACCOUNT1, 100);
        tx.token_transfer(TOKEN, ACCOUNT2, 200);
        tx.token_transfer(TOKEN, ACCOUNT1, 300);

        let transfers = tx.get_token_transfers();
        let account_transfers = transfers.get(&TOKEN).unwrap();

        // Should have two entries, one for each account
        assert_eq!(account_transfers.len(), 2);
        assert_eq!(account_transfers.get(&ACCOUNT1), Some(&400)); // 100 + 300
        assert_eq!(account_transfers.get(&ACCOUNT2), Some(&200));
    }

    #[test]
    fn token_transfer_aggregation_different_tokens() {
        // Test that different tokens create separate entries
        let mut tx = TransferTransaction::new();
        const TOKEN1: TokenId = TokenId::new(0, 0, 5);
        const TOKEN2: TokenId = TokenId::new(0, 0, 6);
        const ACCOUNT: AccountId = AccountId::new(0, 0, 100);

        tx.token_transfer(TOKEN1, ACCOUNT, 100);
        tx.token_transfer(TOKEN2, ACCOUNT, 200);
        tx.token_transfer(TOKEN1, ACCOUNT, 300);

        let transfers = tx.get_token_transfers();

        // Should have entries for both tokens
        assert_eq!(transfers.len(), 2);
        assert_eq!(transfers.get(&TOKEN1).unwrap().get(&ACCOUNT), Some(&400)); // 100 + 300
        assert_eq!(transfers.get(&TOKEN2).unwrap().get(&ACCOUNT), Some(&200));
    }

    #[test]
    fn token_transfer_aggregation_approved_vs_non_approved() {
        // Test that approved and non-approved transfers are kept separate
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);
        const ACCOUNT: AccountId = AccountId::new(0, 0, 100);

        tx.token_transfer(TOKEN, ACCOUNT, 100);
        tx.approved_token_transfer(TOKEN, ACCOUNT, 200);
        tx.token_transfer(TOKEN, ACCOUNT, 300);
        tx.approved_token_transfer(TOKEN, ACCOUNT, 400);

        // Access internal data to verify both approved and non-approved transfers exist
        let data = tx.data();
        let token_transfer = data.token_transfers.iter().find(|tt| tt.token_id == TOKEN).unwrap();

        // Should have 2 transfer entries: one non-approved (400) and one approved (600)
        assert_eq!(token_transfer.transfers.len(), 2);

        let non_approved = token_transfer
            .transfers
            .iter()
            .find(|t| !t.is_approval && t.account_id == ACCOUNT)
            .unwrap();
        assert_eq!(non_approved.amount, 400); // 100 + 300

        let approved = token_transfer
            .transfers
            .iter()
            .find(|t| t.is_approval && t.account_id == ACCOUNT)
            .unwrap();
        assert_eq!(approved.amount, 600); // 200 + 400
    }

    #[test]
    fn token_transfer_with_decimals_aggregation() {
        // Test that transfers with decimals also aggregate properly
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);
        const ACCOUNT: AccountId = AccountId::new(0, 0, 100);

        tx.token_transfer_with_decimals(TOKEN, ACCOUNT, 100, 3);
        tx.token_transfer_with_decimals(TOKEN, ACCOUNT, 200, 3);
        tx.token_transfer_with_decimals(TOKEN, ACCOUNT, 300, 3);

        let transfers = tx.get_token_transfers();
        let account_transfers = transfers.get(&TOKEN).unwrap();

        // Should have only one entry with aggregated amount
        assert_eq!(account_transfers.len(), 1);
        assert_eq!(account_transfers.get(&ACCOUNT), Some(&600));

        // Decimals should be set
        assert_eq!(tx.get_token_decimals().get(&TOKEN), Some(&3));
    }

    #[test]
    fn token_transfer_negative_amounts_aggregate() {
        // Test that negative amounts (withdrawals) also aggregate correctly
        let mut tx = TransferTransaction::new();
        const TOKEN: TokenId = TokenId::new(0, 0, 5);
        const SENDER: AccountId = AccountId::new(0, 0, 100);
        const RECEIVER: AccountId = AccountId::new(0, 0, 200);

        tx.token_transfer(TOKEN, SENDER, -100);
        tx.token_transfer(TOKEN, SENDER, -200);
        tx.token_transfer(TOKEN, RECEIVER, 150);
        tx.token_transfer(TOKEN, RECEIVER, 150);

        let transfers = tx.get_token_transfers();
        let account_transfers = transfers.get(&TOKEN).unwrap();

        assert_eq!(account_transfers.get(&SENDER), Some(&-300)); // -100 + -200
        assert_eq!(account_transfers.get(&RECEIVER), Some(&300)); // 150 + 150
    }
}