1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
use crate::imports::*;
use js_sys::Array;
use kaspa_addresses::Address;
use kaspa_notify::notification::Notification as NotificationT;
pub use kaspa_rpc_macros::{build_wrpc_wasm_bindgen_interface, build_wrpc_wasm_bindgen_subscriptions};
pub use serde_wasm_bindgen::*;

type JsResult<T> = std::result::Result<T, JsError>;

struct NotificationSink(Function);
unsafe impl Send for NotificationSink {}
impl From<NotificationSink> for Function {
    fn from(f: NotificationSink) -> Self {
        f.0
    }
}

/// Kaspa RPC client
#[wasm_bindgen]
pub struct RpcClient {
    client: KaspaRpcClient,
    notification_task: AtomicBool,
    notification_ctl: DuplexChannel,
    notification_callback: Arc<Mutex<Option<NotificationSink>>>,
}

#[wasm_bindgen]
impl RpcClient {
    /// Create a new RPC client with [`Encoding`] and a `url`.
    #[wasm_bindgen(constructor)]
    pub fn new(encoding: Encoding, url: &str) -> RpcClient {
        RpcClient {
            client: KaspaRpcClient::new(encoding, url).unwrap_or_else(|err| panic!("{err}")),
            notification_task: AtomicBool::new(false),
            notification_ctl: DuplexChannel::oneshot(),
            notification_callback: Arc::new(Mutex::new(None)),
        }
    }

    /// Connect to the Kaspa RPC server. This function starts a background
    /// task that connects and reconnects to the server if the connection
    /// is terminated.  Use [`disconnect()`] to terminate the connection.
    pub async fn connect(&self) -> JsResult<()> {
        self.notification_task()?;
        self.client.start().await?;
        self.client.connect(true).await?; //.unwrap();
        Ok(())
    }

    /// Disconnect from the Kaspa RPC server.
    pub async fn disconnect(&self) -> JsResult<()> {
        self.clear_notification_callback();
        self.stop_notification_task().await?;
        self.client.stop().await?;
        self.client.shutdown().await?;
        Ok(())
    }

    async fn stop_notification_task(&self) -> JsResult<()> {
        if self.notification_task.load(Ordering::SeqCst) {
            self.notification_task.store(false, Ordering::SeqCst);
            self.notification_ctl.signal(()).await.map_err(|err| JsError::new(&err.to_string()))?;
        }
        Ok(())
    }

    fn clear_notification_callback(&self) {
        *self.notification_callback.lock().unwrap() = None;
    }

    /// Register a notification callback.
    pub async fn notify(&self, callback: JsValue) -> JsResult<()> {
        if callback.is_function() {
            let fn_callback: Function = callback.into();
            self.notification_callback.lock().unwrap().replace(NotificationSink(fn_callback));
        } else {
            self.stop_notification_task().await?;
            self.clear_notification_callback();
        }
        Ok(())
    }
}

impl RpcClient {
    /// Notification task receives notifications and executes them on the
    /// user-supplied callback function.
    fn notification_task(&self) -> JsResult<()> {
        let ctl_receiver = self.notification_ctl.request.receiver.clone();
        let ctl_sender = self.notification_ctl.response.sender.clone();
        let notification_receiver = self.client.notification_channel_receiver();
        let notification_callback = self.notification_callback.clone();

        spawn(async move {
            loop {
                select! {
                    _ = ctl_receiver.recv().fuse() => {
                        break;
                    },
                    msg = notification_receiver.recv().fuse() => {
                        // log_info!("notification: {:?}",msg);
                        if let Ok(notification) = &msg {
                            if let Some(callback) = notification_callback.lock().unwrap().as_ref() {
                                let op: RpcApiOps = notification.event_type().into();
                                let op_value = to_value(&op).map_err(|err|{
                                    log_error!("Notification handler - unable to convert notification op: {}",err.to_string());
                                }).ok();
                                let op_payload = notification.to_value().map_err(|err| {
                                    log_error!("Notification handler - unable to convert notification payload: {}",err.to_string());
                                }).ok();
                                if op_value.is_none() || op_payload.is_none() {
                                    continue;
                                }
                                if let Err(err) = callback.0.call2(&JsValue::undefined(), &op_value.unwrap(), &op_payload.unwrap()) {
                                    log_error!("Error while executing notification callback: {:?}",err);
                                }
                            }
                        }
                    }
                }
            }

            ctl_sender.send(()).await.ok();
        });

        Ok(())
    }
}

#[wasm_bindgen]
impl RpcClient {
    // experimental/test functions

    /// Subscription to DAA Score (test)
    #[wasm_bindgen(js_name = subscribeDaaScore)]
    pub async fn subscribe_daa_score(&self) -> JsResult<()> {
        self.client.start_notify(ListenerId::default(), Scope::VirtualDaaScoreChanged(VirtualDaaScoreChangedScope {})).await?;
        Ok(())
    }

    /// Unsubscribe from DAA Score (test)
    #[wasm_bindgen(js_name = unsubscribeDaaScore)]
    pub async fn unsubscribe_daa_score(&self) -> JsResult<()> {
        self.client.stop_notify(ListenerId::default(), Scope::VirtualDaaScoreChanged(VirtualDaaScoreChangedScope {})).await?;
        Ok(())
    }

    /// Subscription to UTXOs Changed notifications
    #[wasm_bindgen(js_name = subscribeUtxosChanged)]
    pub async fn subscribe_utxos_changed(&self, addresses: &JsValue) -> JsResult<()> {
        let addresses = Array::from(addresses)
            .to_vec()
            .into_iter()
            .map(|jsv| from_value(jsv).map_err(|err| JsError::new(&err.to_string())))
            .collect::<std::result::Result<Vec<Address>, JsError>>()?;
        self.client.start_notify(ListenerId::default(), Scope::UtxosChanged(UtxosChangedScope { addresses })).await?;
        Ok(())
    }

    /// Unsubscribe from DAA Score (test)
    #[wasm_bindgen(js_name = unsubscribeUtxosChanged)]
    pub async fn unsubscribe_utxos_changed(&self, addresses: &JsValue) -> JsResult<()> {
        let addresses = Array::from(addresses)
            .to_vec()
            .into_iter()
            .map(|jsv| from_value(jsv).map_err(|err| JsError::new(&err.to_string())))
            .collect::<std::result::Result<Vec<Address>, JsError>>()?;
        self.client.stop_notify(ListenerId::default(), Scope::UtxosChanged(UtxosChangedScope { addresses })).await?;
        Ok(())
    }

    // scope variant with field functions

    #[wasm_bindgen(js_name = subscribeVirtualChainChanged)]
    pub async fn subscribe_virtual_chain_changed(&self, include_accepted_transaction_ids: bool) -> JsResult<()> {
        self.client
            .start_notify(
                ListenerId::default(),
                Scope::VirtualChainChanged(VirtualChainChangedScope { include_accepted_transaction_ids }),
            )
            .await?;
        Ok(())
    }
    #[wasm_bindgen(js_name = unsubscribeVirtualChainChanged)]
    pub async fn unsubscribe_virtual_chain_changed(&self, include_accepted_transaction_ids: bool) -> JsResult<()> {
        self.client
            .stop_notify(
                ListenerId::default(),
                Scope::VirtualChainChanged(VirtualChainChangedScope { include_accepted_transaction_ids }),
            )
            .await?;
        Ok(())
    }

    // #[wasm_bindgen(js_name = subscribeUtxosChanged)]
    // pub async fn subscribe_utxos_changed(&self, addresses: Vec<Address>) -> JsResult<()> {
    //     self.client.start_notify(ListenerId::default(), Scope::UtxosChanged(UtxosChangedScope { addresses })).await?;
    //     Ok(())
    // }
    // #[wasm_bindgen(js_name = unsubscribeUtxosChanged)]
    // pub async fn unsubscribe_utxos_changed(&self, addresses: Vec<Address>) -> JsResult<()> {
    //     self.client.stop_notify(ListenerId::default(), Scope::UtxosChanged(UtxosChangedScope { addresses })).await?;
    //     Ok(())
    // }
}

// Build subscribe functions
build_wrpc_wasm_bindgen_subscriptions!([
    BlockAdded,
    //VirtualChainChanged, // can't used this here due to non-C-style enum variant
    FinalityConflict,
    FinalityConflictResolved,
    //UtxosChanged, // can't used this here due to non-C-style enum variant
    SinkBlueScoreChanged,
    VirtualDaaScoreChanged,
    PruningPointUtxoSetOverride,
    NewBlockTemplate,
]);

// Build RPC method invocation functions. This macro
// takes two lists.  First list is for functions that
// do not have arguments and the second one is for
// functions that have single arguments (request).

build_wrpc_wasm_bindgen_interface!(
    [
        // functions with no arguments
        GetBlockCount,
        GetBlockDagInfo,
        GetCoinSupply,
        GetConnectedPeerInfo,
        GetInfo,
        GetPeerAddresses,
        GetProcessMetrics,
        GetSelectedTipHash,
        GetSinkBlueScore,
        Ping,
        Shutdown,
    ],
    [
        // functions with `request` argument
        AddPeer,
        Ban,
        EstimateNetworkHashesPerSecond,
        GetBalanceByAddress,
        GetBalancesByAddresses,
        GetBlock,
        GetBlocks,
        GetBlockTemplate,
        GetCurrentNetwork,
        GetHeaders,
        GetMempoolEntries,
        GetMempoolEntriesByAddresses,
        GetMempoolEntry,
        GetSubnetwork,
        // GetUtxosByAddresses,
        GetVirtualChainFromBlock,
        ResolveFinalityConflict,
        SubmitBlock,
        // SubmitTransaction,
        Unban,
    ]
);

#[wasm_bindgen]
impl RpcClient {
    #[wasm_bindgen(js_name = submitTransaction)]
    pub async fn submit_transaction(&self, request: JsValue) -> JsResult<JsValue> {
        log_info!("submit_transaction req: {:?}", request);
        let request: SubmitTransactionRequest = from_value(request)?;
        let result: RpcResult<SubmitTransactionResponse> = self.client.submit_transaction_call(request).await;
        let response: SubmitTransactionResponse = result.map_err(|err| wasm_bindgen::JsError::new(&err.to_string()))?;
        to_value(&response).map_err(|err| err.into())
    }

    #[wasm_bindgen(js_name = getUtxosByAddresses)]
    pub async fn get_utxos_by_addresses(&self, request: JsValue) -> JsResult<JsValue> {
        log_info!("get_utxos_by_addresses req: {:?}", request);
        let request: GetUtxosByAddressesRequest = from_value(request)?;
        //log_info!("get_utxos_by_addresses request: {:?}", request);
        let result: RpcResult<GetUtxosByAddressesResponse> = self.client.get_utxos_by_addresses_call(request).await;
        //log_info!("get_utxos_by_addresses result: {:?}", result);
        let response: GetUtxosByAddressesResponse = result.map_err(|err| wasm_bindgen::JsError::new(&err.to_string()))?;
        //log_info!("get_utxos_by_addresses resp: {:?}", response);
        to_value(&response).map_err(|err| err.into())
    }
}