From 26ff3204887791cc325d6ec1d5ab529264556685 Mon Sep 17 00:00:00 2001 From: Niklas Adolfsson Date: Thu, 23 Nov 2023 11:54:30 +0100 Subject: [PATCH] add missing files --- src/client.rs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 4 +-- 2 files changed, 68 insertions(+), 3 deletions(-) create mode 100644 src/client.rs diff --git a/src/client.rs b/src/client.rs new file mode 100644 index 000000000..d0a20a120 --- /dev/null +++ b/src/client.rs @@ -0,0 +1,67 @@ +use crate::prelude::*; +use jsonrpsee::ws_client::WsClientBuilder; +use subxt::backend::rpc::RpcClient as RawRpcClient; + +/// Wraps the subxt interfaces to make it easy to use for the staking-miner. +#[derive(Clone, Debug)] +pub struct Client { + /// Access to typed rpc calls from subxt. + rpc: RpcClient, + /// Access to chain APIs such as storage, events etc. + chain_api: ChainClient, + /// Raw RPC client. + raw_rpc: RawRpcClient, +} + +impl Client { + pub async fn new(uri: &str) -> Result { + log::debug!(target: LOG_TARGET, "attempting to connect to {:?}", uri); + + let rpc = loop { + match WsClientBuilder::default() + .max_request_size(u32::MAX) + .max_response_size(u32::MAX) + .request_timeout(std::time::Duration::from_secs(600)) + .build(&uri) + .await + { + Ok(rpc) => break RawRpcClient::new(rpc), + Err(e) => { + log::warn!( + target: LOG_TARGET, + "failed to connect to client due to {:?}, retrying soon..", + e, + ); + }, + }; + tokio::time::sleep(std::time::Duration::from_millis(2_500)).await; + }; + + let chain_api = ChainClient::from_rpc_client(rpc.clone()).await?; + + Ok(Self { rpc: RpcClient::new(rpc.clone()), raw_rpc: rpc, chain_api }) + } + + /// Get a reference to the RPC interface exposed by subxt. + pub fn rpc(&self) -> &RpcClient { + &self.rpc + } + + /// Get a reference to the chain API. + pub fn chain_api(&self) -> &ChainClient { + &self.chain_api + } + + // This is exposed until a new version of subxt is released. + pub async fn rpc_system_account_next_index( + &self, + account_id: &T, + ) -> Result + where + T: serde::Serialize, + { + self.raw_rpc + .request("system_accountNextIndex", subxt::rpc_params![&account_id]) + .await + } +} diff --git a/src/main.rs b/src/main.rs index d940d3520..86ca8ee22 100644 --- a/src/main.rs +++ b/src/main.rs @@ -123,9 +123,7 @@ async fn main() -> Result<(), Error> { log::info!(target: LOG_TARGET, "Connected to chain: {}", chain); epm::update_metadata_constants(client.chain_api()).await?; - SHARED_CLIENT - .set(client.clone()) - .expect("shared client only set once; qed"); + SHARED_CLIENT.set(client.clone()).expect("shared client only set once; qed"); // Start a new tokio task to perform the runtime updates in the background. // if this fails then the miner will be stopped and has to be re-started.