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
//! End-to-end tests against localnet or testnet.
//!
//! These tests require a running Aptos node and are only compiled when
//! the `e2e` feature is enabled.
//!
//! ## Running the tests
//!
//! ### Option 1: Using the convenience script
//! ```bash
//! ./scripts/run-e2e.sh
//! ```
//!
//! ### Option 2: Manual setup
//! ```bash
//! # In one terminal, start localnet:
//! aptos node run-localnet --with-faucet
//!
//! # In another terminal, run tests:
//! cargo test -p aptos-sdk --features "e2e,full"
//! ```
//!
//! ### Option 3: Using custom node URLs
//! ```bash
//! export APTOS_LOCAL_NODE_URL=http://127.0.0.1:8080/v1
//! export APTOS_LOCAL_FAUCET_URL=http://127.0.0.1:8081
//! cargo test -p aptos-sdk --features "e2e,full"
//! ```
//!
//! ## Test Categories
//!
//! - **account_tests**: Account creation, funding, balance queries
//! - **transfer_tests**: APT transfers between accounts
//! - **view_tests**: View function calls
//! - **transaction_tests**: Transaction building, signing, submission
//! - **multi_signer_tests**: Multi-agent and fee payer transactions
//! - **state_tests**: Resource and state queries

use aptos_sdk::{Aptos, AptosConfig};
use std::env;

/// Gets the configuration for E2E tests.
fn get_test_config() -> AptosConfig {
    if let Ok(node_url) = env::var("APTOS_LOCAL_NODE_URL") {
        AptosConfig::custom(&node_url)
            .unwrap()
            .with_faucet_url(
                &env::var("APTOS_LOCAL_FAUCET_URL")
                    .unwrap_or_else(|_| "http://127.0.0.1:8081".to_string()),
            )
            .unwrap()
    } else {
        AptosConfig::local()
    }
}

/// Helper to wait for transaction finality
async fn wait_for_finality() {
    tokio::time::sleep(std::time::Duration::from_secs(2)).await;
}

// =============================================================================
// Account Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod account_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_create_and_fund_account() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create account
        let account = Ed25519Account::generate();
        println!("Created account: {}", account.address());

        // Fund account
        let txn_hashes = aptos
            .fund_account(account.address(), 100_000_000)
            .await
            .expect("failed to fund account");
        println!("Funded with txns: {:?}", txn_hashes);

        wait_for_finality().await;

        // Check balance
        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("failed to get balance");
        assert!(balance > 0, "balance should be > 0");
        println!("Balance: {} octas", balance);
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_create_funded_account_helper() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Use helper method
        let account = aptos
            .create_funded_account(50_000_000)
            .await
            .expect("failed to create funded account");

        println!("Created funded account: {}", account.address());

        wait_for_finality().await;

        let balance = aptos
            .get_balance(account.address())
            .await
            .expect("failed to get balance");
        assert!(balance > 0, "balance should be > 0");
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_sequence_number() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        let seq_num = aptos
            .get_sequence_number(account.address())
            .await
            .expect("failed to get sequence number");

        println!("Sequence number: {}", seq_num);
        // New account should have sequence number 0
        assert_eq!(seq_num, 0);
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_account_not_found() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Random unfunded account
        let account = Ed25519Account::generate();

        let result = aptos.get_sequence_number(account.address()).await;

        // Should get an error for non-existent account
        assert!(result.is_err() || result.unwrap() == 0);
    }
}

// =============================================================================
// Transfer Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod transfer_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_transfer_apt() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create and fund sender
        let sender = aptos
            .create_funded_account(200_000_000)
            .await
            .expect("failed to create sender");
        println!("Sender: {}", sender.address());

        // Create recipient
        let recipient = Ed25519Account::generate();
        println!("Recipient: {}", recipient.address());

        // Transfer
        let result = aptos
            .transfer_apt(&sender, recipient.address(), 10_000_000)
            .await
            .expect("failed to transfer");

        let success = result.data.get("success").and_then(|v| v.as_bool());
        assert_eq!(success, Some(true), "transfer should succeed");
        println!("Transfer successful!");

        wait_for_finality().await;

        // Check recipient balance
        let balance = aptos
            .get_balance(recipient.address())
            .await
            .expect("failed to get balance");
        assert_eq!(
            balance, 10_000_000,
            "recipient should have transferred amount"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_multiple_transfers() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sender");

        // Transfer to multiple recipients
        let recipients: Vec<_> = (0..3).map(|_| Ed25519Account::generate()).collect();

        for (i, recipient) in recipients.iter().enumerate() {
            let result = aptos
                .transfer_apt(&sender, recipient.address(), 1_000_000 * (i as u64 + 1))
                .await
                .expect("failed to transfer");

            let success = result.data.get("success").and_then(|v| v.as_bool());
            assert_eq!(success, Some(true));
            println!("Transfer {} to {} successful", i + 1, recipient.address());
        }

        wait_for_finality().await;

        // Verify balances
        for (i, recipient) in recipients.iter().enumerate() {
            let balance = aptos.get_balance(recipient.address()).await.unwrap_or(0);
            let expected = 1_000_000 * (i as u64 + 1);
            assert_eq!(balance, expected, "recipient {} balance mismatch", i);
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_transfer_insufficient_balance() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(1_000_000)
            .await
            .expect("failed to create sender");

        let recipient = Ed25519Account::generate();

        // Try to transfer more than we have
        let result = aptos
            .transfer_apt(&sender, recipient.address(), 999_999_999_999)
            .await;

        // Should fail (either at simulation or execution)
        assert!(
            result.is_err() || {
                let r = result.unwrap();
                r.data.get("success").and_then(|v| v.as_bool()) == Some(false)
            }
        );
    }
}

// =============================================================================
// View Function Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod view_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_view_timestamp() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let result = aptos
            .view("0x1::timestamp::now_seconds", vec![], vec![])
            .await
            .expect("failed to call view function");

        assert!(!result.is_empty(), "should return a value");
        println!("Current timestamp: {:?}", result);

        // Parse the timestamp
        if let Some(timestamp) = result[0].as_str() {
            let ts: u64 = timestamp.parse().expect("should be a number");
            assert!(ts > 0, "timestamp should be > 0");
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_coin_balance() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Use view function to check balance
        let result = aptos
            .view(
                "0x1::coin::balance",
                vec!["0x1::aptos_coin::AptosCoin".to_string()],
                vec![serde_json::json!(account.address().to_string())],
            )
            .await
            .expect("failed to call view function");

        assert!(!result.is_empty());
        println!("Balance via view: {:?}", result);
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_account_exists() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Check if account exists
        let result = aptos
            .view(
                "0x1::account::exists_at",
                vec![],
                vec![serde_json::json!(account.address().to_string())],
            )
            .await
            .expect("failed to call view function");

        assert_eq!(result[0], serde_json::json!(true));
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_view_nonexistent_account() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let random_address = Ed25519Account::generate().address();
        println!("Random address: {}", random_address);

        let result = aptos
            .view(
                "0x1::account::exists_at",
                vec![],
                vec![serde_json::json!(random_address.to_string())],
            )
            .await
            .expect("failed to call view function");

        println!("Result: {:?}", result);
        // Note: Modern Aptos chains use implicit accounts (AIP-42), so all addresses
        // are considered to "exist" with sequence_number=0 until a transaction is made.
        // The view function returns true for all addresses now.
        assert_eq!(result[0], serde_json::json!(true));
    }
}

// =============================================================================
// Transaction Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod transaction_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::{EntryFunction, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_build_sign_submit_transaction() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        let recipient = Ed25519Account::generate();

        // Build transaction manually
        let payload = EntryFunction::apt_transfer(recipient.address(), 1000).unwrap();
        let raw_txn = aptos
            .build_transaction(&sender, payload.into())
            .await
            .expect("failed to build transaction");

        // Sign
        let signed = sign_transaction(&raw_txn, &sender).expect("failed to sign");

        // Debug: Print BCS bytes
        let bcs_bytes = signed.to_bcs().expect("failed to serialize");
        println!("BCS bytes ({} total):", bcs_bytes.len());
        println!(
            "First 100 bytes: {}",
            const_hex::encode(&bcs_bytes[..100.min(bcs_bytes.len())])
        );
        println!(
            "Last 100 bytes: {}",
            const_hex::encode(&bcs_bytes[bcs_bytes.len().saturating_sub(100)..])
        );
        println!(
            "Authenticator variant (byte at offset {}): {}",
            bcs_bytes.len() - 97,
            bcs_bytes.get(bcs_bytes.len() - 97).unwrap_or(&0)
        );

        // Submit
        let result = aptos
            .submit_and_wait(&signed, None)
            .await
            .expect("failed to submit");

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

    #[tokio::test]
    #[ignore]
    async fn e2e_simulate_transaction() {
        use aptos_sdk::account::Account;
        use aptos_sdk::transaction::authenticator::{Ed25519PublicKey, Ed25519Signature};
        use aptos_sdk::transaction::{SignedTransaction, TransactionAuthenticator};

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        let payload =
            EntryFunction::apt_transfer(Ed25519Account::generate().address(), 1000).unwrap();

        let raw_txn = aptos
            .build_transaction(&account, payload.into())
            .await
            .expect("failed to build transaction");

        // For simulation, we need to create a transaction with a zeroed signature
        // (the API rejects transactions with valid signatures for simulation)
        let auth = TransactionAuthenticator::Ed25519 {
            public_key: Ed25519PublicKey(account.public_key_bytes().try_into().unwrap()),
            signature: Ed25519Signature([0u8; 64]),
        };
        let signed = SignedTransaction::new(raw_txn, auth);

        // Simulate
        let result = aptos
            .simulate_transaction(&signed)
            .await
            .expect("failed to simulate");

        assert!(!result.data.is_empty(), "simulation should return results");

        let success = result.data[0].get("success").and_then(|v| v.as_bool());
        assert_eq!(success, Some(true), "simulation should succeed");

        let gas_used = result.data[0].get("gas_used").and_then(|v| v.as_str());
        println!("Simulated gas used: {:?}", gas_used);
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_transaction_by_hash() {
        use aptos_sdk::types::HashValue;

        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let sender = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        // Do a transfer
        let result = aptos
            .transfer_apt(&sender, Ed25519Account::generate().address(), 1000)
            .await
            .expect("failed to transfer");

        let hash_str = result.data.get("hash").and_then(|v| v.as_str()).unwrap();
        println!("Transaction hash: {}", hash_str);

        wait_for_finality().await;

        // Parse the hash and get transaction by hash (via fullnode client)
        let hash = HashValue::from_hex(hash_str).expect("invalid hash");
        let txn = aptos.fullnode().get_transaction_by_hash(&hash).await;
        assert!(txn.is_ok(), "should be able to get transaction by hash");
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_transaction_expiration() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        // Build transaction with very short expiration (already expired)
        let payload =
            EntryFunction::apt_transfer(Ed25519Account::generate().address(), 1000).unwrap();
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = aptos_sdk::transaction::TransactionBuilder::new()
            .sender(account.address())
            .sequence_number(0)
            .payload(payload.into())
            .chain_id(chain_id)
            .expiration_timestamp_secs(1) // Already expired
            .build()
            .expect("failed to build");

        let signed = sign_transaction(&raw_txn, &account).expect("failed to sign");

        // Submission should fail due to expiration
        let result = aptos.submit_and_wait(&signed, None).await;
        assert!(result.is_err(), "expired transaction should fail");
    }
}

// =============================================================================
// Ledger/Chain Info Tests
// =============================================================================

#[cfg(feature = "ed25519")]
mod ledger_tests {
    use super::*;

    #[tokio::test]
    #[ignore]
    async fn e2e_get_ledger_info() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let ledger_info = aptos
            .ledger_info()
            .await
            .expect("failed to get ledger info");

        println!(
            "Ledger version: {}",
            ledger_info.version().expect("failed to parse version")
        );
        println!(
            "Block height: {}",
            ledger_info.height().expect("failed to parse height")
        );
        println!(
            "Epoch: {}",
            ledger_info.epoch_num().expect("failed to parse epoch")
        );

        assert!(
            ledger_info.version().expect("failed to parse version") > 0,
            "ledger version should be > 0"
        );
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_chain_id_from_ledger() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Just verify we can get ledger info
        let _ledger_info = aptos
            .ledger_info()
            .await
            .expect("failed to get ledger info");

        // Chain ID should be set
        assert!(aptos.chain_id().id() > 0);
        println!("Client chain ID: {}", aptos.chain_id().id());
    }
}

// =============================================================================
// Multi-Signer Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod multi_signer_tests {
    use super::*;
    use aptos_sdk::account::{Account, Ed25519Account};
    use aptos_sdk::transaction::{
        EntryFunction, TransactionBuilder,
        builder::{sign_fee_payer_transaction, sign_multi_agent_transaction},
        types::{FeePayerRawTransaction, MultiAgentRawTransaction},
    };

    #[tokio::test]
    #[ignore]
    async fn e2e_fee_payer_transaction() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create sender with minimal funds (just for account creation)
        let sender = aptos
            .create_funded_account(1_000)
            .await
            .expect("failed to create sender");

        // Create fee payer with lots of funds
        let fee_payer = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create fee payer");

        let recipient = Ed25519Account::generate();

        println!("Sender: {}", sender.address());
        println!("Fee payer: {}", fee_payer.address());
        println!("Recipient: {}", recipient.address());

        // Build the fee payer transaction
        let payload = EntryFunction::apt_transfer(recipient.address(), 500).unwrap();

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .unwrap_or(0);
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let fee_payer_txn = FeePayerRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![],
            fee_payer_address: fee_payer.address(),
        };

        let signed = sign_fee_payer_transaction(&fee_payer_txn, &sender, &[], &fee_payer)
            .expect("failed to sign");

        // Submit
        let result = aptos.submit_and_wait(&signed, None).await;

        // This may or may not work depending on localnet support for fee payer
        match result {
            Ok(r) => {
                println!("Fee payer transaction result: {:?}", r.data);
            }
            Err(e) => {
                println!("Fee payer transaction failed (may not be supported): {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_multi_agent_transaction() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create primary sender
        let sender = aptos
            .create_funded_account(200_000_000)
            .await
            .expect("failed to create sender");

        // Create secondary signer
        let secondary = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create secondary");

        println!("Sender: {}", sender.address());
        println!("Secondary: {}", secondary.address());

        // Note: Most simple transactions don't need multi-agent
        // This is just demonstrating the signing flow
        let payload =
            EntryFunction::apt_transfer(Ed25519Account::generate().address(), 1000).unwrap();

        let sender_seq = aptos
            .get_sequence_number(sender.address())
            .await
            .unwrap_or(0);
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(sender.address())
            .sequence_number(sender_seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let multi_agent_txn = MultiAgentRawTransaction {
            raw_txn,
            secondary_signer_addresses: vec![secondary.address()],
        };

        // Sign with both accounts
        let secondary_ref: &dyn Account = &secondary;
        let signed = sign_multi_agent_transaction(&multi_agent_txn, &sender, &[secondary_ref])
            .expect("failed to sign");

        // Submit
        let result = aptos.submit_and_wait(&signed, None).await;

        match result {
            Ok(r) => {
                println!("Multi-agent transaction result: {:?}", r.data);
            }
            Err(e) => {
                println!("Multi-agent transaction error: {}", e);
            }
        }
    }
}

// =============================================================================
// Multi-Key Account Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "secp256k1", feature = "faucet"))]
mod multi_key_e2e_tests {
    use super::*;
    use aptos_sdk::account::{AnyPrivateKey, MultiKeyAccount};
    use aptos_sdk::crypto::{Ed25519PrivateKey, Secp256k1PrivateKey};
    use aptos_sdk::transaction::{EntryFunction, TransactionBuilder, builder::sign_transaction};

    #[tokio::test]
    #[ignore]
    async fn e2e_multi_key_account_transfer() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create a 2-of-3 multi-key account with mixed types
        let ed_key1 = Ed25519PrivateKey::generate();
        let secp_key = Secp256k1PrivateKey::generate();
        let ed_key2 = Ed25519PrivateKey::generate();

        let keys = vec![
            AnyPrivateKey::ed25519(ed_key1),
            AnyPrivateKey::secp256k1(secp_key),
            AnyPrivateKey::ed25519(ed_key2),
        ];

        let multi_key_account = MultiKeyAccount::new(keys, 2).unwrap();
        println!("Multi-key account: {}", multi_key_account.address());

        // Fund the multi-key account
        aptos
            .fund_account(multi_key_account.address(), 100_000_000)
            .await
            .expect("failed to fund");

        wait_for_finality().await;

        // Check balance
        let balance = aptos
            .get_balance(multi_key_account.address())
            .await
            .unwrap_or(0);
        println!("Multi-key balance: {}", balance);

        // Build and sign a transfer
        let recipient = aptos_sdk::account::Ed25519Account::generate();
        let payload = EntryFunction::apt_transfer(recipient.address(), 1_000_000).unwrap();

        let seq = aptos
            .get_sequence_number(multi_key_account.address())
            .await
            .unwrap_or(0);
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        let raw_txn = TransactionBuilder::new()
            .sender(multi_key_account.address())
            .sequence_number(seq)
            .payload(payload.into())
            .chain_id(chain_id)
            .max_gas_amount(100_000)
            .gas_unit_price(100)
            .build()
            .expect("failed to build");

        let signed =
            sign_transaction(&raw_txn, &multi_key_account).expect("failed to sign with multi-key");

        // Submit
        let result = aptos.submit_and_wait(&signed, None).await;

        match result {
            Ok(r) => {
                let success = r.data.get("success").and_then(|v| v.as_bool());
                println!("Multi-key transaction success: {:?}", success);
            }
            Err(e) => {
                // Multi-key might not be supported on all networks
                println!("Multi-key transaction error (may not be supported): {}", e);
            }
        }
    }
}

// =============================================================================
// Resource/State Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod state_tests {
    use super::*;

    #[tokio::test]
    #[ignore]
    async fn e2e_get_account_resource() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Get the Account resource via fullnode client
        let resource = aptos
            .fullnode()
            .get_account_resource(account.address(), "0x1::account::Account")
            .await;

        match resource {
            Ok(r) => {
                println!("Account resource: {:?}", r.data);
            }
            Err(e) => {
                println!("Failed to get resource: {}", e);
            }
        }
    }

    #[tokio::test]
    #[ignore]
    async fn e2e_get_coin_store_resource() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        let account = aptos
            .create_funded_account(100_000_000)
            .await
            .expect("failed to create account");

        wait_for_finality().await;

        // Get the CoinStore resource for APT
        let resource = aptos
            .fullnode()
            .get_account_resource(
                account.address(),
                "0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin>",
            )
            .await;

        match resource {
            Ok(r) => {
                println!("CoinStore resource: {:?}", r.data);
            }
            Err(e) => {
                println!("Failed to get CoinStore: {}", e);
            }
        }
    }
}

// =============================================================================
// SingleKey Account Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod single_key_tests {
    use aptos_sdk::account::Ed25519SingleKeyAccount;

    #[tokio::test]
    #[ignore]
    async fn e2e_single_key_account_address_derivation() {
        // Test that SingleKey accounts derive addresses correctly
        let account = Ed25519SingleKeyAccount::generate();

        // Address should not be zero
        assert!(!account.address().is_zero());

        // Same key should produce same address
        let address1 = account.address();
        let address2 = account.address();
        assert_eq!(address1, address2);

        println!("SingleKey account address: {}", account.address());
    }
}

// =============================================================================
// Secp256k1 Account Tests
// =============================================================================

#[cfg(all(feature = "secp256k1", feature = "faucet"))]
mod secp256k1_tests {
    use aptos_sdk::account::Secp256k1Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_secp256k1_account_address_derivation() {
        // Test that Secp256k1 accounts derive addresses correctly
        let account = Secp256k1Account::generate();

        // Address should not be zero
        assert!(!account.address().is_zero());

        // Same key should produce same address
        let address1 = account.address();
        let address2 = account.address();
        assert_eq!(address1, address2);

        println!("Secp256k1 account address: {}", account.address());
    }
}

// =============================================================================
// Batch Transaction Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod batch_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;
    use aptos_sdk::transaction::{InputEntryFunctionData, TransactionBatchBuilder};

    #[tokio::test]
    #[ignore]
    async fn e2e_batch_build() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create sender
        let sender = aptos
            .create_funded_account(500_000_000)
            .await
            .expect("failed to create sender");

        let recipient1 = Ed25519Account::generate();
        let recipient2 = Ed25519Account::generate();

        wait_for_finality().await;

        // Get sequence number and resolve chain ID
        let seq_num = aptos
            .fullnode()
            .get_sequence_number(sender.address())
            .await
            .expect("failed to get seq num");
        let chain_id = aptos
            .ensure_chain_id()
            .await
            .expect("failed to resolve chain id");

        // Build batch using TransactionBatchBuilder
        let payload1 = InputEntryFunctionData::transfer_apt(recipient1.address(), 10_000_000)
            .expect("failed to build payload 1");
        let payload2 = InputEntryFunctionData::transfer_apt(recipient2.address(), 10_000_000)
            .expect("failed to build payload 2");

        let batch = TransactionBatchBuilder::new()
            .sender(sender.address())
            .starting_sequence_number(seq_num)
            .chain_id(chain_id)
            .add_payload(payload1)
            .add_payload(payload2)
            .build_and_sign(&sender)
            .expect("failed to build batch");

        println!("Created batch of {} transactions", batch.len());
        assert_eq!(batch.len(), 2);
    }
}

// =============================================================================
// Additional Balance Tests
// =============================================================================

#[cfg(all(feature = "ed25519", feature = "faucet"))]
mod balance_tests {
    use super::*;
    use aptos_sdk::account::Ed25519Account;

    #[tokio::test]
    #[ignore]
    async fn e2e_balance_multiple_accounts() {
        let config = get_test_config();
        let aptos = Aptos::new(config).expect("failed to create client");

        // Create multiple accounts
        let accounts: Vec<_> = (0..3).map(|_| Ed25519Account::generate()).collect();

        // Fund all accounts
        for account in &accounts {
            aptos
                .fund_account(account.address(), 50_000_000)
                .await
                .expect("failed to fund account");
        }

        wait_for_finality().await;

        // Check all balances
        for (i, account) in accounts.iter().enumerate() {
            let balance = aptos
                .get_balance(account.address())
                .await
                .expect("failed to get balance");
            assert!(
                balance >= 50_000_000,
                "Account {} should have at least 50M octas",
                i
            );
            println!("Account {}: {} octas", i, balance);
        }
    }
}