extern crate alloc;
use crate::error::Error; use crate::jsonrpseeclient::rpcstuff::RpcParams;
use alloc::string::{String, ToString};
use futures::executor::block_on;
use jsonrpsee::core::client::Subscription;
use serde::de::DeserializeOwned;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug)]
pub struct SubscriptionWrapper<Notification> {
inner: Subscription<Notification>,
}
impl<Notification: DeserializeOwned> HandleSubscription<Notification>
for SubscriptionWrapper<Notification>
{
fn next(&mut self) -> Option<Result<Notification>> {
block_on(self.inner.next()).map(|result| result.map_err(|e| Error::Client(Box::new(e))))
}
fn unsubscribe(self) -> Result<()> {
block_on(self.inner.unsubscribe()).map_err(|_e| Error::Unsubscribefail) }
}
impl<Notification> From<Subscription<Notification>> for SubscriptionWrapper<Notification> {
fn from(inner: Subscription<Notification>) -> Self {
Self { inner }
}
}
#[maybe_async::maybe_async(?Send)]
pub trait Request {
async fn request<R: DeserializeOwned>(&self, method: &str, params: RpcParams) -> Result<R>;
}
pub trait Subscribe {
type Subscription<Notification>: HandleSubscription<Notification>
where
Notification: DeserializeOwned;
fn subscribe<Notification: DeserializeOwned>(
&self,
sub: &str,
params: RpcParams,
unsub: &str,
) -> Result<Self::Subscription<Notification>>;
}
pub trait HandleSubscription<Notification: DeserializeOwned> {
fn next(&mut self) -> Option<Result<Notification>>;
fn unsubscribe(self) -> Result<()>;
}
pub fn to_json_req(method: &str, params: RpcParams) -> Result<String> {
Ok(serde_json::json!({
"method": method,
"params": params.to_json_value()?,
"jsonrpc": "2.0",
"id": "1",
})
.to_string())
}