bittensor-rs 0.1.1

Standalone Rust SDK for Bittensor blockchain interactions
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
//! # Bittensor Service
//!
//! Central service for all Bittensor chain interactions with connection pooling,
//! automatic failover, and circuit breaker protection.
//!
//! The [`Service`] struct is the main entry point for interacting with the Bittensor
//! blockchain. It manages:
//!
//! - **Connection pooling**: Multiple connections with automatic health checks
//! - **Retry logic**: Exponential backoff for transient failures
//! - **Circuit breaker**: Prevents cascade failures during outages
//! - **Transaction signing**: Uses the configured wallet hotkey
//!
//! # Example
//!
//! ```rust,no_run
//! use bittensor_rs::{config::BittensorConfig, Service};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let config = BittensorConfig::finney("my_wallet", "my_hotkey", 1);
//!     let service = Service::new(config).await?;
//!     
//!     // Query metagraph
//!     let metagraph = service.get_metagraph(1).await?;
//!     println!("Neurons: {}", metagraph.hotkeys.len());
//!     
//!     // Set weights
//!     service.set_weights(1, vec![(0, 100), (1, 200)]).await?;
//!     
//!     // Graceful shutdown
//!     service.shutdown().await;
//!     Ok(())
//! }
//! ```
//!
//! # Connection Monitoring
//!
//! Monitor connection health and metrics:
//!
//! ```rust,no_run
//! # use bittensor_rs::{config::BittensorConfig, Service};
//! # async fn example(service: Service) -> Result<(), Box<dyn std::error::Error>> {
//! let metrics = service.connection_metrics().await;
//! println!("Healthy: {}/{}", metrics.healthy_connections, metrics.total_connections);
//!
//! // Force reconnect if needed
//! service.force_reconnect().await?;
//! # Ok(())
//! # }
//! ```

use crate::config::BittensorConfig;
use crate::connect::{CircuitBreaker, HealthChecker, RetryConfig, RetryNode};
use crate::connect::{ConnectionManager, ConnectionPool, ConnectionPoolBuilder};
use crate::error::BittensorError;
use crate::utils::{set_weights_payload, NormalizedWeight};
use crate::AccountId;
use anyhow::Result;

// Wallet utilities - we'll implement these
use std::path::PathBuf;

// Always use our own generated API module
use crate::api::api;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, info, warn};

// Use subxt directly with our generated API
use subxt_signer::sr25519::Keypair;

// Type alias for our chain client removed; Service uses pooled clients via connect::pool

// Wallet helper functions
fn home_hotkey_location(wallet_name: &str, hotkey_name: &str) -> Option<PathBuf> {
    home::home_dir().map(|home| {
        home.join(".bittensor")
            .join("wallets")
            .join(wallet_name)
            .join("hotkeys")
            .join(hotkey_name)
    })
}

fn load_key_seed(path: &PathBuf) -> Result<String, Box<dyn std::error::Error>> {
    let content = std::fs::read_to_string(path)?;

    // Try to parse as JSON first (new format)
    if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&content) {
        if let Some(secret_phrase) = json_value.get("secretPhrase").and_then(|v| v.as_str()) {
            return Ok(secret_phrase.to_string());
        }
        // Fall back to secretSeed if secretPhrase is not available
        if let Some(secret_seed) = json_value.get("secretSeed").and_then(|v| v.as_str()) {
            return Ok(secret_seed.to_string());
        }
        return Err("JSON wallet file missing secretPhrase or secretSeed".into());
    }

    // If not JSON, assume it's a raw seed phrase (old format)
    Ok(content.trim().to_string())
}

fn signer_from_seed(seed: &str) -> Result<Keypair, Box<dyn std::error::Error + Send + Sync>> {
    use subxt_signer::SecretUri;
    
    // Parse the seed as a SecretUri (handles mnemonic, hex seeds, etc.)
    let uri: SecretUri = seed.parse()?;
    let keypair = Keypair::from_uri(&uri)?;
    Ok(keypair)
}

// Import the metagraph types
use crate::{Metagraph, SelectiveMetagraph};

/// Central service for Bittensor chain interactions with connection pooling and retry mechanisms
pub struct Service {
    config: BittensorConfig,
    connection_pool: Arc<ConnectionPool>,
    connection_manager: Arc<ConnectionManager>,
    signer: Keypair,
    retry_node: RetryNode,
    circuit_breaker: Arc<tokio::sync::Mutex<CircuitBreaker>>,
    health_monitor_handle: Option<tokio::task::JoinHandle<()>>,
}

impl Service {
    /// Creates a new Service instance with the provided configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - The Bittensor configuration containing network and wallet settings
    ///
    /// # Returns
    ///
    /// * `Result<Self, BittensorError>` - A Result containing either the initialized Service or an error
    ///
    /// # Errors
    ///
    /// * `NetworkError` - If connection to the client network fails
    /// * `WalletError` - If wallet key loading or signer creation fails
    pub async fn new(config: BittensorConfig) -> Result<Self, BittensorError> {
        info!(
            "Initializing enhanced Bittensor service for network: {}",
            config.network
        );

        // Build connection pool with configuration
        let pool = Arc::new(
            ConnectionPoolBuilder::new(config.get_chain_endpoints())
                .max_connections(config.connection_pool_size.unwrap_or(3))
                .retry_config(RetryConfig::network())
                .build(),
        );

        // Initialize pool with retry logic
        let retry_node = RetryNode::new().with_timeout(Duration::from_secs(120));

        retry_node
            .execute_with_config(
                || async {
                    pool.initialize()
                        .await
                        .map_err(|e| BittensorError::NetworkError {
                            message: format!("Pool initialization failed: {}", e),
                        })
                },
                RetryConfig::network(),
            )
            .await?;

        info!(
            "Connection pool initialized with {} healthy connections",
            pool.healthy_connection_count().await
        );

        // Create connection manager for state tracking
        let connection_manager = Arc::new(ConnectionManager::new(config.clone()));

        // Start health monitoring
        let health_checker = Arc::new(
            HealthChecker::new()
                .with_interval(
                    config
                        .health_check_interval
                        .unwrap_or(Duration::from_secs(60)),
                )
                .with_timeout(Duration::from_secs(5))
                .with_failure_threshold(3),
        );

        let monitor_handle = health_checker.start_monitoring(Arc::clone(&pool));

        // Load wallet signer
        let hotkey_path = home_hotkey_location(&config.wallet_name, &config.hotkey_name)
            .ok_or_else(|| BittensorError::WalletError {
                message: "Failed to find home directory".to_string(),
            })?;

        if config.read_only {
            info!(
                "Loading hotkey from path: {:?} in READ-ONLY mode (wallet: {}, hotkey: {})",
                hotkey_path, config.wallet_name, config.hotkey_name
            );
            info!("Read-only mode: wallet is used for metagraph queries only, not for signing transactions");
        } else {
            info!(
                "Loading hotkey from path: {:?} (wallet: {}, hotkey: {})",
                hotkey_path, config.wallet_name, config.hotkey_name
            );
        }

        let seed = load_key_seed(&hotkey_path).map_err(|e| BittensorError::WalletError {
            message: format!("Failed to load hotkey from {hotkey_path:?}: {e}"),
        })?;

        let signer = signer_from_seed(&seed).map_err(|e| BittensorError::WalletError {
            message: format!("Failed to create signer from seed: {e}"),
        })?;

        // Initialize circuit breaker for cascade failure prevention
        let circuit_breaker = Arc::new(tokio::sync::Mutex::new(CircuitBreaker::new(
            config.circuit_breaker_threshold.unwrap_or(5),
            config
                .circuit_breaker_recovery
                .unwrap_or(Duration::from_secs(60)),
        )));

        let service = Self {
            config,
            connection_pool: pool,
            connection_manager,
            signer,
            retry_node,
            circuit_breaker,
            health_monitor_handle: Some(monitor_handle),
        };

        info!("Enhanced Bittensor service initialized with connection pooling");
        Ok(service)
    }

    /// Serves an axon on the Bittensor network with retry logic.
    ///
    /// # Arguments
    ///
    /// * `netuid` - The subnet UID to serve the axon on
    /// * `axon_addr` - The socket address where the axon will be served
    ///
    /// # Returns
    ///
    /// * `Result<(), BittensorError>` - A Result indicating success or failure
    ///
    /// # Errors
    ///
    /// * `TxSubmissionError` - If the serve_axon transaction fails to submit
    /// * `MaxRetriesExceeded` - If all retry attempts are exhausted
    pub async fn serve_axon(
        &self,
        netuid: u16,
        axon_addr: SocketAddr,
    ) -> Result<(), BittensorError> {
        info!(
            "Serving axon for netuid {} at {} with retry logic",
            netuid, axon_addr
        );

        let operation = || {
            // Create serve_axon payload using our generated API
            let (ip, ip_type): (u128, u8) = match axon_addr.ip() {
                std::net::IpAddr::V4(ipv4) => (u32::from(ipv4) as u128, 4),
                std::net::IpAddr::V6(ipv6) => (u128::from(ipv6), 6),
            };
            let port = axon_addr.port();
            let protocol = 0; // TCP = 0, UDP = 1

            let payload = api::tx().subtensor_module().serve_axon(
                netuid, 0, // version (u32)
                ip, port, ip_type, protocol, 0, // placeholder1
                0, // placeholder2
            );

            let signer = &self.signer;

            async move {
                // Get a healthy client from the pool
                let client = self
                    .connection_pool
                    .get_healthy_client()
                    .await
                    .map_err(|e| BittensorError::NetworkError {
                        message: format!("Failed to get healthy client: {}", e),
                    })?;

                client
                    .tx()
                    .sign_and_submit_then_watch_default(&payload, signer)
                    .await
                    .map_err(|e| {
                        let err_msg = e.to_string();
                        let err_lower = err_msg.to_lowercase();

                        if err_lower.contains("timeout") {
                            BittensorError::TxTimeoutError {
                                message: format!("serve_axon transaction timeout: {err_msg}"),
                                timeout: Duration::from_secs(60),
                            }
                        } else if err_lower.contains("fee") || err_lower.contains("balance") {
                            BittensorError::InsufficientTxFees {
                                required: 0,
                                available: 0,
                            }
                        } else if err_lower.contains("nonce") {
                            BittensorError::InvalidNonce {
                                expected: 0,
                                actual: 0,
                            }
                        } else {
                            BittensorError::TxSubmissionError {
                                message: format!("Failed to submit serve_axon: {err_msg}"),
                            }
                        }
                    })?;
                Ok(())
            }
        };

        self.retry_node.execute(operation).await?;
        info!("Axon served successfully");
        Ok(())
    }

    /// Sets weights for neurons in the subnet with retry logic.
    ///
    /// # Arguments
    ///
    /// * `netuid` - The subnet UID to set weights for
    /// * `weights` - Vector of (uid, weight) pairs representing neuron weights
    ///
    /// # Returns
    ///
    /// * `Result<(), BittensorError>` - A Result indicating success or failure
    ///
    /// # Errors
    ///
    /// * `TxSubmissionError` - If the set_weights transaction fails to submit
    /// * `InvalidWeights` - If the weight vector is invalid
    /// * `MaxRetriesExceeded` - If all retry attempts are exhausted
    pub async fn set_weights(
        &self,
        netuid: u16,
        weights: Vec<(u16, u16)>,
    ) -> Result<(), BittensorError> {
        info!(
            "Setting weights for netuid {} with {} weights using retry logic",
            netuid,
            weights.len()
        );

        // Validate weights before attempting transaction
        if weights.is_empty() {
            return Err(BittensorError::InvalidWeights {
                reason: "Weight vector cannot be empty".to_string(),
            });
        }

        // Check for duplicate UIDs
        let mut seen_uids = std::collections::HashSet::new();
        for (uid, _) in &weights {
            if !seen_uids.insert(*uid) {
                return Err(BittensorError::InvalidWeights {
                    reason: format!("Duplicate UID found: {uid}"),
                });
            }
        }

        let operation = || {
            // Convert to NormalizedWeight format
            let normalized_weights: Vec<NormalizedWeight> = weights
                .iter()
                .map(|(uid, weight)| NormalizedWeight {
                    uid: *uid,
                    weight: *weight,
                })
                .collect();

            // Create set_weights payload with version_key = 0
            let payload = set_weights_payload(netuid, normalized_weights, 0);
            let signer = &self.signer;

            async move {
                // Get a healthy client from the pool
                let client = self
                    .connection_pool
                    .get_healthy_client()
                    .await
                    .map_err(|e| BittensorError::NetworkError {
                        message: format!("Failed to get healthy client: {}", e),
                    })?;

                client
                    .tx()
                    .sign_and_submit_then_watch_default(&payload, signer)
                    .await
                    .map_err(|e| {
                        let err_msg = e.to_string();
                        let err_lower = err_msg.to_lowercase();

                        if err_lower.contains("timeout") {
                            BittensorError::TxTimeoutError {
                                message: format!("set_weights transaction timeout: {err_msg}"),
                                timeout: Duration::from_secs(120),
                            }
                        } else if err_lower.contains("weight") || err_lower.contains("invalid") {
                            BittensorError::WeightSettingFailed {
                                netuid,
                                reason: format!("Weight validation failed: {err_msg}"),
                            }
                        } else if err_lower.contains("fee") || err_lower.contains("balance") {
                            BittensorError::InsufficientTxFees {
                                required: 0,
                                available: 0,
                            }
                        } else if err_lower.contains("nonce") {
                            BittensorError::InvalidNonce {
                                expected: 0,
                                actual: 0,
                            }
                        } else {
                            BittensorError::TxSubmissionError {
                                message: format!("Failed to submit set_weights: {err_msg}"),
                            }
                        }
                    })?;
                Ok(())
            }
        };

        self.retry_node.execute(operation).await?;
        info!("Weights set successfully for netuid {}", netuid);
        Ok(())
    }

    /// Gets neuron information for a specific UID in the subnet.
    ///
    /// # Arguments
    ///
    /// * `netuid` - The subnet UID
    /// * `uid` - The neuron UID to get information for
    ///
    /// # Returns
    ///
    /// * `Result<Option<NeuronInfo>, BittensorError>` - A Result containing either the neuron info or an error
    ///
    /// # Errors
    ///
    /// * `RpcError` - If the RPC call fails
    pub async fn get_neuron(
        &self,
        netuid: u16,
        uid: u16,
    ) -> Result<Option<crate::NeuronInfo>, BittensorError> {
        debug!("Getting neuron info for UID: {} on netuid: {}", uid, netuid);

        // Get a healthy client from the pool
        let client = self
            .connection_pool
            .get_healthy_client()
            .await
            .map_err(|e| BittensorError::NetworkError {
                message: format!("Failed to get healthy client: {}", e),
            })?;

        let runtime_api =
            client
                .runtime_api()
                .at_latest()
                .await
                .map_err(|e| BittensorError::RpcError {
                    message: format!("Failed to get runtime API: {e}"),
                })?;

        let neuron_info = runtime_api
            .call(
                api::runtime_apis::neuron_info_runtime_api::NeuronInfoRuntimeApi
                    .get_neuron(netuid, uid),
            )
            .await
            .map_err(|e| BittensorError::RpcError {
                message: format!("Failed to call get_neuron: {e}"),
            })?;

        Ok(neuron_info)
    }

    /// Gets the complete metagraph for a subnet with circuit breaker protection.
    ///
    /// # Arguments
    ///
    /// * `netuid` - The subnet UID to get the metagraph for
    ///
    /// # Returns
    ///
    /// * `Result<Metagraph, BittensorError>` - A Result containing either the metagraph or an error
    ///
    /// # Errors
    ///
    /// * `RpcError` - If the RPC call fails
    /// * `SubnetNotFound` - If the subnet doesn't exist
    /// * `ServiceUnavailable` - If circuit breaker is open
    pub async fn get_metagraph(&self, netuid: u16) -> Result<Metagraph, BittensorError> {
        info!(
            "Fetching metagraph for netuid: {} with circuit breaker protection",
            netuid
        );

        let operation = || {
            async move {
                // Get a healthy client from the pool
                let client = self
                    .connection_pool
                    .get_healthy_client()
                    .await
                    .map_err(|e| BittensorError::NetworkError {
                        message: format!("Failed to get healthy client: {}", e),
                    })?;

                let runtime_api = client.runtime_api().at_latest().await.map_err(|e| {
                    let err_msg = e.to_string();
                    let err_lower = err_msg.to_lowercase();

                    if err_lower.contains("timeout") {
                        BittensorError::RpcTimeoutError {
                            message: format!("Runtime API timeout: {err_msg}"),
                            timeout: Duration::from_secs(30),
                        }
                    } else if err_lower.contains("connection") {
                        BittensorError::RpcConnectionError {
                            message: format!("Runtime API connection failed: {err_msg}"),
                        }
                    } else {
                        BittensorError::RpcMethodError {
                            method: "runtime_api".to_string(),
                            message: err_msg,
                        }
                    }
                })?;

                let metagraph = runtime_api
                    .call(
                        api::runtime_apis::subnet_info_runtime_api::SubnetInfoRuntimeApi
                            .get_metagraph(netuid),
                    )
                    .await
                    .map_err(|e| {
                        let err_msg = e.to_string();
                        if err_msg.to_lowercase().contains("timeout") {
                            BittensorError::RpcTimeoutError {
                                message: format!("get_metagraph call timeout: {err_msg}"),
                                timeout: Duration::from_secs(30),
                            }
                        } else {
                            BittensorError::RpcMethodError {
                                method: "get_metagraph".to_string(),
                                message: err_msg,
                            }
                        }
                    })?
                    .ok_or(BittensorError::SubnetNotFound { netuid })?;

                Ok(metagraph)
            }
        };

        // Use circuit breaker for RPC calls
        // Clone the circuit breaker to avoid holding the lock across await
        let mut circuit_breaker = {
            let cb = self.circuit_breaker.lock().await;
            cb.clone()
        };
        let result = circuit_breaker.execute(operation).await;

        // Update the original circuit breaker with the new state
        {
            let mut original_cb = self.circuit_breaker.lock().await;
            *original_cb = circuit_breaker;
        }

        match &result {
            Ok(_) => info!("Metagraph fetched successfully for netuid: {}", netuid),
            Err(e) => warn!("Failed to fetch metagraph for netuid {}: {}", netuid, e),
        }

        result
    }

    /// Retrieves a selective metagraph for a specific subnet, containing only the requested fields.
    ///
    /// # Arguments
    ///
    /// * `netuid` - The subnet UID to get the selective metagraph for
    /// * `fields` - Vector of field indices to include in the selective metagraph
    ///
    /// # Returns
    ///
    /// * `Result<SelectiveMetagraph, BittensorError>` - A Result containing either the selective metagraph or an error
    ///
    /// # Errors
    ///
    /// * `RpcError` - If connection to the runtime API fails
    /// * `RpcError` - If the selective metagraph call fails
    /// * `RpcError` - If no selective metagraph is found for the subnet
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let fields = vec![0, 1, 2]; // Include first three fields
    /// let selective_metagraph = service.get_selective_metagraph(1, fields).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_selective_metagraph(
        &self,
        netuid: u16,
        fields: Vec<u16>,
    ) -> Result<SelectiveMetagraph, BittensorError> {
        info!(
            "Fetching selective metagraph for netuid: {} with {} fields",
            netuid,
            fields.len()
        );

        // Get a healthy client from the pool
        let client = self
            .connection_pool
            .get_healthy_client()
            .await
            .map_err(|e| BittensorError::NetworkError {
                message: format!("Failed to get healthy client: {}", e),
            })?;

        let runtime_api =
            client
                .runtime_api()
                .at_latest()
                .await
                .map_err(|e| BittensorError::RpcError {
                    message: format!("Failed to get runtime API: {e}"),
                })?;

        let selective_metagraph = runtime_api
            .call(
                api::runtime_apis::subnet_info_runtime_api::SubnetInfoRuntimeApi
                    .get_selective_metagraph(netuid, fields),
            )
            .await
            .map_err(|e| BittensorError::RpcError {
                message: format!("Failed to call get_selective_metagraph: {e}"),
            })?
            .ok_or_else(|| BittensorError::RpcError {
                message: format!("Selective metagraph not found for subnet {netuid}"),
            })?;

        Ok(selective_metagraph)
    }

    /// Retrieves the current block number from the Bittensor network.
    ///
    /// # Returns
    ///
    /// * `Result<u64, BittensorError>` - A Result containing either the current block number or an error
    ///
    /// # Errors
    ///
    /// * `RpcError` - If connection to the latest block fails
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let block_number = service.get_block_number().await?;
    /// println!("Current block: {}", block_number);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn get_block_number(&self) -> Result<u64, BittensorError> {
        // Get a healthy client from the pool
        let client = self
            .connection_pool
            .get_healthy_client()
            .await
            .map_err(|e| BittensorError::NetworkError {
                message: format!("Failed to get healthy client: {}", e),
            })?;

        let latest_block =
            client
                .blocks()
                .at_latest()
                .await
                .map_err(|e| BittensorError::RpcError {
                    message: format!("Failed to get latest block: {e}"),
                })?;

        Ok(latest_block.number().into())
    }

    /// Returns the account ID associated with the service's signer.
    ///
    /// # Returns
    ///
    /// * `&AccountId` - Reference to the signer's account ID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let account_id = service.get_account_id();
    /// println!("Account ID: {}", account_id);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_account_id(&self) -> AccountId {
        subxt::config::polkadot::AccountId32::from(self.signer.public_key().0)
    }

    /// Get current block number (alias for get_block_number)
    pub async fn get_current_block(&self) -> Result<u64, BittensorError> {
        self.get_block_number().await
    }

    /// Submit an extrinsic (transaction) to the chain
    pub async fn submit_extrinsic<T>(&self, payload: T) -> Result<(), BittensorError>
    where
        T: subxt::tx::Payload,
    {
        // Get a healthy client from the pool
        let client = self
            .connection_pool
            .get_healthy_client()
            .await
            .map_err(|e| BittensorError::NetworkError {
                message: format!("Failed to get healthy client: {}", e),
            })?;

        let tx_result = client
            .tx()
            .sign_and_submit_default(&payload, &self.signer)
            .await
            .map_err(|e| BittensorError::TxSubmissionError {
                message: format!("Failed to submit extrinsic: {e}"),
            })?;

        info!("Transaction submitted with hash: {:?}", tx_result);
        Ok(())
    }

    /// Returns the configured network name for this service instance.
    ///
    /// # Returns
    ///
    /// * `&str` - Reference to the network name
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let network = service.get_network();
    /// println!("Connected to network: {}", network);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_network(&self) -> &str {
        &self.config.network
    }

    /// Returns the configured subnet UID for this service instance.
    ///
    /// # Returns
    ///
    /// * `u16` - The subnet UID
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let netuid = service.get_netuid();
    /// println!("Subnet UID: {}", netuid);
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_netuid(&self) -> u16 {
        self.config.netuid
    }

    /// Sign data with the service's signer (hotkey)
    ///
    /// This method signs arbitrary data with the validator/miner's hotkey.
    /// The signature can be verified using `verify_bittensor_signature`.
    ///
    /// # Arguments
    ///
    /// * `data` - The data to sign
    ///
    /// # Returns
    ///
    /// * `Result<String, BittensorError>` - Hex-encoded signature string
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use bittensor_rs::Service;
    /// # use bittensor_rs::config::BittensorConfig;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// # let config = BittensorConfig::default();
    /// # let service = Service::new(config).await?;
    /// let nonce = "test-nonce-123";
    /// let signature = service.sign_data(nonce.as_bytes())?;
    /// println!("Signature: {}", signature);
    /// # Ok(())
    /// # }
    /// ```
    pub fn sign_data(&self, data: &[u8]) -> Result<String, BittensorError> {
        // Sign the data with our signer
        let signature = self.signer.sign(data);
        Ok(hex::encode(signature.0))
    }
}

impl Service {
    /// Gets retry statistics for monitoring
    pub async fn get_retry_stats(&self) -> RetryStats {
        RetryStats {
            circuit_breaker_state: {
                let cb = self.circuit_breaker.lock().await;
                format!("{cb:?}")
            },
        }
    }

    /// Resets the circuit breaker state (for recovery operations)
    pub async fn reset_circuit_breaker(&self) {
        let mut cb = self.circuit_breaker.lock().await;
        *cb = CircuitBreaker::new(5, Duration::from_secs(60));
        info!("Circuit breaker reset");
    }

    /// Get connection pool metrics for monitoring
    pub async fn connection_metrics(&self) -> ConnectionPoolMetrics {
        ConnectionPoolMetrics {
            total_connections: self.connection_pool.total_connections().await,
            healthy_connections: self.connection_pool.healthy_connection_count().await,
            connection_state: self.connection_manager.get_state().await.status_message(),
            metrics: self.connection_manager.metrics(),
        }
    }

    /// Force reconnection of all connections
    pub async fn force_reconnect(&self) -> Result<(), BittensorError> {
        warn!("Forcing reconnection of all connections");
        self.connection_pool.refresh_connections().await?;
        self.connection_manager.force_reconnect().await?;
        Ok(())
    }

    /// Gracefully shutdown the service
    pub async fn shutdown(mut self) {
        info!("Shutting down enhanced Bittensor service");

        // Stop health monitoring
        if let Some(handle) = self.health_monitor_handle.take() {
            handle.abort();
        }

        // Connection pool will be dropped automatically
    }
}

/// Statistics for retry mechanisms
#[derive(Debug, Clone)]
pub struct RetryStats {
    pub circuit_breaker_state: String,
}

/// Connection pool metrics for monitoring
#[derive(Debug, Clone)]
pub struct ConnectionPoolMetrics {
    pub total_connections: usize,
    pub healthy_connections: usize,
    pub connection_state: String,
    pub metrics: crate::connect::ConnectionMetricsSnapshot,
}

// Implement Drop to ensure cleanup
impl Drop for Service {
    fn drop(&mut self) {
        if let Some(handle) = self.health_monitor_handle.take() {
            handle.abort();
        }
    }
}