use crate::indexer::*; use crate::*; use anyhow::{anyhow, Result}; use std::collections::{hash_map, HashMap}; pub struct IdentityCache<'a> { client: &'a Client, identities: HashMap<u32, String>, indexer: Option<Indexer<'a>>, } impl<'a> IdentityCache<'a> { pub fn new(client: &'a Client, indexer: Option<Indexer<'a>>) -> Self { Self { client, identities: HashMap::new(), indexer, } } pub async fn fetch_identity( &mut self, identity_id: u32, parent_hash: sp_core::H256, ) -> Result<String> { Ok(match self.identities.entry(identity_id) { hash_map::Entry::Occupied(entry) => entry.get().clone(), hash_map::Entry::Vacant(entry) => entry .insert({ let pubkey = self .client .storage() .fetch( &runtime::storage().identity().identities(identity_id), Some(parent_hash), ) .await? .ok_or_else(|| anyhow!("Identity {} not found", identity_id))? .owner_key .to_string(); format!( "“ {} ”", if let Some(indexer) = &self.indexer { if let Ok(Some(username)) = indexer.username_by_pubkey(&pubkey).await { username } else { pubkey } } else { pubkey } ) }) .clone(), }) } }