aptos-sdk 0.5.0

A user-friendly, idiomatic Rust SDK for the Aptos blockchain
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
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
//! Transaction types.

use crate::error::AptosResult;
use crate::transaction::authenticator::TransactionAuthenticator;
use crate::transaction::payload::TransactionPayload;
use crate::types::{AccountAddress, ChainId, HashValue};
use serde::{Deserialize, Serialize};

/// The raw transaction that a client signs.
///
/// A `RawTransaction` contains all the details of a transaction before
/// it is signed, including the sender, payload, gas parameters, and
/// expiration time.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RawTransaction {
    /// Sender's address.
    pub sender: AccountAddress,
    /// Sequence number of this transaction.
    pub sequence_number: u64,
    /// The transaction payload (entry function, script, etc.).
    pub payload: TransactionPayload,
    /// Maximum gas units the sender is willing to pay.
    pub max_gas_amount: u64,
    /// Price per gas unit in octas.
    pub gas_unit_price: u64,
    /// Expiration time in seconds since Unix epoch.
    pub expiration_timestamp_secs: u64,
    /// Chain ID to prevent cross-chain replay.
    pub chain_id: ChainId,
}

impl RawTransaction {
    /// Creates a new raw transaction.
    pub fn new(
        sender: AccountAddress,
        sequence_number: u64,
        payload: TransactionPayload,
        max_gas_amount: u64,
        gas_unit_price: u64,
        expiration_timestamp_secs: u64,
        chain_id: ChainId,
    ) -> Self {
        Self {
            sender,
            sequence_number,
            payload,
            max_gas_amount,
            gas_unit_price,
            expiration_timestamp_secs,
            chain_id,
        }
    }

    /// Generates the signing message for this transaction.
    ///
    /// This is the message that should be signed to create a valid
    /// transaction authenticator.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization of the transaction fails.
    pub fn signing_message(&self) -> AptosResult<Vec<u8>> {
        let prefix = crate::crypto::sha3_256(b"APTOS::RawTransaction");
        let bcs_bytes = aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)?;

        let mut message = Vec::with_capacity(prefix.len() + bcs_bytes.len());
        message.extend_from_slice(&prefix);
        message.extend_from_slice(&bcs_bytes);
        Ok(message)
    }

    /// Serializes this transaction to BCS bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn to_bcs(&self) -> AptosResult<Vec<u8>> {
        aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)
    }
}

/// An orderless transaction using hash-based replay protection.
///
/// Unlike standard transactions that use sequence numbers, orderless transactions
/// use a random nonce and a short expiration window (typically 60 seconds) to
/// prevent replay attacks. This allows transactions to be submitted in any order.
///
/// # Note
///
/// Orderless transactions must be configured with a very short expiration time
/// (recommended: 60 seconds or less) since the replay protection relies on
/// the chain remembering recently seen transaction hashes.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RawTransactionOrderless {
    /// Sender's address.
    pub sender: AccountAddress,
    /// Random nonce for uniqueness (32 bytes recommended).
    pub nonce: Vec<u8>,
    /// The transaction payload (entry function, script, etc.).
    pub payload: TransactionPayload,
    /// Maximum gas units the sender is willing to pay.
    pub max_gas_amount: u64,
    /// Price per gas unit in octas.
    pub gas_unit_price: u64,
    /// Expiration time in seconds since Unix epoch.
    /// Should be short (e.g., current time + 60 seconds).
    pub expiration_timestamp_secs: u64,
    /// Chain ID to prevent cross-chain replay.
    pub chain_id: ChainId,
}

impl RawTransactionOrderless {
    /// Creates a new orderless transaction with a random nonce.
    pub fn new(
        sender: AccountAddress,
        payload: TransactionPayload,
        max_gas_amount: u64,
        gas_unit_price: u64,
        expiration_timestamp_secs: u64,
        chain_id: ChainId,
    ) -> Self {
        // Generate a random 32-byte nonce
        let mut nonce = vec![0u8; 32];
        rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
        Self {
            sender,
            nonce,
            payload,
            max_gas_amount,
            gas_unit_price,
            expiration_timestamp_secs,
            chain_id,
        }
    }

    /// Creates a new orderless transaction with a specific nonce.
    pub fn with_nonce(
        sender: AccountAddress,
        nonce: Vec<u8>,
        payload: TransactionPayload,
        max_gas_amount: u64,
        gas_unit_price: u64,
        expiration_timestamp_secs: u64,
        chain_id: ChainId,
    ) -> Self {
        Self {
            sender,
            nonce,
            payload,
            max_gas_amount,
            gas_unit_price,
            expiration_timestamp_secs,
            chain_id,
        }
    }

    /// Generates the signing message for this orderless transaction.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization of the transaction fails.
    pub fn signing_message(&self) -> AptosResult<Vec<u8>> {
        let prefix = crate::crypto::sha3_256(b"APTOS::RawTransactionOrderless");
        let bcs_bytes = aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)?;

        let mut message = Vec::with_capacity(prefix.len() + bcs_bytes.len());
        message.extend_from_slice(&prefix);
        message.extend_from_slice(&bcs_bytes);
        Ok(message)
    }

    /// Serializes this transaction to BCS bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn to_bcs(&self) -> AptosResult<Vec<u8>> {
        aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)
    }
}

/// A signed orderless transaction ready for submission.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedTransactionOrderless {
    /// The orderless raw transaction.
    pub raw_txn: RawTransactionOrderless,
    /// The authenticator (signature(s) and public key(s)).
    pub authenticator: TransactionAuthenticator,
}

impl SignedTransactionOrderless {
    /// Creates a new signed orderless transaction.
    pub fn new(raw_txn: RawTransactionOrderless, authenticator: TransactionAuthenticator) -> Self {
        Self {
            raw_txn,
            authenticator,
        }
    }

    /// Serializes this signed transaction to BCS bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn to_bcs(&self) -> AptosResult<Vec<u8>> {
        aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)
    }

    /// Returns the sender address.
    pub fn sender(&self) -> AccountAddress {
        self.raw_txn.sender
    }

    /// Returns the nonce.
    pub fn nonce(&self) -> &[u8] {
        &self.raw_txn.nonce
    }

    /// Computes the transaction hash.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization of the transaction fails.
    pub fn hash(&self) -> AptosResult<HashValue> {
        let bcs_bytes = self.to_bcs()?;
        let prefix = crate::crypto::sha3_256(b"APTOS::Transaction");

        let mut data = Vec::with_capacity(prefix.len() + 1 + bcs_bytes.len());
        data.extend_from_slice(&prefix);
        // Use variant 2 for orderless user transactions (assuming standard is 0, script is 1)
        data.push(2);
        data.extend_from_slice(&bcs_bytes);

        Ok(HashValue::new(crate::crypto::sha3_256(&data)))
    }
}

/// A signed transaction ready for submission.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct SignedTransaction {
    /// The raw transaction.
    pub raw_txn: RawTransaction,
    /// The authenticator (signature(s) and public key(s)).
    pub authenticator: TransactionAuthenticator,
}

impl SignedTransaction {
    /// Creates a new signed transaction.
    pub fn new(raw_txn: RawTransaction, authenticator: TransactionAuthenticator) -> Self {
        Self {
            raw_txn,
            authenticator,
        }
    }

    /// Clones this transaction with authenticators rewritten for `/transactions/simulate`.
    ///
    /// The Aptos fullnode rejects simulate requests that carry a cryptographically **valid**
    /// signature. [`crate::api::FullnodeClient::simulate_transaction`] applies this
    /// transformation automatically; this helper exists for callers who serialize manually.
    #[must_use]
    pub fn for_simulate_endpoint(&self) -> Self {
        Self {
            raw_txn: self.raw_txn.clone(),
            authenticator: self.authenticator.clone().for_simulate_endpoint(),
        }
    }

    /// Serializes this signed transaction to BCS bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn to_bcs(&self) -> AptosResult<Vec<u8>> {
        aptos_bcs::to_bytes(self).map_err(crate::error::AptosError::bcs)
    }

    /// Returns the sender address.
    pub fn sender(&self) -> AccountAddress {
        self.raw_txn.sender
    }

    /// Returns the sequence number.
    pub fn sequence_number(&self) -> u64 {
        self.raw_txn.sequence_number
    }

    /// Computes the transaction hash.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization of the transaction fails.
    pub fn hash(&self) -> AptosResult<HashValue> {
        let bcs_bytes = self.to_bcs()?;
        let prefix = crate::crypto::sha3_256(b"APTOS::Transaction");

        let mut data = Vec::with_capacity(prefix.len() + 1 + bcs_bytes.len());
        data.extend_from_slice(&prefix);
        data.push(0); // User transaction variant
        data.extend_from_slice(&bcs_bytes);

        Ok(HashValue::new(crate::crypto::sha3_256(&data)))
    }

    /// Verifies the transaction authenticator against the transaction's
    /// signing message and sender address.
    ///
    /// # Errors
    ///
    /// Returns an error if the authenticator does not verify or if the
    /// derived sender address does not match the raw transaction sender.
    pub fn verify_signature(&self) -> AptosResult<()> {
        match &self.authenticator {
            #[cfg(feature = "ed25519")]
            TransactionAuthenticator::Ed25519 {
                public_key,
                signature,
            } => {
                let public_key = crate::crypto::Ed25519PublicKey::from_bytes(&public_key.0)?;
                let signature = crate::crypto::Ed25519Signature::from_bytes(&signature.0)?;
                let signing_message = self.raw_txn.signing_message()?;
                public_key.verify(&signing_message, &signature)?;
                if public_key.to_address() != self.raw_txn.sender {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "signed transaction sender does not match authenticator address".into(),
                    ));
                }
                Ok(())
            }
            #[cfg(not(feature = "ed25519"))]
            TransactionAuthenticator::Ed25519 { .. } => Err(
                crate::error::AptosError::FeatureNotEnabled("Ed25519 verification".into()),
            ),
            #[cfg(feature = "ed25519")]
            TransactionAuthenticator::MultiEd25519 {
                public_key,
                signature,
            } => {
                let public_key = crate::crypto::MultiEd25519PublicKey::from_bytes(public_key)?;
                let signature = crate::crypto::MultiEd25519Signature::from_bytes(signature)?;
                let signing_message = self.raw_txn.signing_message()?;
                public_key.verify(&signing_message, &signature)?;
                if public_key.to_address() != self.raw_txn.sender {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "signed transaction sender does not match authenticator address".into(),
                    ));
                }
                Ok(())
            }
            #[cfg(not(feature = "ed25519"))]
            TransactionAuthenticator::MultiEd25519 { .. } => Err(
                crate::error::AptosError::FeatureNotEnabled("MultiEd25519 verification".into()),
            ),
            TransactionAuthenticator::SingleSender { sender } => {
                let signing_message = self.raw_txn.signing_message()?;
                sender.verify(&signing_message)?;
                if sender.derived_address()? != self.raw_txn.sender {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "signed transaction sender does not match authenticator address".into(),
                    ));
                }
                Ok(())
            }
            TransactionAuthenticator::MultiAgent {
                sender,
                secondary_signer_addresses,
                secondary_signers,
            } => {
                if secondary_signer_addresses.len() != secondary_signers.len() {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "secondary signer count does not match secondary signer addresses".into(),
                    ));
                }
                let signing_message = MultiAgentRawTransaction::new(
                    self.raw_txn.clone(),
                    secondary_signer_addresses.clone(),
                )
                .signing_message()?;
                sender.verify(&signing_message)?;
                if sender.derived_address()? != self.raw_txn.sender {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "signed transaction sender does not match authenticator address".into(),
                    ));
                }
                for (expected_address, signer) in secondary_signer_addresses
                    .iter()
                    .zip(secondary_signers.iter())
                {
                    signer.verify(&signing_message)?;
                    if signer.derived_address()? != *expected_address {
                        return Err(crate::error::AptosError::InvalidSignature(
                            "secondary signer address does not match authenticator address".into(),
                        ));
                    }
                }
                Ok(())
            }
            TransactionAuthenticator::FeePayer {
                sender,
                secondary_signer_addresses,
                secondary_signers,
                fee_payer_address,
                fee_payer_signer,
            } => {
                if secondary_signer_addresses.len() != secondary_signers.len() {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "secondary signer count does not match secondary signer addresses".into(),
                    ));
                }
                let signing_message = FeePayerRawTransaction::new(
                    self.raw_txn.clone(),
                    secondary_signer_addresses.clone(),
                    *fee_payer_address,
                )
                .signing_message()?;
                sender.verify(&signing_message)?;
                if sender.derived_address()? != self.raw_txn.sender {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "signed transaction sender does not match authenticator address".into(),
                    ));
                }
                for (expected_address, signer) in secondary_signer_addresses
                    .iter()
                    .zip(secondary_signers.iter())
                {
                    signer.verify(&signing_message)?;
                    if signer.derived_address()? != *expected_address {
                        return Err(crate::error::AptosError::InvalidSignature(
                            "secondary signer address does not match authenticator address".into(),
                        ));
                    }
                }
                fee_payer_signer.verify(&signing_message)?;
                if fee_payer_signer.derived_address()? != *fee_payer_address {
                    return Err(crate::error::AptosError::InvalidSignature(
                        "fee payer address does not match authenticator address".into(),
                    ));
                }
                Ok(())
            }
        }
    }
}

/// Information about a submitted/executed transaction.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionInfo {
    /// The transaction hash.
    pub hash: HashValue,
    /// The ledger version this transaction was committed at.
    #[serde(default)]
    pub version: Option<u64>,
    /// Whether the transaction succeeded.
    #[serde(default)]
    pub success: Option<bool>,
    /// The VM status message.
    #[serde(default)]
    pub vm_status: Option<String>,
    /// Gas used by the transaction.
    #[serde(default)]
    pub gas_used: Option<u64>,
}

impl TransactionInfo {
    /// Returns true if the transaction succeeded.
    pub fn is_success(&self) -> bool {
        self.success.unwrap_or(false)
    }
}

/// Multi-agent transaction with additional signers.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct MultiAgentRawTransaction {
    /// The raw transaction.
    pub raw_txn: RawTransaction,
    /// Secondary signer addresses.
    pub secondary_signer_addresses: Vec<AccountAddress>,
}

impl MultiAgentRawTransaction {
    /// Creates a new multi-agent transaction.
    pub fn new(raw_txn: RawTransaction, secondary_signer_addresses: Vec<AccountAddress>) -> Self {
        Self {
            raw_txn,
            secondary_signer_addresses,
        }
    }

    /// Generates the signing message for multi-agent transactions.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn signing_message(&self) -> AptosResult<Vec<u8>> {
        // Serialize as RawTransactionWithData::MultiAgent variant
        #[derive(Serialize)]
        enum RawTransactionWithData<'a> {
            MultiAgent {
                raw_txn: &'a RawTransaction,
                secondary_signer_addresses: &'a Vec<AccountAddress>,
            },
        }

        let prefix = crate::crypto::sha3_256(b"APTOS::RawTransactionWithData");

        let data = RawTransactionWithData::MultiAgent {
            raw_txn: &self.raw_txn,
            secondary_signer_addresses: &self.secondary_signer_addresses,
        };

        let bcs_bytes = aptos_bcs::to_bytes(&data).map_err(crate::error::AptosError::bcs)?;

        let mut message = Vec::with_capacity(prefix.len() + bcs_bytes.len());
        message.extend_from_slice(&prefix);
        message.extend_from_slice(&bcs_bytes);
        Ok(message)
    }
}

/// Fee payer transaction where a third party pays gas fees.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct FeePayerRawTransaction {
    /// The raw transaction.
    pub raw_txn: RawTransaction,
    /// Secondary signer addresses (for multi-agent).
    pub secondary_signer_addresses: Vec<AccountAddress>,
    /// The fee payer's address.
    pub fee_payer_address: AccountAddress,
}

impl FeePayerRawTransaction {
    /// Creates a new fee payer transaction.
    pub fn new(
        raw_txn: RawTransaction,
        secondary_signer_addresses: Vec<AccountAddress>,
        fee_payer_address: AccountAddress,
    ) -> Self {
        Self {
            raw_txn,
            secondary_signer_addresses,
            fee_payer_address,
        }
    }

    /// Creates a fee payer transaction without secondary signers.
    pub fn new_simple(raw_txn: RawTransaction, fee_payer_address: AccountAddress) -> Self {
        Self {
            raw_txn,
            secondary_signer_addresses: vec![],
            fee_payer_address,
        }
    }

    /// Generates the signing message for fee payer transactions.
    ///
    /// # Errors
    ///
    /// Returns an error if BCS serialization fails.
    pub fn signing_message(&self) -> AptosResult<Vec<u8>> {
        #[derive(Serialize)]
        enum RawTransactionWithData<'a> {
            #[allow(dead_code)]
            MultiAgent {
                raw_txn: &'a RawTransaction,
                secondary_signer_addresses: &'a Vec<AccountAddress>,
            },
            MultiAgentWithFeePayer {
                raw_txn: &'a RawTransaction,
                secondary_signer_addresses: &'a Vec<AccountAddress>,
                fee_payer_address: &'a AccountAddress,
            },
        }
        let prefix = crate::crypto::sha3_256(b"APTOS::RawTransactionWithData");

        let data = RawTransactionWithData::MultiAgentWithFeePayer {
            raw_txn: &self.raw_txn,
            secondary_signer_addresses: &self.secondary_signer_addresses,
            fee_payer_address: &self.fee_payer_address,
        };

        let bcs_bytes = aptos_bcs::to_bytes(&data).map_err(crate::error::AptosError::bcs)?;

        let mut message = Vec::with_capacity(prefix.len() + bcs_bytes.len());
        message.extend_from_slice(&prefix);
        message.extend_from_slice(&bcs_bytes);
        Ok(message)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transaction::payload::EntryFunction;
    use crate::types::MoveModuleId;

    fn create_test_raw_transaction() -> RawTransaction {
        RawTransaction::new(
            AccountAddress::ONE,
            0,
            TransactionPayload::EntryFunction(EntryFunction {
                module: MoveModuleId::from_str_strict("0x1::coin").unwrap(),
                function: "transfer".to_string(),
                type_args: vec![],
                args: vec![],
            }),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        )
    }

    #[cfg(feature = "ed25519")]
    fn create_transfer_raw_transaction(sender: AccountAddress) -> RawTransaction {
        RawTransaction::new(
            sender,
            0,
            EntryFunction::apt_transfer(AccountAddress::from_hex("0x2").unwrap(), 1)
                .unwrap()
                .into(),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        )
    }

    #[test]
    fn test_raw_transaction_signing_message() {
        let txn = create_test_raw_transaction();
        let message = txn.signing_message().unwrap();
        assert!(!message.is_empty());
        // First 32 bytes should be the hash prefix
        assert_eq!(message.len(), 32 + txn.to_bcs().unwrap().len());
    }

    #[test]
    fn test_raw_transaction_fields() {
        let txn = create_test_raw_transaction();
        assert_eq!(txn.sender, AccountAddress::ONE);
        assert_eq!(txn.sequence_number, 0);
        assert_eq!(txn.max_gas_amount, 100_000);
        assert_eq!(txn.gas_unit_price, 100);
        assert_eq!(txn.expiration_timestamp_secs, 1_000_000_000);
        assert_eq!(txn.chain_id, ChainId::testnet());
    }

    #[test]
    fn test_raw_transaction_bcs_serialization() {
        let txn = create_test_raw_transaction();
        let bcs = txn.to_bcs().unwrap();
        assert!(!bcs.is_empty());
    }

    #[test]
    fn test_signed_transaction() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_raw_transaction();
        // Create a dummy authenticator
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(txn, auth);
        assert_eq!(signed.sender(), AccountAddress::ONE);
    }

    #[test]
    fn test_signed_transaction_bcs() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_raw_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(txn, auth);
        let bcs = signed.to_bcs().unwrap();
        assert!(!bcs.is_empty());
    }

    #[test]
    fn test_authenticator_bcs_format() {
        // Test that Ed25519 authenticator serializes WITH length prefixes (Aptos BCS format)
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0xab; 32]),
            signature: Ed25519Signature([0xcd; 64]),
        };
        let bcs = aptos_bcs::to_bytes(&auth).unwrap();

        // Print for debugging
        println!("Authenticator BCS bytes: {}", const_hex::encode(&bcs));
        println!("First byte (variant index): {}", bcs[0]);
        println!("Second byte (length prefix): {}", bcs[1]);
        println!("Third byte (first pubkey byte): {}", bcs[2]);

        // Ed25519 variant should be index 0
        assert_eq!(bcs[0], 0, "Ed25519 variant index should be 0");
        // Next byte is length prefix for pubkey (32 = 0x20)
        assert_eq!(bcs[1], 32, "Pubkey length prefix should be 32");
        // Next 32 bytes should be pubkey
        assert_eq!(bcs[2], 0xab, "First pubkey byte should be 0xab");
        // After pubkey (1 + 1 + 32 = 34), length prefix for signature (64 = 0x40)
        assert_eq!(bcs[34], 64, "Signature length prefix should be 64");
        // Signature starts at offset 35
        assert_eq!(bcs[35], 0xcd, "First signature byte should be 0xcd");
        // Total: 1 (variant) + 1 (pubkey len) + 32 (pubkey) + 1 (sig len) + 64 (sig) = 99
        assert_eq!(bcs.len(), 99, "BCS length should be 99");
    }

    #[test]
    fn test_transaction_info_deserialization() {
        let json = r#"{
            "version": 12345,
            "hash": "0x0000000000000000000000000000000000000000000000000000000000000001",
            "gas_used": 100,
            "success": true,
            "vm_status": "Executed successfully"
        }"#;
        let info: TransactionInfo = serde_json::from_str(json).unwrap();
        assert_eq!(info.version, Some(12345));
        assert_eq!(info.gas_used, Some(100));
        assert_eq!(info.success, Some(true));
        assert_eq!(info.vm_status, Some("Executed successfully".to_string()));
    }

    #[test]
    fn test_fee_payer_raw_transaction_new() {
        let raw_txn = create_test_raw_transaction();
        let secondary_addr = AccountAddress::from_hex("0x2").unwrap();
        let fee_payer_addr = AccountAddress::THREE;
        let fee_payer = FeePayerRawTransaction::new(raw_txn, vec![secondary_addr], fee_payer_addr);
        assert_eq!(fee_payer.fee_payer_address, AccountAddress::THREE);
        assert_eq!(fee_payer.secondary_signer_addresses.len(), 1);
    }

    #[test]
    fn test_fee_payer_raw_transaction_new_simple() {
        let raw_txn = create_test_raw_transaction();
        let fee_payer = FeePayerRawTransaction::new_simple(raw_txn, AccountAddress::THREE);
        assert_eq!(fee_payer.fee_payer_address, AccountAddress::THREE);
        assert!(fee_payer.secondary_signer_addresses.is_empty());
    }

    #[test]
    fn test_fee_payer_signing_message() {
        let raw_txn = create_test_raw_transaction();
        let fee_payer = FeePayerRawTransaction::new_simple(raw_txn, AccountAddress::THREE);
        let message = fee_payer.signing_message().unwrap();
        assert!(!message.is_empty());
    }

    #[test]
    fn test_signed_transaction_hash() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_raw_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(txn, auth);
        let hash = signed.hash().unwrap();
        // Hash should be 32 bytes
        assert_eq!(hash.as_bytes().len(), 32);
        // Hash should be deterministic
        let hash2 = signed.hash().unwrap();
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_signed_transaction_sequence_number() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_raw_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(txn, auth);
        assert_eq!(signed.sequence_number(), 0);
    }

    #[test]
    fn test_transaction_info_is_success() {
        let info_success = TransactionInfo {
            hash: HashValue::new([0; 32]),
            version: Some(1),
            success: Some(true),
            vm_status: None,
            gas_used: Some(100),
        };
        assert!(info_success.is_success());

        let info_failed = TransactionInfo {
            hash: HashValue::new([0; 32]),
            version: Some(1),
            success: Some(false),
            vm_status: Some("Failed".to_string()),
            gas_used: Some(100),
        };
        assert!(!info_failed.is_success());

        let info_unknown = TransactionInfo {
            hash: HashValue::new([0; 32]),
            version: None,
            success: None,
            vm_status: None,
            gas_used: None,
        };
        assert!(!info_unknown.is_success());
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_ed25519_sender_mismatch() {
        use crate::account::Ed25519Account;
        use crate::error::AptosError;
        use crate::transaction::builder::sign_transaction;

        let signer = Ed25519Account::generate();
        let claimed_sender = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(claimed_sender.address());
        let signed_txn = sign_transaction(&raw_txn, &signer).unwrap();
        let err = signed_txn.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("sender does not match"))
        );
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_multi_ed25519_sender_mismatch() {
        use crate::account::Ed25519Account;
        use crate::account::MultiEd25519Account;
        use crate::crypto::Ed25519PrivateKey;
        use crate::error::AptosError;
        use crate::transaction::builder::sign_transaction;

        let signer = MultiEd25519Account::new(
            vec![Ed25519PrivateKey::generate(), Ed25519PrivateKey::generate()],
            2,
        )
        .unwrap();
        let claimed_sender = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(claimed_sender.address());
        let signed_txn = sign_transaction(&raw_txn, &signer).unwrap();
        let err = signed_txn.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("sender does not match"))
        );
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_single_sender_sender_mismatch() {
        use crate::account::Ed25519SingleKeyAccount;
        use crate::error::AptosError;
        use crate::transaction::builder::sign_transaction;

        let signer = Ed25519SingleKeyAccount::generate();
        let claimed_sender = Ed25519SingleKeyAccount::generate();
        let raw_txn = create_transfer_raw_transaction(claimed_sender.address());
        let signed_txn = sign_transaction(&raw_txn, &signer).unwrap();
        let err = signed_txn.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("sender does not match"))
        );
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_multi_agent_sender_mismatch() {
        use crate::account::{Account, Ed25519Account};
        use crate::error::AptosError;
        use crate::transaction::builder::sign_multi_agent_transaction;

        let signer = Ed25519Account::generate();
        let claimed_sender = Ed25519Account::generate();
        let secondary = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(claimed_sender.address());

        let multi_agent = MultiAgentRawTransaction::new(raw_txn, vec![secondary.address()]);
        let secondary_refs: Vec<&dyn Account> = vec![&secondary];
        let signed_txn =
            sign_multi_agent_transaction(&multi_agent, &signer, &secondary_refs).unwrap();
        let err = signed_txn.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("sender does not match"))
        );
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_multi_agent_secondary_address_mismatch() {
        use crate::account::{Account, Ed25519Account};
        use crate::error::AptosError;
        use crate::transaction::builder::sign_multi_agent_transaction;

        let sender = Ed25519Account::generate();
        let expected_secondary = Ed25519Account::generate();
        let wrong_secondary = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(sender.address());
        let multi_agent =
            MultiAgentRawTransaction::new(raw_txn, vec![expected_secondary.address()]);
        let secondary_refs: Vec<&dyn Account> = vec![&wrong_secondary];
        let signed = sign_multi_agent_transaction(&multi_agent, &sender, &secondary_refs).unwrap();
        let err = signed.verify_signature().unwrap_err();
        assert!(matches!(err, AptosError::InvalidSignature(msg) if msg
            .contains("secondary signer address does not match")));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_fee_payer_sender_mismatch() {
        use crate::account::{Account, Ed25519Account};
        use crate::error::AptosError;
        use crate::transaction::builder::sign_fee_payer_transaction;

        let signer = Ed25519Account::generate();
        let claimed_sender = Ed25519Account::generate();
        let secondary = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(claimed_sender.address());
        let fee_payer_txn =
            FeePayerRawTransaction::new(raw_txn, vec![secondary.address()], fee_payer.address());
        let secondary_refs: Vec<&dyn Account> = vec![&secondary];
        let signed_txn =
            sign_fee_payer_transaction(&fee_payer_txn, &signer, &secondary_refs, &fee_payer)
                .unwrap();
        let err = signed_txn.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("sender does not match"))
        );
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_fee_payer_secondary_address_mismatch() {
        use crate::account::{Account, Ed25519Account};
        use crate::error::AptosError;
        use crate::transaction::builder::sign_fee_payer_transaction;

        let sender = Ed25519Account::generate();
        let expected_secondary = Ed25519Account::generate();
        let wrong_secondary = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(sender.address());
        let fee_payer_txn = FeePayerRawTransaction::new(
            raw_txn,
            vec![expected_secondary.address()],
            fee_payer.address(),
        );
        let secondary_refs: Vec<&dyn Account> = vec![&wrong_secondary];
        let signed =
            sign_fee_payer_transaction(&fee_payer_txn, &sender, &secondary_refs, &fee_payer)
                .unwrap();
        let err = signed.verify_signature().unwrap_err();
        assert!(matches!(err, AptosError::InvalidSignature(msg) if msg
            .contains("secondary signer address does not match")));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_verify_signature_fee_payer_address_mismatch() {
        use crate::account::{Account, Ed25519Account};
        use crate::error::AptosError;
        use crate::transaction::authenticator::{AccountAuthenticator, TransactionAuthenticator};
        use crate::transaction::builder::sign_fee_payer_transaction;

        let sender = Ed25519Account::generate();
        let secondary = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let impostor_fee_payer = Ed25519Account::generate();
        let raw_txn = create_transfer_raw_transaction(sender.address());
        let fee_payer_txn =
            FeePayerRawTransaction::new(raw_txn, vec![secondary.address()], fee_payer.address());
        let secondary_refs: Vec<&dyn Account> = vec![&secondary];
        let mut signed =
            sign_fee_payer_transaction(&fee_payer_txn, &sender, &secondary_refs, &fee_payer)
                .unwrap();

        let signing_message = FeePayerRawTransaction::new(
            signed.raw_txn.clone(),
            vec![secondary.address()],
            fee_payer.address(),
        )
        .signing_message()
        .unwrap();
        let impostor_auth = AccountAuthenticator::ed25519(
            impostor_fee_payer.public_key_bytes(),
            impostor_fee_payer.sign(&signing_message).unwrap(),
        );
        if let TransactionAuthenticator::FeePayer {
            fee_payer_signer, ..
        } = &mut signed.authenticator
        {
            *fee_payer_signer = impostor_auth;
        } else {
            panic!("expected FeePayer authenticator");
        }
        let err = signed.verify_signature().unwrap_err();
        assert!(
            matches!(err, AptosError::InvalidSignature(msg) if msg.contains("fee payer address"))
        );
    }

    fn create_test_orderless_transaction() -> RawTransactionOrderless {
        RawTransactionOrderless::with_nonce(
            AccountAddress::ONE,
            vec![
                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,
            ],
            TransactionPayload::EntryFunction(EntryFunction {
                module: MoveModuleId::from_str_strict("0x1::coin").unwrap(),
                function: "transfer".to_string(),
                type_args: vec![],
                args: vec![],
            }),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        )
    }

    #[test]
    fn test_orderless_transaction_with_nonce() {
        let nonce = vec![0xab; 32];
        let txn = RawTransactionOrderless::with_nonce(
            AccountAddress::ONE,
            nonce.clone(),
            TransactionPayload::EntryFunction(EntryFunction {
                module: MoveModuleId::from_str_strict("0x1::coin").unwrap(),
                function: "transfer".to_string(),
                type_args: vec![],
                args: vec![],
            }),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        );
        assert_eq!(txn.sender, AccountAddress::ONE);
        assert_eq!(txn.nonce, nonce);
        assert_eq!(txn.max_gas_amount, 100_000);
        assert_eq!(txn.gas_unit_price, 100);
    }

    #[test]
    fn test_orderless_transaction_new_generates_random_nonce() {
        let txn1 = RawTransactionOrderless::new(
            AccountAddress::ONE,
            TransactionPayload::EntryFunction(EntryFunction {
                module: MoveModuleId::from_str_strict("0x1::coin").unwrap(),
                function: "transfer".to_string(),
                type_args: vec![],
                args: vec![],
            }),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        );
        let txn2 = RawTransactionOrderless::new(
            AccountAddress::ONE,
            TransactionPayload::EntryFunction(EntryFunction {
                module: MoveModuleId::from_str_strict("0x1::coin").unwrap(),
                function: "transfer".to_string(),
                type_args: vec![],
                args: vec![],
            }),
            100_000,
            100,
            1_000_000_000,
            ChainId::testnet(),
        );
        // Random nonces should be different
        assert_ne!(txn1.nonce, txn2.nonce);
        // Nonce should be 32 bytes
        assert_eq!(txn1.nonce.len(), 32);
        assert_eq!(txn2.nonce.len(), 32);
    }

    #[test]
    fn test_orderless_transaction_signing_message() {
        let txn = create_test_orderless_transaction();
        let message = txn.signing_message().unwrap();
        assert!(!message.is_empty());
        // First 32 bytes should be the hash prefix
        assert_eq!(message.len(), 32 + txn.to_bcs().unwrap().len());
    }

    #[test]
    fn test_orderless_transaction_bcs() {
        let txn = create_test_orderless_transaction();
        let bcs = txn.to_bcs().unwrap();
        assert!(!bcs.is_empty());
    }

    #[test]
    fn test_signed_orderless_transaction() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_orderless_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransactionOrderless::new(txn, auth);
        assert_eq!(signed.sender(), AccountAddress::ONE);
        assert_eq!(signed.nonce().len(), 32);
    }

    #[test]
    fn test_signed_orderless_transaction_bcs() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_orderless_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransactionOrderless::new(txn, auth);
        let bcs = signed.to_bcs().unwrap();
        assert!(!bcs.is_empty());
    }

    #[test]
    fn test_signed_orderless_transaction_hash() {
        use crate::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        let txn = create_test_orderless_transaction();
        let auth = crate::transaction::TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey([0u8; 32]),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransactionOrderless::new(txn, auth);
        let hash = signed.hash().unwrap();
        // Hash should be 32 bytes
        assert_eq!(hash.as_bytes().len(), 32);
        // Hash should be deterministic
        let hash2 = signed.hash().unwrap();
        assert_eq!(hash, hash2);
    }

    #[test]
    fn test_multi_agent_raw_transaction() {
        let raw_txn = create_test_raw_transaction();
        let secondary = vec![AccountAddress::from_hex("0x2").unwrap()];
        let multi_agent = MultiAgentRawTransaction::new(raw_txn, secondary.clone());
        assert_eq!(multi_agent.secondary_signer_addresses, secondary);
    }

    #[test]
    fn test_multi_agent_signing_message() {
        let raw_txn = create_test_raw_transaction();
        let secondary = vec![AccountAddress::from_hex("0x2").unwrap()];
        let multi_agent = MultiAgentRawTransaction::new(raw_txn, secondary);
        let message = multi_agent.signing_message().unwrap();
        assert!(!message.is_empty());
    }
}