aptos-sdk 0.4.1

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
//! 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,
        }
    }

    /// 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)))
    }
}

/// 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(),
        )
    }

    #[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());
    }

    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());
    }
}