Add light client platform WASM compatible (#1026)

* Cargo update in prep for wasm build

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Add light client test

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Implement low level socket

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Add native platform primitives

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Add wasm platform primitives

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Implement smoldot platform

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Adjust code to use custom platform

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Adjust feature flags

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* tests: Adjust wasm endpoint to accept ws for p2p

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Adjust wasm socket

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Book mention of wasm

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* ci: Propagate env variable properly

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* subxt: Revert to native feature flags

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* cli: Use tokio rt-multi-thread feature

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* subxt: Add tokio feature flags for native platform

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm: Use polkadot live for wasm testing

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm: Add support for DNS p2p addresses

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm: Disable logs

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm: Run wasm test for firefox driver

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm: Reenable chrome driver

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Move lightclient RPC to dedicated crate for better feature flags and modularity

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Use subxt-lightclient low level RPC crate

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Apply cargo fmt

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Enable default:native feature for cargo check

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* ci: Extra step for subxt-lightclient similar to signer crate

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Remove native platform code and use smoldot instead

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* codegen: Enable tokio/multi-threads

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* lightclient: Refactor modules

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Adjust testing crates

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* ci: Run light-client WASM tests

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm-rpc: Remove light-client imports

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* testing: Update wasm cargo.lock files

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* ci: Spawn substrate node with deterministic p2p address for WASM tests

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm_socket: Use rc and refcell

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* wasm_socket: Switch back to Arc<Mutex<>>

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

* Add comments

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>

---------

Signed-off-by: Alexandru Vasile <alexandru.vasile@parity.io>
This commit is contained in:
Alexandru Vasile
2023-07-18 14:27:16 +03:00
committed by GitHub
parent ab2f2a8cdf
commit 4bda673847
28 changed files with 5280 additions and 305 deletions
-436
View File
@@ -1,436 +0,0 @@
// Copyright 2019-2023 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use futures::stream::StreamExt;
use futures_util::future::{self, Either};
use serde::Deserialize;
use serde_json::value::RawValue;
use std::{collections::HashMap, str::FromStr, sync::Arc};
use tokio::sync::{mpsc, oneshot};
use super::LightClientError;
use smoldot_light::{platform::default::DefaultPlatform as Platform, ChainId};
const LOG_TARGET: &str = "light-client-background";
/// The response of an RPC method.
pub type MethodResponse = Result<Box<RawValue>, LightClientError>;
/// Message protocol between the front-end client that submits the RPC requests
/// and the backend handler that produces responses from the chain.
///
/// The light client uses a single object [`smoldot_light::JsonRpcResponses`] to
/// handle all requests and subscriptions from a chain. A background task is spawned
/// to multiplex the rpc responses and to provide them back to their rightful submitters.
#[derive(Debug)]
pub enum FromSubxt {
/// The RPC method request.
Request {
/// The method of the request.
method: String,
/// The parameters of the request.
params: String,
/// Channel used to send back the result.
sender: oneshot::Sender<MethodResponse>,
},
/// The RPC subscription (pub/sub) request.
Subscription {
/// The method of the request.
method: String,
/// The parameters of the request.
params: String,
/// Channel used to send back the subscription ID if successful.
sub_id: oneshot::Sender<MethodResponse>,
/// Channel used to send back the notifcations.
sender: mpsc::UnboundedSender<Box<RawValue>>,
},
}
/// Background task data.
pub struct BackgroundTask {
/// Smoldot light client implementation that leverages the exposed platform.
client: smoldot_light::Client<Arc<Platform>>,
/// The ID of the chain used to identify the chain protocol (ie. substrate).
///
/// Note: A single chain is supported for a client. This aligns with the subxt's
/// vision of the Client.
chain_id: ChainId,
/// Unique ID for RPC calls.
request_id: usize,
/// Map the request ID of a RPC method to the frontend `Sender`.
requests: HashMap<usize, oneshot::Sender<MethodResponse>>,
/// Subscription calls first need to make a plain RPC method
/// request to obtain the subscription ID.
///
/// The RPC method request is made in the background and the response should
/// not be sent back to the user.
/// Map the request ID of a RPC method to the frontend `Sender`.
id_to_subscription: HashMap<
usize,
(
oneshot::Sender<MethodResponse>,
mpsc::UnboundedSender<Box<RawValue>>,
),
>,
/// Map the subscription ID to the frontend `Sender`.
subscriptions: HashMap<usize, mpsc::UnboundedSender<Box<RawValue>>>,
}
impl BackgroundTask {
/// Constructs a new [`BackgroundTask`].
pub fn new(client: smoldot_light::Client<Arc<Platform>>, chain_id: ChainId) -> BackgroundTask {
BackgroundTask {
client,
chain_id,
request_id: 1,
requests: Default::default(),
id_to_subscription: Default::default(),
subscriptions: Default::default(),
}
}
/// Fetch and increment the request ID.
fn next_id(&mut self) -> usize {
let next = self.request_id;
self.request_id = self.request_id.wrapping_add(1);
next
}
/// Handle the registration messages received from the user.
async fn handle_requests(&mut self, message: FromSubxt) {
match message {
FromSubxt::Request {
method,
params,
sender,
} => {
let id = self.next_id();
let request = format!(
r#"{{"jsonrpc":"2.0","id":"{}", "method":"{}","params":{}}}"#,
id, method, params
);
self.requests.insert(id, sender);
let result = self.client.json_rpc_request(request, self.chain_id);
if let Err(err) = result {
tracing::warn!(
target: LOG_TARGET,
"Cannot send RPC request to lightclient {:?}",
err.to_string()
);
let sender = self
.requests
.remove(&id)
.expect("Channel is inserted above; qed");
// Send the error back to frontend.
if sender
.send(Err(LightClientError::Request(err.to_string())))
.is_err()
{
tracing::warn!(
target: LOG_TARGET,
"Cannot send RPC request error to id={id}",
);
}
}
}
FromSubxt::Subscription {
method,
params,
sub_id,
sender,
} => {
// For subscriptions we need to make a plain RPC request to the subscription method.
// The server will return as a result the subscription ID.
let id = self.next_id();
let request = format!(
r#"{{"jsonrpc":"2.0","id":"{}", "method":"{}","params":{}}}"#,
id, method, params
);
self.id_to_subscription.insert(id, (sub_id, sender));
let result = self.client.json_rpc_request(request, self.chain_id);
if let Err(err) = result {
tracing::warn!(
target: LOG_TARGET,
"Cannot send RPC request to lightclient {:?}",
err.to_string()
);
let (sub_id, _) = self
.id_to_subscription
.remove(&id)
.expect("Channels are inserted above; qed");
// Send the error back to frontend.
if sub_id
.send(Err(LightClientError::Request(err.to_string())))
.is_err()
{
tracing::warn!(
target: LOG_TARGET,
"Cannot send RPC request error to id={id}",
);
}
}
}
};
}
/// Parse the response received from the light client and sent it to the appropriate user.
fn handle_rpc_response(&mut self, response: String) {
match RpcResponse::from_str(&response) {
Ok(RpcResponse::Error { id, error }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send error. Id={id} is not a valid number");
return
};
if let Some(sender) = self.requests.remove(&id) {
if sender
.send(Err(LightClientError::Request(error.to_string())))
.is_err()
{
tracing::warn!(
target: LOG_TARGET,
"Cannot send method response to id={id}",
);
}
} else if let Some((sub_id_sender, _)) = self.id_to_subscription.remove(&id) {
if sub_id_sender
.send(Err(LightClientError::Request(error.to_string())))
.is_err()
{
tracing::warn!(
target: LOG_TARGET,
"Cannot send method response to id {:?}",
id
);
}
}
}
Ok(RpcResponse::Method { id, result }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send response. Id={id} is not a valid number");
return
};
// Send the response back.
if let Some(sender) = self.requests.remove(&id) {
if sender.send(Ok(result)).is_err() {
tracing::warn!(
target: LOG_TARGET,
"Cannot send method response to id={id}",
);
}
} else if let Some((sub_id_sender, sender)) = self.id_to_subscription.remove(&id) {
let Ok(sub_id) = result
.get()
.trim_start_matches('"')
.trim_end_matches('"')
.parse::<usize>() else {
tracing::warn!(
target: LOG_TARGET,
"Subscription id={result} is not a valid number",
);
return;
};
tracing::trace!(target: LOG_TARGET, "Received subscription id={sub_id}");
if sub_id_sender.send(Ok(result)).is_err() {
tracing::warn!(
target: LOG_TARGET,
"Cannot send method response to id={id}",
);
} else {
// Track this subscription ID if send is successful.
self.subscriptions.insert(sub_id, sender);
}
}
}
Ok(RpcResponse::Subscription { method, id, result }) => {
let Ok(id) = id.parse::<usize>() else {
tracing::warn!(target: LOG_TARGET, "Cannot send subscription. Id={id} is not a valid number");
return
};
if let Some(sender) = self.subscriptions.get_mut(&id) {
// Send the current notification response.
if sender.send(result).is_err() {
tracing::warn!(
target: LOG_TARGET,
"Cannot send notification to subscription id={id} method={method}",
);
// Remove the sender if the subscription dropped the receiver.
self.subscriptions.remove(&id);
}
}
}
Err(err) => {
tracing::warn!(target: LOG_TARGET, "cannot decode RPC response {:?}", err);
}
}
}
/// Perform the main background task:
/// - receiving requests from subxt RPC method / subscriptions
/// - provides the results from the light client back to users.
pub async fn start_task(
&mut self,
from_subxt: mpsc::UnboundedReceiver<FromSubxt>,
from_node: smoldot_light::JsonRpcResponses,
) {
let from_subxt_event = tokio_stream::wrappers::UnboundedReceiverStream::new(from_subxt);
let from_node_event = futures_util::stream::unfold(from_node, |mut from_node| async {
from_node.next().await.map(|result| (result, from_node))
});
tokio::pin!(from_subxt_event, from_node_event);
let mut from_subxt_event_fut = from_subxt_event.next();
let mut from_node_event_fut = from_node_event.next();
loop {
match future::select(from_subxt_event_fut, from_node_event_fut).await {
// Message received from subxt.
Either::Left((subxt_message, previous_fut)) => {
let Some(message) = subxt_message else {
tracing::trace!(target: LOG_TARGET, "Subxt channel closed");
break;
};
tracing::trace!(
target: LOG_TARGET,
"Received register message {:?}",
message
);
self.handle_requests(message).await;
from_subxt_event_fut = from_subxt_event.next();
from_node_event_fut = previous_fut;
}
// Message received from rpc handler: lightclient response.
Either::Right((node_message, previous_fut)) => {
// Smoldot returns `None` if the chain has been removed (which subxt does not remove).
let Some(response) = node_message else {
tracing::trace!(target: LOG_TARGET, "Smoldot RPC responses channel closed");
break;
};
tracing::trace!(
target: LOG_TARGET,
"Received smoldot RPC result {:?}",
response
);
self.handle_rpc_response(response);
// Advance backend, save frontend.
from_subxt_event_fut = previous_fut;
from_node_event_fut = from_node_event.next();
}
}
}
tracing::trace!(target: LOG_TARGET, "Task closed");
}
}
/// The RPC response from the light-client.
/// This can either be a response of a method, or a notification from a subscription.
#[derive(Debug, Clone)]
enum RpcResponse {
Method {
/// Response ID.
id: String,
/// The result of the method call.
result: Box<RawValue>,
},
Subscription {
/// RPC method that generated the notification.
method: String,
/// Subscription ID.
id: String,
/// Result.
result: Box<RawValue>,
},
Error {
/// Response ID.
id: String,
/// Error.
error: Box<RawValue>,
},
}
impl std::str::FromStr for RpcResponse {
type Err = serde_json::Error;
fn from_str(response: &str) -> Result<Self, Self::Err> {
// Helper structures to deserialize from raw RPC strings.
#[derive(Deserialize, Debug)]
struct Response {
/// JSON-RPC version.
#[allow(unused)]
jsonrpc: String,
/// Result.
result: Box<RawValue>,
/// Request ID
id: String,
}
#[derive(Deserialize)]
struct NotificationParams {
/// The ID of the subscription.
subscription: String,
/// Result.
result: Box<RawValue>,
}
#[derive(Deserialize)]
struct ResponseNotification {
/// JSON-RPC version.
#[allow(unused)]
jsonrpc: String,
/// RPC method that generated the notification.
method: String,
/// Result.
params: NotificationParams,
}
#[derive(Deserialize)]
struct ErrorResponse {
/// JSON-RPC version.
#[allow(unused)]
jsonrpc: String,
/// Request ID.
id: String,
/// Error.
error: Box<RawValue>,
}
// Check if the response can be mapped as an RPC method response.
let result: Result<Response, _> = serde_json::from_str(response);
if let Ok(response) = result {
return Ok(RpcResponse::Method {
id: response.id,
result: response.result,
});
}
let result: Result<ResponseNotification, _> = serde_json::from_str(response);
if let Ok(notification) = result {
return Ok(RpcResponse::Subscription {
id: notification.params.subscription,
method: notification.method,
result: notification.params.result,
});
}
let error: ErrorResponse = serde_json::from_str(response)?;
Ok(RpcResponse::Error {
id: error.id,
error: error.error,
})
}
}
+60 -28
View File
@@ -5,14 +5,8 @@
use super::{rpc::LightClientRpc, LightClient, LightClientError};
use crate::{config::Config, error::Error, OnlineClient};
#[cfg(feature = "jsonrpsee")]
use jsonrpsee::{
async_client::ClientBuilder,
client_transport::ws::{Uri, WsTransportClientBuilder},
core::client::ClientT,
rpc_params,
};
use smoldot_light::ChainId;
use subxt_lightclient::{AddChainConfig, AddChainConfigJsonRpc, ChainId};
use std::num::NonZeroU32;
use std::sync::Arc;
@@ -145,9 +139,9 @@ impl LightClientBuilder {
}
}
let config = smoldot_light::AddChainConfig {
let config = AddChainConfig {
specification: &chain_spec.to_string(),
json_rpc: smoldot_light::AddChainConfigJsonRpc::Enabled {
json_rpc: AddChainConfigJsonRpc::Enabled {
max_pending_requests: self.max_pending_requests,
max_subscriptions: self.max_subscriptions,
},
@@ -165,27 +159,65 @@ impl LightClientBuilder {
/// Fetch the chain spec from the URL.
#[cfg(feature = "jsonrpsee")]
async fn fetch_url(url: impl AsRef<str>) -> Result<serde_json::Value, Error> {
let url = url
.as_ref()
.parse::<Uri>()
.map_err(|_| Error::LightClient(LightClientError::InvalidUrl))?;
use jsonrpsee::core::client::ClientT;
if url.scheme_str() != Some("ws") && url.scheme_str() != Some("wss") {
return Err(Error::LightClient(LightClientError::InvalidScheme));
}
let (sender, receiver) = WsTransportClientBuilder::default()
.build(url)
.await
.map_err(|_| LightClientError::Handshake)?;
let client = ClientBuilder::default()
.request_timeout(core::time::Duration::from_secs(180))
.max_notifs_per_subscription(4096)
.build_with_tokio(sender, receiver);
let client = jsonrpsee_helpers::client(url.as_ref()).await?;
client
.request("sync_state_genSyncSpec", rpc_params![true])
.request("sync_state_genSyncSpec", jsonrpsee::rpc_params![true])
.await
.map_err(|err| Error::Rpc(crate::error::RpcError::ClientError(Box::new(err))))
}
#[cfg(all(feature = "jsonrpsee", feature = "native"))]
mod jsonrpsee_helpers {
use crate::error::{Error, LightClientError};
pub use jsonrpsee::{
client_transport::ws::{InvalidUri, Receiver, Sender, Uri, WsTransportClientBuilder},
core::client::{Client, ClientBuilder},
};
/// Build WS RPC client from URL
pub async fn client(url: &str) -> Result<Client, Error> {
let url = url
.parse::<Uri>()
.map_err(|_| Error::LightClient(LightClientError::InvalidUrl))?;
if url.scheme_str() != Some("ws") && url.scheme_str() != Some("wss") {
return Err(Error::LightClient(LightClientError::InvalidScheme));
}
let (sender, receiver) = ws_transport(url).await?;
Ok(ClientBuilder::default()
.max_notifs_per_subscription(4096)
.build_with_tokio(sender, receiver))
}
async fn ws_transport(url: Uri) -> Result<(Sender, Receiver), Error> {
WsTransportClientBuilder::default()
.build(url)
.await
.map_err(|_| Error::LightClient(LightClientError::Handshake))
}
}
#[cfg(all(feature = "jsonrpsee", feature = "web"))]
mod jsonrpsee_helpers {
use crate::error::{Error, LightClientError};
pub use jsonrpsee::{
client_transport::web,
core::client::{Client, ClientBuilder},
};
/// Build web RPC client from URL
pub async fn client(url: &str) -> Result<Client, Error> {
let (sender, receiver) = web::connect(url)
.await
.map_err(|_| Error::LightClient(LightClientError::Handshake))?;
Ok(ClientBuilder::default()
.max_notifs_per_subscription(4096)
.build_with_wasm(sender, receiver))
}
}
+5 -10
View File
@@ -4,35 +4,30 @@
//! This module provides support for light clients.
mod background;
mod builder;
mod rpc;
use derivative::Derivative;
use crate::{
client::{OfflineClientT, OnlineClientT},
config::Config,
OnlineClient,
};
pub use builder::LightClientBuilder;
use derivative::Derivative;
use subxt_lightclient::LightClientRpcError;
/// Light client error.
#[derive(Debug, thiserror::Error)]
pub enum LightClientError {
/// Error encountered while adding the chain to the light-client.
#[error("Failed to add the chain to the light client: {0}.")]
AddChainError(String),
/// Error originated from the low-level RPC layer.
#[error("Rpc error: {0}")]
Rpc(LightClientRpcError),
/// The background task is closed.
#[error("Failed to communicate with the background task.")]
BackgroundClosed,
/// Invalid RPC parameters cannot be serialized as JSON string.
#[error("RPC parameters cannot be serialized as JSON string.")]
InvalidParams,
/// Error originated while trying to submit a RPC request.
#[error("RPC request cannot be sent: {0}.")]
Request(String),
/// The provided URL scheme is invalid.
///
/// Supported versions: WS, WSS.
+13 -86
View File
@@ -2,30 +2,22 @@
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.
use super::{
background::{BackgroundTask, FromSubxt, MethodResponse},
LightClientError,
};
use super::LightClientError;
use crate::{
error::{Error, RpcError},
rpc::{RpcClientT, RpcFuture, RpcSubscription},
};
use futures::{stream::StreamExt, Stream};
use futures::{Stream, StreamExt};
use serde_json::value::RawValue;
use smoldot_light::{platform::default::DefaultPlatform as Platform, ChainId};
use std::pin::Pin;
use tokio::sync::{mpsc, mpsc::error::SendError, oneshot};
use subxt_lightclient::{AddChainConfig, ChainId, LightClientRpcError};
use tokio_stream::wrappers::UnboundedReceiverStream;
pub const LOG_TARGET: &str = "light-client";
/// The light-client RPC implementation that is used to connect with the chain.
#[derive(Clone)]
pub struct LightClientRpc {
/// Communicate with the backend task that multiplexes the responses
/// back to the frontend.
to_backend: mpsc::UnboundedSender<FromSubxt>,
}
pub struct LightClientRpc(subxt_lightclient::LightClientRpc);
impl LightClientRpc {
/// Constructs a new [`LightClientRpc`], providing the chain specification.
@@ -39,81 +31,12 @@ impl LightClientRpc {
///
/// Panics if being called outside of `tokio` runtime context.
pub fn new(
config: smoldot_light::AddChainConfig<'_, (), impl Iterator<Item = ChainId>>,
config: AddChainConfig<'_, (), impl Iterator<Item = ChainId>>,
) -> Result<LightClientRpc, Error> {
tracing::trace!(target: LOG_TARGET, "Create light client");
let rpc = subxt_lightclient::LightClientRpc::new(config)
.map_err(|err| LightClientError::Rpc(err))?;
let mut client = smoldot_light::Client::new(Platform::new(
env!("CARGO_PKG_NAME").into(),
env!("CARGO_PKG_VERSION").into(),
));
let smoldot_light::AddChainSuccess {
chain_id,
json_rpc_responses,
} = client
.add_chain(config)
.map_err(|err| LightClientError::AddChainError(err.to_string()))?;
let (to_backend, backend) = mpsc::unbounded_channel();
// `json_rpc_responses` can only be `None` if we had passed `json_rpc: Disabled`.
let rpc_responses = json_rpc_responses.expect("Light client RPC configured; qed");
tokio::spawn(async move {
let mut task = BackgroundTask::new(client, chain_id);
task.start_task(backend, rpc_responses).await;
});
Ok(LightClientRpc { to_backend })
}
/// Submits an RPC method request to the light-client.
///
/// This method sends a request to the light-client to execute an RPC method with the provided parameters.
/// The parameters are parsed into a valid JSON object in the background.
fn method_request(
&self,
method: String,
params: String,
) -> Result<oneshot::Receiver<MethodResponse>, SendError<FromSubxt>> {
let (sender, receiver) = oneshot::channel();
self.to_backend.send(FromSubxt::Request {
method,
params,
sender,
})?;
Ok(receiver)
}
/// Makes an RPC subscription call to the light-client.
///
/// This method sends a request to the light-client to establish an RPC subscription with the provided parameters.
/// The parameters are parsed into a valid JSON object in the background.
fn subscription_request(
&self,
method: String,
params: String,
) -> Result<
(
oneshot::Receiver<MethodResponse>,
mpsc::UnboundedReceiver<Box<RawValue>>,
),
SendError<FromSubxt>,
> {
let (sub_id, sub_id_rx) = oneshot::channel();
let (sender, receiver) = mpsc::unbounded_channel();
self.to_backend.send(FromSubxt::Subscription {
method,
params,
sub_id,
sender,
})?;
Ok((sub_id_rx, receiver))
Ok(LightClientRpc(rpc))
}
}
@@ -135,6 +58,7 @@ impl RpcClientT for LightClientRpc {
// Fails if the background is closed.
let rx = client
.0
.method_request(method.to_string(), params)
.map_err(|_| RpcError::ClientError(Box::new(LightClientError::BackgroundClosed)))?;
@@ -174,6 +98,7 @@ impl RpcClientT for LightClientRpc {
// Fails if the background is closed.
let (sub_id, notif) = client
.0
.subscription_request(sub.to_string(), params)
.map_err(|_| RpcError::ClientError(Box::new(LightClientError::BackgroundClosed)))?;
@@ -182,7 +107,9 @@ impl RpcClientT for LightClientRpc {
.await
.map_err(|_| RpcError::ClientError(Box::new(LightClientError::BackgroundClosed)))?
.map_err(|err| {
RpcError::ClientError(Box::new(LightClientError::Request(err.to_string())))
RpcError::ClientError(Box::new(LightClientError::Rpc(
LightClientRpcError::Request(err.to_string()),
)))
})?;
let sub_id = result