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
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
//! Sponsored transaction helpers.
//!
//! This module provides high-level utilities for creating and managing
//! sponsored (fee payer) transactions, where one account pays the gas fees
//! on behalf of another account.
//!
//! # Overview
//!
//! Sponsored transactions allow a "fee payer" account to pay the gas fees
//! for a transaction initiated by a different "sender" account. This is useful for:
//!
//! - **Onboarding new users** - Users without APT can still execute transactions
//! - **dApp subsidization** - Applications can pay gas fees for their users
//! - **Gasless experiences** - Create seamless UX without exposing gas costs
//!
//! # Example
//!
//! ```rust,ignore
//! use aptos_sdk::transaction::{SponsoredTransactionBuilder, EntryFunction};
//!
//! // Build a sponsored transaction
//! let fee_payer_txn = SponsoredTransactionBuilder::new()
//!     .sender(user_account.address())
//!     .sequence_number(0)
//!     .fee_payer(sponsor_account.address())
//!     .payload(payload)
//!     .chain_id(ChainId::testnet())
//!     .build()?;
//!
//! // Sign with all parties
//! let signed = sign_sponsored_transaction(
//!     &fee_payer_txn,
//!     &user_account,
//!     &[],
//!     &sponsor_account,
//! )?;
//! ```

use crate::account::Account;
use crate::error::{AptosError, AptosResult};
use crate::transaction::authenticator::{AccountAuthenticator, TransactionAuthenticator};
use crate::transaction::builder::{
    DEFAULT_EXPIRATION_SECONDS, DEFAULT_GAS_UNIT_PRICE, DEFAULT_MAX_GAS_AMOUNT,
};
use crate::transaction::payload::TransactionPayload;
use crate::transaction::types::{FeePayerRawTransaction, RawTransaction, SignedTransaction};
use crate::types::{AccountAddress, ChainId};
use std::time::{SystemTime, UNIX_EPOCH};

/// A builder for constructing sponsored (fee payer) transactions.
///
/// This provides a fluent API for creating transactions where a fee payer
/// account pays the gas fees on behalf of the sender.
///
/// # Example
///
/// ```rust,ignore
/// use aptos_sdk::transaction::{SponsoredTransactionBuilder, EntryFunction};
///
/// // Build the fee payer transaction structure
/// let fee_payer_txn = SponsoredTransactionBuilder::new()
///     .sender(user_account.address())
///     .sequence_number(0)
///     .fee_payer(sponsor_account.address())
///     .payload(payload)
///     .chain_id(ChainId::testnet())
///     .build()?;
///
/// // Then sign it
/// let signed = sign_sponsored_transaction(
///     &fee_payer_txn,
///     &user_account,
///     &[],  // no secondary signers
///     &sponsor_account,
/// )?;
/// ```
#[derive(Debug, Clone, Default)]
pub struct SponsoredTransactionBuilder {
    sender_address: Option<AccountAddress>,
    sequence_number: Option<u64>,
    secondary_addresses: Vec<AccountAddress>,
    fee_payer_address: Option<AccountAddress>,
    payload: Option<TransactionPayload>,
    max_gas_amount: u64,
    gas_unit_price: u64,
    expiration_timestamp_secs: Option<u64>,
    chain_id: Option<ChainId>,
}

impl SponsoredTransactionBuilder {
    /// Creates a new sponsored transaction builder with default values.
    #[must_use]
    pub fn new() -> Self {
        Self {
            sender_address: None,
            sequence_number: None,
            secondary_addresses: Vec::new(),
            fee_payer_address: None,
            payload: None,
            max_gas_amount: DEFAULT_MAX_GAS_AMOUNT,
            gas_unit_price: DEFAULT_GAS_UNIT_PRICE,
            expiration_timestamp_secs: None,
            chain_id: None,
        }
    }

    /// Sets the sender address.
    #[must_use]
    pub fn sender(mut self, address: AccountAddress) -> Self {
        self.sender_address = Some(address);
        self
    }

    /// Sets the sender's sequence number.
    #[must_use]
    pub fn sequence_number(mut self, sequence_number: u64) -> Self {
        self.sequence_number = Some(sequence_number);
        self
    }

    /// Adds a secondary signer address to the transaction.
    ///
    /// Secondary signers are additional accounts that must sign the transaction.
    /// This is useful for multi-party transactions.
    #[must_use]
    pub fn secondary_signer(mut self, address: AccountAddress) -> Self {
        self.secondary_addresses.push(address);
        self
    }

    /// Adds multiple secondary signer addresses to the transaction.
    #[must_use]
    pub fn secondary_signers(mut self, addresses: &[AccountAddress]) -> Self {
        self.secondary_addresses.extend(addresses);
        self
    }

    /// Sets the fee payer address.
    #[must_use]
    pub fn fee_payer(mut self, address: AccountAddress) -> Self {
        self.fee_payer_address = Some(address);
        self
    }

    /// Sets the transaction payload.
    #[must_use]
    pub fn payload(mut self, payload: TransactionPayload) -> Self {
        self.payload = Some(payload);
        self
    }

    /// Sets the maximum gas amount.
    #[must_use]
    pub fn max_gas_amount(mut self, max_gas_amount: u64) -> Self {
        self.max_gas_amount = max_gas_amount;
        self
    }

    /// Sets the gas unit price in octas.
    #[must_use]
    pub fn gas_unit_price(mut self, gas_unit_price: u64) -> Self {
        self.gas_unit_price = gas_unit_price;
        self
    }

    /// Sets the expiration timestamp in seconds since Unix epoch.
    #[must_use]
    pub fn expiration_timestamp_secs(mut self, expiration_timestamp_secs: u64) -> Self {
        self.expiration_timestamp_secs = Some(expiration_timestamp_secs);
        self
    }

    /// Sets the expiration time relative to now.
    #[must_use]
    pub fn expiration_from_now(mut self, seconds: u64) -> Self {
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs();
        self.expiration_timestamp_secs = Some(now + seconds);
        self
    }

    /// Sets the chain ID.
    #[must_use]
    pub fn chain_id(mut self, chain_id: ChainId) -> Self {
        self.chain_id = Some(chain_id);
        self
    }

    /// Builds the raw fee payer transaction (unsigned).
    ///
    /// This returns a `FeePayerRawTransaction` that can be signed later
    /// by the sender, secondary signers, and fee payer.
    ///
    /// # Errors
    ///
    /// Returns an error if `sender`, `sequence_number`, `payload`, `chain_id`, or `fee_payer` is not set.
    pub fn build(self) -> AptosResult<FeePayerRawTransaction> {
        let sender = self
            .sender_address
            .ok_or_else(|| AptosError::transaction("sender is required"))?;
        let sequence_number = self
            .sequence_number
            .ok_or_else(|| AptosError::transaction("sequence_number is required"))?;
        let payload = self
            .payload
            .ok_or_else(|| AptosError::transaction("payload is required"))?;
        let chain_id = self
            .chain_id
            .ok_or_else(|| AptosError::transaction("chain_id is required"))?;
        let fee_payer_address = self
            .fee_payer_address
            .ok_or_else(|| AptosError::transaction("fee_payer is required"))?;

        // SECURITY: Apply expiration offset only once (was previously doubled)
        let expiration_timestamp_secs = self.expiration_timestamp_secs.unwrap_or_else(|| {
            SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs()
                .saturating_add(DEFAULT_EXPIRATION_SECONDS)
        });

        let raw_txn = RawTransaction::new(
            sender,
            sequence_number,
            payload,
            self.max_gas_amount,
            self.gas_unit_price,
            expiration_timestamp_secs,
            chain_id,
        );

        Ok(FeePayerRawTransaction {
            raw_txn,
            secondary_signer_addresses: self.secondary_addresses,
            fee_payer_address,
        })
    }

    /// Builds and signs the transaction with all provided accounts.
    ///
    /// This is a convenience method that builds the transaction and signs it
    /// in one step.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let signed = SponsoredTransactionBuilder::new()
    ///     .sender(user.address())
    ///     .sequence_number(0)
    ///     .fee_payer(sponsor.address())
    ///     .payload(payload)
    ///     .chain_id(ChainId::testnet())
    ///     .build_and_sign(&user, &[], &sponsor)?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if building the transaction fails or if any signer fails to sign.
    pub fn build_and_sign<S, F>(
        self,
        sender: &S,
        secondary_signers: &[&dyn Account],
        fee_payer: &F,
    ) -> AptosResult<SignedTransaction>
    where
        S: Account,
        F: Account,
    {
        let fee_payer_txn = self.build()?;
        sign_sponsored_transaction(&fee_payer_txn, sender, secondary_signers, fee_payer)
    }
}

/// Signs a sponsored (fee payer) transaction with all required signatures.
///
/// # Arguments
///
/// * `fee_payer_txn` - The unsigned fee payer transaction
/// * `sender` - The sender account
/// * `secondary_signers` - Additional signers (if any)
/// * `fee_payer` - The account paying gas fees
///
/// # Example
///
/// ```rust,ignore
/// use aptos_sdk::transaction::sign_sponsored_transaction;
///
/// let signed_txn = sign_sponsored_transaction(
///     &fee_payer_txn,
///     &sender_account,
///     &[],  // No secondary signers
///     &fee_payer_account,
/// )?;
/// ```
///
/// # Errors
///
/// Returns an error if generating the signing message fails or if any signer fails to sign.
pub fn sign_sponsored_transaction<S, F>(
    fee_payer_txn: &FeePayerRawTransaction,
    sender: &S,
    secondary_signers: &[&dyn Account],
    fee_payer: &F,
) -> AptosResult<SignedTransaction>
where
    S: Account,
    F: Account,
{
    let signing_message = fee_payer_txn.signing_message()?;

    // Sign with sender
    let sender_signature = sender.sign(&signing_message)?;
    let sender_public_key = sender.public_key_bytes();
    let sender_auth = make_account_authenticator(
        sender.signature_scheme(),
        sender_public_key,
        sender_signature,
    )?;

    // Sign with secondary signers
    let mut secondary_auths = Vec::with_capacity(secondary_signers.len());
    for signer in secondary_signers {
        let signature = signer.sign(&signing_message)?;
        let public_key = signer.public_key_bytes();
        secondary_auths.push(make_account_authenticator(
            signer.signature_scheme(),
            public_key,
            signature,
        )?);
    }

    // Sign with fee payer
    let fee_payer_signature = fee_payer.sign(&signing_message)?;
    let fee_payer_public_key = fee_payer.public_key_bytes();
    let fee_payer_auth = make_account_authenticator(
        fee_payer.signature_scheme(),
        fee_payer_public_key,
        fee_payer_signature,
    )?;

    let authenticator = TransactionAuthenticator::fee_payer(
        sender_auth,
        fee_payer_txn.secondary_signer_addresses.clone(),
        secondary_auths,
        fee_payer_txn.fee_payer_address,
        fee_payer_auth,
    );

    Ok(SignedTransaction::new(
        fee_payer_txn.raw_txn.clone(),
        authenticator,
    ))
}

/// Creates an account authenticator from signature components.
///
/// # Errors
///
/// Returns an error if the signature scheme is not recognized.
fn make_account_authenticator(
    scheme: u8,
    public_key: Vec<u8>,
    signature: Vec<u8>,
) -> AptosResult<AccountAuthenticator> {
    match scheme {
        crate::crypto::ED25519_SCHEME => Ok(AccountAuthenticator::ed25519(public_key, signature)),
        crate::crypto::MULTI_ED25519_SCHEME => Ok(AccountAuthenticator::MultiEd25519 {
            public_key,
            signature,
        }),
        crate::crypto::SINGLE_KEY_SCHEME => {
            Ok(AccountAuthenticator::single_key(public_key, signature))
        }
        crate::crypto::MULTI_KEY_SCHEME => {
            Ok(AccountAuthenticator::multi_key(public_key, signature))
        }
        _ => Err(AptosError::InvalidSignature(format!(
            "unknown signature scheme: {scheme}"
        ))),
    }
}

/// A partially signed sponsored transaction.
///
/// This represents a sponsored transaction that has been signed by some but
/// not all required signers. It can be passed between parties for signature
/// collection.
#[derive(Debug, Clone)]
pub struct PartiallySigned {
    /// The underlying fee payer transaction.
    pub fee_payer_txn: FeePayerRawTransaction,
    /// Sender's signature (if signed).
    pub sender_auth: Option<AccountAuthenticator>,
    /// Secondary signer signatures.
    pub secondary_auths: Vec<Option<AccountAuthenticator>>,
    /// Fee payer's signature (if signed).
    pub fee_payer_auth: Option<AccountAuthenticator>,
}

impl PartiallySigned {
    /// Creates a new partially signed transaction.
    pub fn new(fee_payer_txn: FeePayerRawTransaction) -> Self {
        let num_secondary = fee_payer_txn.secondary_signer_addresses.len();
        Self {
            fee_payer_txn,
            sender_auth: None,
            secondary_auths: vec![None; num_secondary],
            fee_payer_auth: None,
        }
    }

    /// Signs as the sender.
    ///
    /// # Errors
    ///
    /// Returns an error if generating the signing message fails, if signing fails,
    /// or if the signature scheme is not recognized.
    pub fn sign_as_sender<A: Account>(&mut self, sender: &A) -> AptosResult<()> {
        let signing_message = self.fee_payer_txn.signing_message()?;
        let signature = sender.sign(&signing_message)?;
        let public_key = sender.public_key_bytes();
        self.sender_auth = Some(make_account_authenticator(
            sender.signature_scheme(),
            public_key,
            signature,
        )?);
        Ok(())
    }

    /// Signs as a secondary signer at the given index.
    ///
    /// # Errors
    ///
    /// Returns an error if the index is out of bounds, if generating the signing message fails,
    /// if signing fails, or if the signature scheme is not recognized.
    pub fn sign_as_secondary<A: Account>(&mut self, index: usize, signer: &A) -> AptosResult<()> {
        if index >= self.secondary_auths.len() {
            return Err(AptosError::transaction(format!(
                "secondary signer index {} out of bounds (max {})",
                index,
                self.secondary_auths.len()
            )));
        }

        let signing_message = self.fee_payer_txn.signing_message()?;
        let signature = signer.sign(&signing_message)?;
        let public_key = signer.public_key_bytes();
        self.secondary_auths[index] = Some(make_account_authenticator(
            signer.signature_scheme(),
            public_key,
            signature,
        )?);
        Ok(())
    }

    /// Signs as the fee payer.
    ///
    /// # Errors
    ///
    /// Returns an error if generating the signing message fails, if signing fails,
    /// or if the signature scheme is not recognized.
    pub fn sign_as_fee_payer<A: Account>(&mut self, fee_payer: &A) -> AptosResult<()> {
        let signing_message = self.fee_payer_txn.signing_message()?;
        let signature = fee_payer.sign(&signing_message)?;
        let public_key = fee_payer.public_key_bytes();
        self.fee_payer_auth = Some(make_account_authenticator(
            fee_payer.signature_scheme(),
            public_key,
            signature,
        )?);
        Ok(())
    }

    /// Checks if all required signatures have been collected.
    pub fn is_complete(&self) -> bool {
        self.sender_auth.is_some()
            && self.fee_payer_auth.is_some()
            && self.secondary_auths.iter().all(Option::is_some)
    }

    /// Finalizes the transaction if all signatures are present.
    ///
    /// Returns an error if any signatures are missing.
    ///
    /// # Errors
    ///
    /// Returns an error if the sender signature, fee payer signature, or any secondary signer signature is missing.
    pub fn finalize(self) -> AptosResult<SignedTransaction> {
        let sender_auth = self
            .sender_auth
            .ok_or_else(|| AptosError::transaction("missing sender signature"))?;
        let fee_payer_auth = self
            .fee_payer_auth
            .ok_or_else(|| AptosError::transaction("missing fee payer signature"))?;

        let secondary_auths: Result<Vec<_>, _> = self
            .secondary_auths
            .into_iter()
            .enumerate()
            .map(|(i, auth)| {
                auth.ok_or_else(|| {
                    AptosError::transaction(format!("missing secondary signer {i} signature"))
                })
            })
            .collect();
        let secondary_auths = secondary_auths?;

        let authenticator = TransactionAuthenticator::fee_payer(
            sender_auth,
            self.fee_payer_txn.secondary_signer_addresses.clone(),
            secondary_auths,
            self.fee_payer_txn.fee_payer_address,
            fee_payer_auth,
        );

        Ok(SignedTransaction::new(
            self.fee_payer_txn.raw_txn,
            authenticator,
        ))
    }
}

/// Extension trait that adds sponsorship capabilities to accounts.
///
/// This trait provides convenient methods for an account to sponsor
/// transactions for other users.
pub trait Sponsor: Account + Sized {
    /// Sponsors a transaction for another account.
    ///
    /// Creates and signs a sponsored transaction where `self` pays the gas fees.
    ///
    /// # Arguments
    ///
    /// * `sender` - The account initiating the transaction
    /// * `sender_sequence_number` - The sender's current sequence number
    /// * `payload` - The transaction payload
    /// * `chain_id` - The target chain ID
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use aptos_sdk::transaction::Sponsor;
    ///
    /// let signed_txn = sponsor_account.sponsor(
    ///     &user_account,
    ///     0,
    ///     payload,
    ///     ChainId::testnet(),
    /// )?;
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if building the transaction fails or if any signer fails to sign.
    fn sponsor<S: Account>(
        &self,
        sender: &S,
        sender_sequence_number: u64,
        payload: TransactionPayload,
        chain_id: ChainId,
    ) -> AptosResult<SignedTransaction> {
        SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_sequence_number)
            .fee_payer(self.address())
            .payload(payload)
            .chain_id(chain_id)
            .build_and_sign(sender, &[], self)
    }

    /// Sponsors a transaction with custom gas settings.
    ///
    /// # Errors
    ///
    /// Returns an error if building the transaction fails or if any signer fails to sign.
    fn sponsor_with_gas<S: Account>(
        &self,
        sender: &S,
        sender_sequence_number: u64,
        payload: TransactionPayload,
        chain_id: ChainId,
        max_gas_amount: u64,
        gas_unit_price: u64,
    ) -> AptosResult<SignedTransaction> {
        SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_sequence_number)
            .fee_payer(self.address())
            .payload(payload)
            .chain_id(chain_id)
            .max_gas_amount(max_gas_amount)
            .gas_unit_price(gas_unit_price)
            .build_and_sign(sender, &[], self)
    }
}

// Implement Sponsor for all Account types that are Sized
impl<A: Account + Sized> Sponsor for A {}

/// Creates a simple sponsored transaction with minimal configuration.
///
/// This is a convenience function for the common case of sponsoring a
/// simple transaction without secondary signers.
///
/// # Example
///
/// ```rust,ignore
/// use aptos_sdk::transaction::sponsor_transaction;
///
/// let signed = sponsor_transaction(
///     &sender_account,
///     sender_sequence_number,
///     &sponsor_account,
///     payload,
///     ChainId::testnet(),
/// )?;
/// ```
///
/// # Errors
///
/// Returns an error if building the transaction fails or if any signer fails to sign.
pub fn sponsor_transaction<S, F>(
    sender: &S,
    sender_sequence_number: u64,
    fee_payer: &F,
    payload: TransactionPayload,
    chain_id: ChainId,
) -> AptosResult<SignedTransaction>
where
    S: Account,
    F: Account,
{
    SponsoredTransactionBuilder::new()
        .sender(sender.address())
        .sequence_number(sender_sequence_number)
        .fee_payer(fee_payer.address())
        .payload(payload)
        .chain_id(chain_id)
        .build_and_sign(sender, &[], fee_payer)
}

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

    #[test]
    fn test_builder_missing_sender() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let result = SponsoredTransactionBuilder::new()
            .sequence_number(0)
            .fee_payer(AccountAddress::ONE)
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("sender"));
    }

    #[test]
    fn test_builder_missing_fee_payer() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let result = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("fee_payer"));
    }

    #[test]
    fn test_builder_complete() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(5)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .max_gas_amount(100_000)
            .gas_unit_price(150)
            .build()
            .unwrap();

        assert_eq!(fee_payer_txn.raw_txn.sender, AccountAddress::ONE);
        assert_eq!(fee_payer_txn.raw_txn.sequence_number, 5);
        assert_eq!(fee_payer_txn.raw_txn.max_gas_amount, 100_000);
        assert_eq!(fee_payer_txn.raw_txn.gas_unit_price, 150);
        assert_eq!(
            fee_payer_txn.fee_payer_address,
            AccountAddress::from_hex("0x3").unwrap()
        );
    }

    #[test]
    fn test_partially_signed_completion_check() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let partially_signed = PartiallySigned::new(fee_payer_txn);
        assert!(!partially_signed.is_complete());
    }

    #[test]
    fn test_partially_signed_finalize_incomplete() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let partially_signed = PartiallySigned::new(fee_payer_txn);
        let result = partially_signed.finalize();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("missing"));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_full_sponsored_transaction() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let signed_txn = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(0)
            .fee_payer(fee_payer.address())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build_and_sign(&sender, &[], &fee_payer)
            .unwrap();

        // Verify the transaction structure
        assert_eq!(signed_txn.raw_txn.sender, sender.address());
        assert!(matches!(
            signed_txn.authenticator,
            TransactionAuthenticator::FeePayer { .. }
        ));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_sponsor_trait() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let sponsor = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // Use the Sponsor trait
        let signed_txn = sponsor
            .sponsor(&sender, 0, payload.into(), ChainId::testnet())
            .unwrap();

        assert_eq!(signed_txn.raw_txn.sender, sender.address());
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_sponsor_transaction_fn() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // Use the convenience function
        let signed_txn =
            sponsor_transaction(&sender, 0, &fee_payer, payload.into(), ChainId::testnet())
                .unwrap();

        assert_eq!(signed_txn.raw_txn.sender, sender.address());
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_partially_signed_flow() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // Build the transaction
        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(0)
            .fee_payer(fee_payer.address())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        // Create partially signed and collect signatures
        let mut partially_signed = PartiallySigned::new(fee_payer_txn);

        // Not complete yet
        assert!(!partially_signed.is_complete());

        // Sign as sender
        partially_signed.sign_as_sender(&sender).unwrap();
        assert!(!partially_signed.is_complete());

        // Sign as fee payer
        partially_signed.sign_as_fee_payer(&fee_payer).unwrap();
        assert!(partially_signed.is_complete());

        // Finalize
        let signed_txn = partially_signed.finalize().unwrap();
        assert_eq!(signed_txn.raw_txn.sender, sender.address());
    }

    #[test]
    fn test_builder_missing_sequence_number() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let result = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("sequence_number"));
    }

    #[test]
    fn test_builder_missing_payload() {
        let result = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .chain_id(ChainId::testnet())
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("payload"));
    }

    #[test]
    fn test_builder_missing_chain_id() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let result = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .build();

        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("chain_id"));
    }

    #[test]
    fn test_builder_secondary_signers() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let secondary1 = AccountAddress::from_hex("0x4").unwrap();
        let secondary2 = AccountAddress::from_hex("0x5").unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .secondary_signer(secondary1)
            .secondary_signers(&[secondary2])
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        assert_eq!(fee_payer_txn.secondary_signer_addresses.len(), 2);
        assert_eq!(fee_payer_txn.secondary_signer_addresses[0], secondary1);
        assert_eq!(fee_payer_txn.secondary_signer_addresses[1], secondary2);
    }

    #[test]
    fn test_builder_expiration_timestamp() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let expiration = 1_234_567_890_u64;

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .expiration_timestamp_secs(expiration)
            .build()
            .unwrap();

        assert_eq!(fee_payer_txn.raw_txn.expiration_timestamp_secs, expiration);
    }

    #[test]
    fn test_builder_expiration_from_now() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(TransactionPayload::EntryFunction(
                EntryFunction::apt_transfer(recipient, 1000).unwrap(),
            ))
            .chain_id(ChainId::testnet())
            .expiration_from_now(60)
            .build()
            .unwrap();

        // Expiration should be roughly now + 60 seconds
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert!(fee_payer_txn.raw_txn.expiration_timestamp_secs >= now);
        assert!(fee_payer_txn.raw_txn.expiration_timestamp_secs <= now + 65);
    }

    #[test]
    fn test_builder_default() {
        let builder = SponsoredTransactionBuilder::default();
        assert!(builder.sender_address.is_none());
        assert!(builder.sequence_number.is_none());
        assert!(builder.fee_payer_address.is_none());
        assert!(builder.payload.is_none());
        assert!(builder.chain_id.is_none());
        // Default values are set via SponsoredTransactionBuilder::new()
        // not via Default::default() which initializes to Rust defaults (0)
        // Let's just check the builder is properly created
    }

    #[test]
    fn test_builder_new_defaults() {
        let builder = SponsoredTransactionBuilder::new();
        assert!(builder.sender_address.is_none());
        assert!(builder.sequence_number.is_none());
        assert!(builder.fee_payer_address.is_none());
        assert!(builder.payload.is_none());
        assert!(builder.chain_id.is_none());
        assert_eq!(builder.max_gas_amount, DEFAULT_MAX_GAS_AMOUNT);
        assert_eq!(builder.gas_unit_price, DEFAULT_GAS_UNIT_PRICE);
    }

    #[test]
    fn test_builder_debug() {
        let builder = SponsoredTransactionBuilder::new().sender(AccountAddress::ONE);
        let debug = format!("{builder:?}");
        assert!(debug.contains("SponsoredTransactionBuilder"));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_partially_signed_with_secondary_signers() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let secondary = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // Build with secondary signer
        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(0)
            .secondary_signer(secondary.address())
            .fee_payer(fee_payer.address())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let mut partially_signed = PartiallySigned::new(fee_payer_txn);

        // Need all three signatures
        assert!(!partially_signed.is_complete());

        partially_signed.sign_as_sender(&sender).unwrap();
        assert!(!partially_signed.is_complete());

        partially_signed.sign_as_secondary(0, &secondary).unwrap();
        assert!(!partially_signed.is_complete());

        partially_signed.sign_as_fee_payer(&fee_payer).unwrap();
        assert!(partially_signed.is_complete());

        let signed = partially_signed.finalize().unwrap();
        assert_eq!(signed.raw_txn.sender, sender.address());
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_partially_signed_secondary_index_out_of_bounds() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let secondary = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // No secondary signers in the transaction
        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(0)
            .fee_payer(fee_payer.address())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let mut partially_signed = PartiallySigned::new(fee_payer_txn);

        // Try to sign as secondary at index 0 (out of bounds because no secondary signers)
        let result = partially_signed.sign_as_secondary(0, &secondary);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("out of bounds"));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_partially_signed_finalize_missing_secondary() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let fee_payer = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        // Build with secondary signer but don't sign it
        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(0)
            .secondary_signer(AccountAddress::from_hex("0x5").unwrap())
            .fee_payer(fee_payer.address())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let mut partially_signed = PartiallySigned::new(fee_payer_txn);

        // Sign sender and fee payer but not secondary
        partially_signed.sign_as_sender(&sender).unwrap();
        partially_signed.sign_as_fee_payer(&fee_payer).unwrap();

        // Should fail because secondary is missing
        let result = partially_signed.finalize();
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("secondary signer"));
    }

    #[cfg(feature = "ed25519")]
    #[test]
    fn test_sponsor_with_gas() {
        use crate::account::Ed25519Account;

        let sender = Ed25519Account::generate();
        let sponsor = Ed25519Account::generate();
        let recipient = AccountAddress::from_hex("0x123").unwrap();

        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let signed_txn = sponsor
            .sponsor_with_gas(&sender, 0, payload.into(), ChainId::testnet(), 50000, 200)
            .unwrap();

        assert_eq!(signed_txn.raw_txn.sender, sender.address());
        assert_eq!(signed_txn.raw_txn.max_gas_amount, 50000);
        assert_eq!(signed_txn.raw_txn.gas_unit_price, 200);
    }

    #[test]
    fn test_partially_signed_debug() {
        let recipient = AccountAddress::from_hex("0x123").unwrap();
        let payload = EntryFunction::apt_transfer(recipient, 1000).unwrap();

        let fee_payer_txn = SponsoredTransactionBuilder::new()
            .sender(AccountAddress::ONE)
            .sequence_number(0)
            .fee_payer(AccountAddress::from_hex("0x3").unwrap())
            .payload(payload.into())
            .chain_id(ChainId::testnet())
            .build()
            .unwrap();

        let partially_signed = PartiallySigned::new(fee_payer_txn);
        let debug = format!("{partially_signed:?}");
        assert!(debug.contains("PartiallySigned"));
    }
}