|
| 1 | +//! Metagraph API handler |
| 2 | +//! |
| 3 | +//! Exposes all registered neurons (miners + validators) from the cached metagraph. |
| 4 | +
|
| 5 | +use crate::state::AppState; |
| 6 | +use axum::{extract::State, Json}; |
| 7 | +use serde::Serialize; |
| 8 | +use sp_core::crypto::Ss58Codec; |
| 9 | +use std::sync::Arc; |
| 10 | + |
| 11 | +#[derive(Debug, Serialize)] |
| 12 | +pub struct NeuronInfo { |
| 13 | + pub uid: u64, |
| 14 | + pub hotkey: String, |
| 15 | + pub stake: u64, |
| 16 | +} |
| 17 | + |
| 18 | +/// GET /api/v1/metagraph - Get all registered neurons |
| 19 | +pub async fn get_metagraph(State(state): State<Arc<AppState>>) -> Json<Vec<NeuronInfo>> { |
| 20 | + let mg = state.metagraph.read(); |
| 21 | + let neurons = match *mg { |
| 22 | + Some(ref metagraph) => metagraph |
| 23 | + .neurons |
| 24 | + .iter() |
| 25 | + .map(|(uid, neuron)| NeuronInfo { |
| 26 | + uid: *uid, |
| 27 | + hotkey: neuron.hotkey.to_ss58check(), |
| 28 | + stake: neuron.stake.min(u64::MAX as u128) as u64, |
| 29 | + }) |
| 30 | + .collect(), |
| 31 | + None => vec![], |
| 32 | + }; |
| 33 | + Json(neurons) |
| 34 | +} |
| 35 | + |
| 36 | +#[cfg(test)] |
| 37 | +mod tests { |
| 38 | + use super::*; |
| 39 | + |
| 40 | + #[test] |
| 41 | + fn test_neuron_info_serialize() { |
| 42 | + let info = NeuronInfo { |
| 43 | + uid: 42, |
| 44 | + hotkey: "5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY".to_string(), |
| 45 | + stake: 10_000_000_000_000, |
| 46 | + }; |
| 47 | + let json = serde_json::to_string(&info).unwrap(); |
| 48 | + assert!(json.contains("42")); |
| 49 | + assert!(json.contains("5GrwvaEF")); |
| 50 | + assert!(json.contains("10000000000000")); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn test_neuron_info_empty_vec_serialize() { |
| 55 | + let neurons: Vec<NeuronInfo> = vec![]; |
| 56 | + let json = serde_json::to_string(&neurons).unwrap(); |
| 57 | + assert_eq!(json, "[]"); |
| 58 | + } |
| 59 | +} |
0 commit comments