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
//! GraphQL indexer client.
//!
//! This module provides a client for querying the Aptos Indexer GraphQL API.
//! The indexer provides access to indexed blockchain data including tokens,
//! events, transaction history, and more.
//!
//! # Example
//!
//! ```rust,no_run
//! use aptos_sdk::api::{IndexerClient, PaginationParams};
//! use aptos_sdk::config::AptosConfig;
//! use aptos_sdk::types::AccountAddress;
//!
//! #[tokio::main]
//! async fn main() -> anyhow::Result<()> {
//!     let config = AptosConfig::testnet();
//!     let client = IndexerClient::new(&config)?;
//!     
//!     // Get fungible asset balances
//!     let balances = client.get_fungible_asset_balances(AccountAddress::ONE).await?;
//!     
//!     // Get account tokens with pagination
//!     let tokens = client.get_account_tokens_paginated(
//!         AccountAddress::ONE,
//!         Some(PaginationParams { limit: 10, offset: 0 }),
//!     ).await?;
//!     
//!     Ok(())
//! }
//! ```

use crate::config::AptosConfig;
use crate::error::{AptosError, AptosResult};
use crate::retry::{RetryConfig, RetryExecutor};
use crate::types::AccountAddress;
use reqwest::Client;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use url::Url;

/// Maximum indexer response size: 10 MB.
const MAX_INDEXER_RESPONSE_SIZE: usize = 10 * 1024 * 1024;

/// Client for the Aptos indexer GraphQL API.
///
/// The indexer provides access to indexed blockchain data including
/// tokens, events, and transaction history. Queries are automatically
/// retried with exponential backoff for transient failures.
///
/// # Example
///
/// ```rust,no_run
/// use aptos_sdk::api::IndexerClient;
/// use aptos_sdk::config::AptosConfig;
///
/// #[tokio::main]
/// async fn main() -> anyhow::Result<()> {
///     let config = AptosConfig::testnet();
///     let client = IndexerClient::new(&config)?;
///     // Use the client for GraphQL queries
///     Ok(())
/// }
/// ```
#[derive(Debug, Clone)]
pub struct IndexerClient {
    indexer_url: Url,
    client: Client,
    retry_config: Arc<RetryConfig>,
}

/// GraphQL request body.
#[derive(Debug, Serialize)]
struct GraphQLRequest {
    query: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    variables: Option<serde_json::Value>,
}

/// GraphQL response body.
#[derive(Debug, Deserialize)]
struct GraphQLResponse<T> {
    data: Option<T>,
    errors: Option<Vec<GraphQLError>>,
}

/// GraphQL error.
#[derive(Debug, Deserialize)]
struct GraphQLError {
    message: String,
}

impl IndexerClient {
    /// Creates a new indexer client.
    ///
    /// # TLS Security
    ///
    /// This client uses `reqwest` with its default TLS configuration, which
    /// validates server certificates against the system's certificate store.
    /// All Aptos indexer endpoints use HTTPS with valid certificates.
    ///
    /// # Errors
    ///
    /// Returns an error if the indexer URL is not configured in the config, or if the HTTP client
    /// fails to build (e.g., invalid TLS configuration).
    pub fn new(config: &AptosConfig) -> AptosResult<Self> {
        let indexer_url = config
            .indexer_url()
            .cloned()
            .ok_or_else(|| AptosError::Config("indexer URL not configured".into()))?;

        let pool = config.pool_config();

        // SECURITY: TLS certificate validation is enabled by default via reqwest.
        let mut builder = Client::builder()
            .timeout(config.timeout)
            .pool_max_idle_per_host(pool.max_idle_per_host.unwrap_or(usize::MAX))
            .pool_idle_timeout(pool.idle_timeout)
            .tcp_nodelay(pool.tcp_nodelay);

        if let Some(keepalive) = pool.tcp_keepalive {
            builder = builder.tcp_keepalive(keepalive);
        }

        let client = builder.build().map_err(AptosError::Http)?;

        let retry_config = Arc::new(config.retry_config().clone());

        Ok(Self {
            indexer_url,
            client,
            retry_config,
        })
    }

    /// Creates an indexer client with a custom URL.
    ///
    /// # Errors
    ///
    /// Returns an error if the URL cannot be parsed.
    pub fn with_url(url: &str) -> AptosResult<Self> {
        let indexer_url = Url::parse(url)?;
        // SECURITY: Validate URL scheme to prevent SSRF via dangerous protocols
        crate::config::validate_url_scheme(&indexer_url)?;
        let client = Client::new();
        Ok(Self {
            indexer_url,
            client,
            retry_config: Arc::new(RetryConfig::default()),
        })
    }

    /// Executes a GraphQL query.
    ///
    /// # Errors
    ///
    /// Returns an error if the HTTP request fails, the API returns an error status code,
    /// the response cannot be parsed as JSON, the GraphQL query contains errors, or the
    /// response data is missing.
    pub async fn query<T: for<'de> Deserialize<'de> + Send + 'static>(
        &self,
        query: &str,
        variables: Option<serde_json::Value>,
    ) -> AptosResult<T> {
        let request = GraphQLRequest {
            query: query.to_string(),
            variables,
        };

        let client = self.client.clone();
        let url = self.indexer_url.clone();
        let retry_config = self.retry_config.clone();

        let executor = RetryExecutor::from_shared(retry_config);
        executor
            .execute(|| {
                let client = client.clone();
                let url = url.clone();
                let request = GraphQLRequest {
                    query: request.query.clone(),
                    variables: request.variables.clone(),
                };
                async move {
                    let response = client.post(url.as_str()).json(&request).send().await?;

                    if response.status().is_success() {
                        // SECURITY: Stream body with size limit to prevent OOM
                        // from malicious responses (including chunked encoding).
                        let bytes = crate::config::read_response_bounded(
                            response,
                            MAX_INDEXER_RESPONSE_SIZE,
                        )
                        .await?;
                        let graphql_response: GraphQLResponse<T> = serde_json::from_slice(&bytes)?;

                        if let Some(errors) = graphql_response.errors {
                            // Build error message directly without intermediate Vec
                            let mut message = String::new();
                            for (i, e) in errors.iter().enumerate() {
                                if i > 0 {
                                    message.push_str("; ");
                                }
                                message.push_str(&e.message);
                            }
                            return Err(AptosError::Api {
                                status_code: 400,
                                message,
                                error_code: Some("GRAPHQL_ERROR".into()),
                                vm_error_code: None,
                            });
                        }

                        graphql_response.data.ok_or_else(|| {
                            AptosError::Internal("no data in GraphQL response".into())
                        })
                    } else {
                        let status = response.status();
                        let body = response.text().await.unwrap_or_default();
                        Err(AptosError::api(status.as_u16(), body))
                    }
                }
            })
            .await
    }

    /// Gets the account's fungible asset balances.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_fungible_asset_balances(
        &self,
        address: AccountAddress,
    ) -> AptosResult<Vec<FungibleAssetBalance>> {
        #[derive(Deserialize)]
        struct Response {
            current_fungible_asset_balances: Vec<FungibleAssetBalance>,
        }

        let query = r"
            query GetFungibleAssetBalances($address: String!) {
                current_fungible_asset_balances(
                    where: { owner_address: { _eq: $address } }
                ) {
                    asset_type
                    amount
                    metadata {
                        name
                        symbol
                        decimals
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string()
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.current_fungible_asset_balances)
    }

    /// Gets the account's token (NFT) holdings.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_account_tokens(
        &self,
        address: AccountAddress,
    ) -> AptosResult<Vec<TokenBalance>> {
        #[derive(Deserialize)]
        struct Response {
            current_token_ownerships_v2: Vec<TokenBalance>,
        }

        let query = r"
            query GetAccountTokens($address: String!) {
                current_token_ownerships_v2(
                    where: { owner_address: { _eq: $address }, amount: { _gt: 0 } }
                ) {
                    token_data_id
                    amount
                    current_token_data {
                        token_name
                        description
                        token_uri
                        current_collection {
                            collection_name
                        }
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string()
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.current_token_ownerships_v2)
    }

    /// Gets recent transactions for an account.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_account_transactions(
        &self,
        address: AccountAddress,
        limit: Option<u32>,
    ) -> AptosResult<Vec<Transaction>> {
        #[derive(Deserialize)]
        struct Response {
            account_transactions: Vec<Transaction>,
        }

        let query = r"
            query GetAccountTransactions($address: String!, $limit: Int!) {
                account_transactions(
                    where: { account_address: { _eq: $address } }
                    order_by: { transaction_version: desc }
                    limit: $limit
                ) {
                    transaction_version
                    coin_activities {
                        activity_type
                        amount
                        coin_type
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string(),
            "limit": limit.unwrap_or(25)
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.account_transactions)
    }
}

/// Fungible asset balance from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct FungibleAssetBalance {
    /// The asset type.
    pub asset_type: String,
    /// The balance amount.
    pub amount: String,
    /// Asset metadata.
    pub metadata: Option<FungibleAssetMetadata>,
}

/// Fungible asset metadata from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct FungibleAssetMetadata {
    /// Asset name.
    pub name: String,
    /// Asset symbol.
    pub symbol: String,
    /// Number of decimals.
    pub decimals: u8,
}

/// Token (NFT) balance from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenBalance {
    /// The token data ID.
    pub token_data_id: String,
    /// Amount owned.
    pub amount: String,
    /// Token data.
    pub current_token_data: Option<TokenData>,
}

/// Token data from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct TokenData {
    /// Token name.
    pub token_name: String,
    /// Token description.
    pub description: String,
    /// Token URI.
    pub token_uri: String,
    /// Collection data.
    pub current_collection: Option<CollectionData>,
}

/// Collection data from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct CollectionData {
    /// Collection name.
    pub collection_name: String,
}

/// Transaction from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct Transaction {
    /// Transaction version.
    pub transaction_version: String,
    /// Coin activities in this transaction.
    pub coin_activities: Vec<CoinActivity>,
}

/// Coin activity from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct CoinActivity {
    /// Activity type.
    pub activity_type: String,
    /// Amount.
    pub amount: Option<String>,
    /// Coin type.
    pub coin_type: String,
}

/// Pagination parameters for indexer queries.
#[derive(Debug, Clone, Default)]
pub struct PaginationParams {
    /// Maximum number of items to return.
    pub limit: u32,
    /// Number of items to skip.
    pub offset: u32,
}

impl PaginationParams {
    /// Creates new pagination parameters.
    pub fn new(limit: u32, offset: u32) -> Self {
        Self { limit, offset }
    }

    /// Creates pagination for the first page.
    pub fn first(limit: u32) -> Self {
        Self { limit, offset: 0 }
    }
}

/// A paginated response.
#[derive(Debug, Clone)]
pub struct Page<T> {
    /// The items in this page.
    pub items: Vec<T>,
    /// Whether there are more items.
    pub has_more: bool,
    /// Total count if available.
    pub total_count: Option<u64>,
}

/// Event from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct Event {
    /// Event sequence number.
    pub sequence_number: String,
    /// Event type.
    #[serde(rename = "type")]
    pub event_type: String,
    /// Event data.
    pub data: serde_json::Value,
    /// Transaction version that emitted this event.
    pub transaction_version: Option<String>,
    /// Account address associated with the event.
    pub account_address: Option<String>,
    /// Creation number.
    pub creation_number: Option<String>,
}

/// Collection data from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct Collection {
    /// Collection address.
    pub collection_id: String,
    /// Collection name.
    pub collection_name: String,
    /// Creator address.
    pub creator_address: String,
    /// Current supply.
    pub current_supply: String,
    /// Maximum supply (0 = unlimited).
    pub max_supply: Option<String>,
    /// Collection URI.
    pub uri: String,
    /// Description.
    pub description: String,
}

/// Coin balance from the indexer (legacy coin module).
#[derive(Debug, Clone, Deserialize)]
pub struct CoinBalance {
    /// Coin type.
    pub coin_type: String,
    /// Balance amount.
    pub amount: String,
}

/// Processor status from the indexer.
#[derive(Debug, Clone, Deserialize)]
pub struct ProcessorStatus {
    /// Processor name.
    pub processor: String,
    /// Last successfully processed version.
    pub last_success_version: u64,
    /// Last updated timestamp.
    pub last_updated: Option<String>,
}

impl IndexerClient {
    // ... existing methods ...

    /// Gets the account's token (NFT) holdings with pagination.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_account_tokens_paginated(
        &self,
        address: AccountAddress,
        pagination: Option<PaginationParams>,
    ) -> AptosResult<Page<TokenBalance>> {
        #[derive(Deserialize)]
        struct AggregateCount {
            count: u64,
        }

        #[derive(Deserialize)]
        struct Aggregate {
            aggregate: Option<AggregateCount>,
        }

        #[derive(Deserialize)]
        struct Response {
            current_token_ownerships_v2: Vec<TokenBalance>,
            current_token_ownerships_v2_aggregate: Aggregate,
        }

        let pagination = pagination.unwrap_or(PaginationParams {
            limit: 25,
            offset: 0,
        });

        let query = r"
            query GetAccountTokens($address: String!, $limit: Int!, $offset: Int!) {
                current_token_ownerships_v2(
                    where: { owner_address: { _eq: $address }, amount: { _gt: 0 } }
                    limit: $limit
                    offset: $offset
                ) {
                    token_data_id
                    amount
                    current_token_data {
                        token_name
                        description
                        token_uri
                        current_collection {
                            collection_name
                        }
                    }
                }
                current_token_ownerships_v2_aggregate(
                    where: { owner_address: { _eq: $address }, amount: { _gt: 0 } }
                ) {
                    aggregate {
                        count
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string(),
            "limit": pagination.limit,
            "offset": pagination.offset
        });

        let response: Response = self.query(query, Some(variables)).await?;
        let total_count = response
            .current_token_ownerships_v2_aggregate
            .aggregate
            .map(|a| a.count);
        let has_more = total_count.is_some_and(|total| {
            (u64::from(pagination.offset) + response.current_token_ownerships_v2.len() as u64)
                < total
        });

        Ok(Page {
            items: response.current_token_ownerships_v2,
            has_more,
            total_count,
        })
    }

    /// Gets the account's transaction history with pagination.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_account_transactions_paginated(
        &self,
        address: AccountAddress,
        pagination: Option<PaginationParams>,
    ) -> AptosResult<Page<Transaction>> {
        #[derive(Deserialize)]
        struct AggregateCount {
            count: u64,
        }

        #[derive(Deserialize)]
        struct Aggregate {
            aggregate: Option<AggregateCount>,
        }

        #[derive(Deserialize)]
        struct Response {
            account_transactions: Vec<Transaction>,
            account_transactions_aggregate: Aggregate,
        }

        let pagination = pagination.unwrap_or(PaginationParams {
            limit: 25,
            offset: 0,
        });

        let query = r"
            query GetAccountTransactions($address: String!, $limit: Int!, $offset: Int!) {
                account_transactions(
                    where: { account_address: { _eq: $address } }
                    order_by: { transaction_version: desc }
                    limit: $limit
                    offset: $offset
                ) {
                    transaction_version
                    coin_activities {
                        activity_type
                        amount
                        coin_type
                    }
                }
                account_transactions_aggregate(
                    where: { account_address: { _eq: $address } }
                ) {
                    aggregate {
                        count
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string(),
            "limit": pagination.limit,
            "offset": pagination.offset
        });

        let response: Response = self.query(query, Some(variables)).await?;
        let total_count = response
            .account_transactions_aggregate
            .aggregate
            .map(|a| a.count);
        let has_more = total_count.is_some_and(|total| {
            (u64::from(pagination.offset) + response.account_transactions.len() as u64) < total
        });

        Ok(Page {
            items: response.account_transactions,
            has_more,
            total_count,
        })
    }

    /// Gets events by type.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_events_by_type(
        &self,
        event_type: &str,
        limit: Option<u32>,
    ) -> AptosResult<Vec<Event>> {
        #[derive(Deserialize)]
        struct Response {
            events: Vec<Event>,
        }

        let query = r"
            query GetEventsByType($type: String!, $limit: Int!) {
                events(
                    where: { type: { _eq: $type } }
                    order_by: { transaction_version: desc }
                    limit: $limit
                ) {
                    sequence_number
                    type
                    data
                    transaction_version
                    account_address
                    creation_number
                }
            }
        ";

        let variables = serde_json::json!({
            "type": event_type,
            "limit": limit.unwrap_or(25)
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.events)
    }

    /// Gets events involving an account.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_events_by_account(
        &self,
        address: AccountAddress,
        limit: Option<u32>,
    ) -> AptosResult<Vec<Event>> {
        #[derive(Deserialize)]
        struct Response {
            events: Vec<Event>,
        }

        let query = r"
            query GetEventsByAccount($address: String!, $limit: Int!) {
                events(
                    where: { account_address: { _eq: $address } }
                    order_by: { transaction_version: desc }
                    limit: $limit
                ) {
                    sequence_number
                    type
                    data
                    transaction_version
                    account_address
                    creation_number
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string(),
            "limit": limit.unwrap_or(25)
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.events)
    }

    /// Gets a collection by its address.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details),
    /// or if the collection is not found.
    pub async fn get_collection(
        &self,
        collection_address: AccountAddress,
    ) -> AptosResult<Collection> {
        #[derive(Deserialize)]
        struct Response {
            current_collections_v2: Vec<Collection>,
        }

        let query = r"
            query GetCollection($address: String!) {
                current_collections_v2(
                    where: { collection_id: { _eq: $address } }
                    limit: 1
                ) {
                    collection_id
                    collection_name
                    creator_address
                    current_supply
                    max_supply
                    uri
                    description
                }
            }
        ";

        let variables = serde_json::json!({
            "address": collection_address.to_string()
        });

        let response: Response = self.query(query, Some(variables)).await?;
        response
            .current_collections_v2
            .into_iter()
            .next()
            .ok_or_else(|| {
                AptosError::NotFound(format!("Collection not found: {collection_address}"))
            })
    }

    /// Gets tokens in a collection.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_collection_tokens(
        &self,
        collection_address: AccountAddress,
        pagination: Option<PaginationParams>,
    ) -> AptosResult<Page<TokenBalance>> {
        #[derive(Deserialize)]
        struct Response {
            current_token_ownerships_v2: Vec<TokenBalance>,
        }

        let pagination = pagination.unwrap_or(PaginationParams {
            limit: 25,
            offset: 0,
        });

        let query = r"
            query GetCollectionTokens($address: String!, $limit: Int!, $offset: Int!) {
                current_token_ownerships_v2(
                    where: { 
                        current_token_data: { 
                            current_collection: { 
                                collection_id: { _eq: $address } 
                            } 
                        }
                        amount: { _gt: 0 }
                    }
                    limit: $limit
                    offset: $offset
                ) {
                    token_data_id
                    amount
                    current_token_data {
                        token_name
                        description
                        token_uri
                        current_collection {
                            collection_name
                        }
                    }
                }
            }
        ";

        let variables = serde_json::json!({
            "address": collection_address.to_string(),
            "limit": pagination.limit,
            "offset": pagination.offset
        });

        let response: Response = self.query(query, Some(variables)).await?;
        let items_count = response.current_token_ownerships_v2.len();

        Ok(Page {
            items: response.current_token_ownerships_v2,
            has_more: items_count == pagination.limit as usize,
            total_count: None,
        })
    }

    /// Gets coin balances for an account (legacy coin module).
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_coin_balances(
        &self,
        address: AccountAddress,
    ) -> AptosResult<Vec<CoinBalance>> {
        #[derive(Deserialize)]
        struct Response {
            current_coin_balances: Vec<CoinBalance>,
        }

        let query = r"
            query GetCoinBalances($address: String!) {
                current_coin_balances(
                    where: { owner_address: { _eq: $address } }
                ) {
                    coin_type
                    amount
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string()
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.current_coin_balances)
    }

    /// Gets coin activities for an account.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_coin_activities(
        &self,
        address: AccountAddress,
        limit: Option<u32>,
    ) -> AptosResult<Vec<CoinActivity>> {
        #[derive(Deserialize)]
        struct Response {
            coin_activities: Vec<CoinActivity>,
        }

        let query = r"
            query GetCoinActivities($address: String!, $limit: Int!) {
                coin_activities(
                    where: { owner_address: { _eq: $address } }
                    order_by: { transaction_version: desc }
                    limit: $limit
                ) {
                    activity_type
                    amount
                    coin_type
                }
            }
        ";

        let variables = serde_json::json!({
            "address": address.to_string(),
            "limit": limit.unwrap_or(25)
        });

        let response: Response = self.query(query, Some(variables)).await?;
        Ok(response.coin_activities)
    }

    /// Gets the processor status to check indexer health.
    ///
    /// # Errors
    ///
    /// Returns an error if the GraphQL query fails (see [`query`](Self::query) for details).
    pub async fn get_processor_status(&self) -> AptosResult<Vec<ProcessorStatus>> {
        #[derive(Deserialize)]
        struct Response {
            processor_status: Vec<ProcessorStatus>,
        }

        let query = r"
            query GetProcessorStatus {
                processor_status {
                    processor
                    last_success_version
                    last_updated
                }
            }
        ";

        let response: Response = self.query(query, None).await?;
        Ok(response.processor_status)
    }

    /// Gets the current indexer version (last processed transaction).
    ///
    /// # Errors
    ///
    /// Returns an error if the processor status cannot be fetched, or if no processor status
    /// is available.
    pub async fn get_indexer_version(&self) -> AptosResult<u64> {
        let statuses = self.get_processor_status().await?;
        statuses
            .into_iter()
            .map(|s| s.last_success_version)
            .max()
            .ok_or_else(|| AptosError::Internal("No processor status available".into()))
    }

    /// Checks if the indexer is healthy by comparing with a reference version.
    ///
    /// # Errors
    ///
    /// Returns an error if the indexer version cannot be fetched (see [`get_indexer_version`](Self::get_indexer_version) for details).
    pub async fn check_indexer_lag(
        &self,
        reference_version: u64,
        max_lag: u64,
    ) -> AptosResult<bool> {
        let indexer_version = self.get_indexer_version().await?;
        Ok(reference_version.saturating_sub(indexer_version) <= max_lag)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_indexer_client_creation() {
        let client = IndexerClient::new(&AptosConfig::testnet());
        assert!(client.is_ok());
    }

    #[test]
    fn test_pagination_params() {
        let params = PaginationParams::new(10, 20);
        assert_eq!(params.limit, 10);
        assert_eq!(params.offset, 20);

        let first_page = PaginationParams::first(50);
        assert_eq!(first_page.limit, 50);
        assert_eq!(first_page.offset, 0);
    }

    #[test]
    fn test_page_has_more() {
        let page: Page<u32> = Page {
            items: vec![1, 2, 3],
            has_more: true,
            total_count: Some(100),
        };
        assert!(page.has_more);
        assert_eq!(page.items.len(), 3);
        assert_eq!(page.total_count, Some(100));
    }

    #[test]
    fn test_custom_url() {
        let client = IndexerClient::with_url("https://custom-indexer.example.com/v1/graphql");
        assert!(client.is_ok());
    }
}