use tonic_web_wasm_client::Client as WebClient;
use super::pb::{
get_block_request::Selector, sentrix_client::SentrixClient, BlockHeight, EventFilter,
GetBalanceRequest, GetBlockRequest, GetMempoolRequest, GetSupplyRequest,
GetValidatorSetRequest, Mempool, StreamEventsRequest, Supply, ValidatorSet,
};
pub type Inner = SentrixClient<WebClient>;
#[derive(Clone)]
pub struct SentrixGrpcClient {
inner: Inner,
}
impl SentrixGrpcClient {
pub fn new(endpoint: impl Into<String>) -> Self {
let transport = WebClient::new(endpoint.into());
Self {
inner: SentrixClient::new(transport),
}
}
pub async fn get_latest_block(&mut self) -> Result<super::pb::Block, tonic::Status> {
let req = GetBlockRequest {
selector: Some(Selector::Latest(true)),
};
let resp = self.inner.get_block(req).await?;
Ok(resp.into_inner())
}
pub async fn get_block_by_height(
&mut self,
height: u64,
) -> Result<super::pb::Block, tonic::Status> {
let req = GetBlockRequest {
selector: Some(Selector::Height(BlockHeight { value: height })),
};
let resp = self.inner.get_block(req).await?;
Ok(resp.into_inner())
}
pub async fn get_balance(
&mut self,
addr: [u8; 20],
) -> Result<super::pb::Account, tonic::Status> {
let req = GetBalanceRequest {
address: Some(super::pb::Address {
value: addr.to_vec(),
}),
at_height: None,
};
let resp = self.inner.get_balance(req).await?;
Ok(resp.into_inner())
}
pub async fn get_validator_set(&mut self) -> Result<ValidatorSet, tonic::Status> {
let req = GetValidatorSetRequest { at_height: None };
let resp = self.inner.get_validator_set(req).await?;
Ok(resp.into_inner())
}
pub async fn get_supply(&mut self) -> Result<Supply, tonic::Status> {
let req = GetSupplyRequest { at_height: None };
let resp = self.inner.get_supply(req).await?;
Ok(resp.into_inner())
}
pub async fn get_mempool(&mut self, limit: u32) -> Result<Mempool, tonic::Status> {
let req = GetMempoolRequest { limit };
let resp = self.inner.get_mempool(req).await?;
Ok(resp.into_inner())
}
pub async fn subscribe_events(
&mut self,
filters: Vec<EventFilter>,
) -> Result<tonic::Streaming<super::pb::ChainEvent>, tonic::Status> {
let req = StreamEventsRequest {
filters: filters.into_iter().map(|f| f as i32).collect(),
from_sequence: 0,
};
let resp = self.inner.stream_events(req).await?;
Ok(resp.into_inner())
}
}
pub fn hash_short(h: &super::pb::Hash) -> String {
if h.value.len() != 32 {
return "—".into();
}
let hex = hex::encode(&h.value);
format!("{}…{}", &hex[..6], &hex[hex.len() - 4..])
}