neo3/neo_clients/rpc/transports/
rw.rs1use crate::neo_clients::{JsonRpcProvider, ProviderError};
5use async_trait::async_trait;
6use serde::{de::DeserializeOwned, Serialize};
7use std::fmt::Display;
8use thiserror::Error;
9
10#[derive(Debug, Clone)]
19pub struct RwClient<Read, Write> {
20 r: Read,
22 w: Write,
24}
25
26impl<Read, Write> RwClient<Read, Write> {
27 pub fn new(r: Read, w: Write) -> RwClient<Read, Write> {
46 Self { r, w }
47 }
48
49 pub fn read_client(&self) -> &Read {
51 &self.r
52 }
53
54 pub fn write_client(&self) -> &Write {
56 &self.w
57 }
58
59 pub fn transpose(self) -> RwClient<Write, Read> {
61 let RwClient { r, w } = self;
62 RwClient::new(w, r)
63 }
64
65 pub fn split(self) -> (Read, Write) {
67 let RwClient { r, w } = self;
68 (r, w)
69 }
70}
71
72#[derive(Error, Debug)]
73pub enum RwClientError<Read, Write>
75where
76 Read: JsonRpcProvider,
77 <Read as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
78 Write: JsonRpcProvider,
79 <Write as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
80{
81 #[error("Read error: {0}")]
83 Read(Read::Error),
84 #[error("Write error: {0}")]
85 Write(Write::Error),
87}
88
89impl<Read, Write> From<RwClientError<Read, Write>> for ProviderError
90where
91 Read: JsonRpcProvider + 'static,
92 <Read as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
93 Write: JsonRpcProvider + 'static,
94 <Write as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
95{
96 fn from(src: RwClientError<Read, Write>) -> Self {
97 ProviderError::CustomError(src.to_string())
98 }
99}
100
101#[cfg_attr(target_arch = "wasm32", async_trait(? Send))]
102#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
103impl<Read, Write> JsonRpcProvider for RwClient<Read, Write>
104where
105 Read: JsonRpcProvider + 'static,
106 <Read as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
107 Write: JsonRpcProvider + 'static,
108 <Write as JsonRpcProvider>::Error: Sync + Send + 'static + Display,
109{
110 type Error = RwClientError<Read, Write>;
111
112 async fn fetch<T, R>(&self, method: &str, params: T) -> Result<R, Self::Error>
115 where
116 T: std::fmt::Debug + Serialize + Send + Sync,
117 R: DeserializeOwned + Send,
118 {
119 match method {
120 "neo_sendTransaction" | "neo_sendRawTransaction" =>
121 self.w.fetch(method, params).await.map_err(RwClientError::Write),
122 _ => self.r.fetch(method, params).await.map_err(RwClientError::Read),
123 }
124 }
125}