wasi_sol/provider/dioxus/
connection.rs

1use std::{fmt, ops::Deref, rc::Rc, sync::Arc};
2
3use dioxus::prelude::*;
4
5use solana_client_wasm::WasmClient as RpcClient;
6
7use solana_sdk::commitment_config::CommitmentConfig;
8
9#[derive(Clone)]
10pub struct ConnectionContextState {
11    pub connection: Arc<RpcClient>,
12}
13
14impl PartialEq for ConnectionContextState {
15    fn eq(&self, other: &Self) -> bool {
16        Arc::ptr_eq(&self.connection, &other.connection)
17    }
18}
19impl fmt::Debug for ConnectionContextState {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        f.debug_struct("ConnectionContextState")
22            .field("commitment", &self.connection.commitment())
23            .finish()
24    }
25}
26
27#[derive(Clone, PartialEq)]
28pub struct ConnectionContext(Rc<ConnectionContextState>);
29
30impl Deref for ConnectionContext {
31    type Target = Rc<ConnectionContextState>;
32
33    fn deref(&self) -> &Self::Target {
34        &self.0
35    }
36}
37
38impl fmt::Debug for ConnectionContext {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.debug_struct("ConnectionContext")
41            .field("commitment", &self.connection.commitment())
42            .finish()
43    }
44}
45
46#[component]
47pub fn ConnectionProvider(props: ConnectionProps) -> Element {
48    let endpoint = use_signal(|| props.endpoint);
49    let connection_state = use_memo(move || {
50        Rc::new(ConnectionContextState {
51            connection: RpcClient::new_with_commitment(
52                (&endpoint.clone())(),
53                CommitmentConfig::confirmed(),
54            )
55            .into(),
56        })
57    });
58
59    use_context_provider(|| ConnectionContext(connection_state()));
60
61    rsx! { { &props.children } }
62}
63
64#[derive(Props, Clone, PartialEq)]
65pub struct ConnectionProps {
66    pub children: Element,
67    pub endpoint: &'static str,
68}
69
70#[component]
71pub fn use_connection() -> ConnectionContext {
72    use_context::<ConnectionContext>()
73}