1pub mod apis;
82pub mod error;
83pub mod iota_client_config;
84pub mod json_rpc_error;
85pub mod wallet_context;
86
87use std::{
88 collections::{HashMap, VecDeque},
89 fmt::{Debug, Formatter},
90 marker::PhantomData,
91 pin::Pin,
92 str::FromStr,
93 sync::Arc,
94 task::Poll,
95 time::Duration,
96};
97
98use async_trait::async_trait;
99use base64::Engine;
100use futures::TryStreamExt;
101pub use iota_json as json;
102use iota_json_rpc_api::{
103 CLIENT_SDK_TYPE_HEADER, CLIENT_SDK_VERSION_HEADER, CLIENT_TARGET_API_VERSION_HEADER,
104};
105pub use iota_json_rpc_types as rpc_types;
106use iota_json_rpc_types::{
107 IotaObjectDataFilter, IotaObjectDataOptions, IotaObjectResponse, IotaObjectResponseQuery, Page,
108};
109use iota_sdk_types::{Address, ObjectId, StructTag};
110use iota_transaction_builder::{DataReader, TransactionBuilder};
111pub use iota_types as types;
112use jsonrpsee::{
113 core::client::ClientT,
114 http_client::{HeaderMap, HeaderValue, HttpClient, HttpClientBuilder},
115 rpc_params,
116 ws_client::{PingConfig, WsClient, WsClientBuilder},
117};
118use reqwest::header::HeaderName;
119use rustls::crypto::{CryptoProvider, ring};
120use serde_json::Value;
121
122use crate::{
123 apis::{CoinReadApi, EventApi, GovernanceApi, QuorumDriverApi, ReadApi},
124 error::{Error, IotaRpcResult},
125};
126
127pub const IOTA_COIN_TYPE: &str = "0x2::iota::IOTA";
128pub const IOTA_LOCAL_NETWORK_URL: &str = "http://127.0.0.1:9000";
129pub const IOTA_LOCAL_NETWORK_URL_0: &str = "http://0.0.0.0:9000";
130pub const IOTA_LOCAL_NETWORK_GRAPHQL_URL: &str = "http://127.0.0.1:9125";
131pub const IOTA_LOCAL_NETWORK_GAS_URL: &str = "http://127.0.0.1:9123/v1/gas";
132pub const IOTA_DEVNET_URL: &str = "https://api.devnet.iota.cafe";
133pub const IOTA_DEVNET_GRAPHQL_URL: &str = "https://graphql.devnet.iota.cafe";
134pub const IOTA_DEVNET_GAS_URL: &str = "https://faucet.devnet.iota.cafe/v1/gas";
135pub const IOTA_TESTNET_URL: &str = "https://api.testnet.iota.cafe";
136pub const IOTA_TESTNET_GRAPHQL_URL: &str = "https://graphql.testnet.iota.cafe";
137pub const IOTA_TESTNET_GAS_URL: &str = "https://faucet.testnet.iota.cafe/v1/gas";
138pub const IOTA_MAINNET_URL: &str = "https://api.mainnet.iota.cafe";
139pub const IOTA_MAINNET_GRAPHQL_URL: &str = "https://graphql.mainnet.iota.cafe";
140
141pub struct IotaClientBuilder {
166 request_timeout: Duration,
167 max_concurrent_requests: Option<usize>,
168 ws_url: Option<String>,
169 ws_ping_interval: Option<Duration>,
170 basic_auth: Option<(String, String)>,
171 tls_config: Option<rustls::ClientConfig>,
172 headers: Option<HashMap<String, String>>,
173}
174
175impl Default for IotaClientBuilder {
176 fn default() -> Self {
177 Self {
178 request_timeout: Duration::from_secs(60),
179 max_concurrent_requests: None,
180 ws_url: None,
181 ws_ping_interval: None,
182 basic_auth: None,
183 tls_config: None,
184 headers: None,
185 }
186 }
187}
188
189impl IotaClientBuilder {
190 pub fn request_timeout(mut self, request_timeout: Duration) -> Self {
192 self.request_timeout = request_timeout;
193 self
194 }
195
196 pub fn max_concurrent_requests(mut self, max_concurrent_requests: usize) -> Self {
198 self.max_concurrent_requests = Some(max_concurrent_requests);
199 self
200 }
201
202 pub fn ws_url(mut self, url: impl AsRef<str>) -> Self {
204 self.ws_url = Some(url.as_ref().to_string());
205 self
206 }
207
208 pub fn ws_ping_interval(mut self, duration: Duration) -> Self {
210 self.ws_ping_interval = Some(duration);
211 self
212 }
213
214 pub fn basic_auth(mut self, username: impl AsRef<str>, password: impl AsRef<str>) -> Self {
216 self.basic_auth = Some((username.as_ref().to_string(), password.as_ref().to_string()));
217 self
218 }
219
220 pub fn custom_headers(mut self, headers: HashMap<String, String>) -> Self {
222 self.headers = Some(headers);
223 self
224 }
225
226 pub fn tls_config(mut self, config: rustls::ClientConfig) -> Self {
228 self.tls_config = Some(config);
229 self
230 }
231
232 pub async fn build(self, http: impl AsRef<str>) -> IotaRpcResult<IotaClient> {
251 if CryptoProvider::get_default().is_none() {
252 ring::default_provider().install_default().ok();
253 }
254
255 let client_version = env!("CARGO_PKG_VERSION");
256 let mut headers = HeaderMap::new();
257 headers.insert(
258 CLIENT_TARGET_API_VERSION_HEADER,
259 HeaderValue::from_static(client_version),
261 );
262 headers.insert(
263 CLIENT_SDK_VERSION_HEADER,
264 HeaderValue::from_static(client_version),
265 );
266 headers.insert(CLIENT_SDK_TYPE_HEADER, HeaderValue::from_static("rust"));
267
268 if let Some((username, password)) = self.basic_auth {
269 let auth =
270 base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
271 headers.insert(
272 "authorization",
273 HeaderValue::from_str(&format!("Basic {auth}")).unwrap(),
275 );
276 }
277
278 if let Some(custom_headers) = self.headers {
279 for (key, value) in custom_headers {
280 let header_name =
281 HeaderName::from_str(&key).map_err(|e| Error::CustomHeaders(e.to_string()))?;
282 let header_value = HeaderValue::from_str(&value)
283 .map_err(|e| Error::CustomHeaders(e.to_string()))?;
284 headers.insert(header_name, header_value);
285 }
286 }
287
288 let ws = if let Some(url) = self.ws_url {
289 let mut builder = WsClientBuilder::default()
290 .max_request_size(2 << 30)
291 .set_headers(headers.clone())
292 .request_timeout(self.request_timeout);
293
294 if let Some(duration) = self.ws_ping_interval {
295 builder = builder.enable_ws_ping(PingConfig::new().ping_interval(duration))
296 }
297
298 if let Some(max_concurrent_requests) = self.max_concurrent_requests {
299 builder = builder.max_concurrent_requests(max_concurrent_requests);
300 }
301
302 builder.build(url).await.ok()
303 } else {
304 None
305 };
306
307 let mut http_builder = HttpClientBuilder::default()
308 .max_request_size(2 << 30)
309 .set_headers(headers)
310 .request_timeout(self.request_timeout);
311
312 if let Some(max_concurrent_requests) = self.max_concurrent_requests {
313 http_builder = http_builder.max_concurrent_requests(max_concurrent_requests);
314 }
315
316 if let Some(tls_config) = self.tls_config {
317 http_builder = http_builder.with_custom_cert_store(tls_config);
318 }
319
320 let http = http_builder.build(http)?;
321
322 let info = Self::get_server_info(&http, &ws).await?;
323
324 let rpc = RpcClient { http, ws, info };
325 let api = Arc::new(rpc);
326 let read_api = Arc::new(ReadApi::new(api.clone()));
327 let quorum_driver_api = QuorumDriverApi::new(api.clone());
328 let event_api = EventApi::new(api.clone());
329 let transaction_builder = TransactionBuilder::new(read_api.clone());
330 let coin_read_api = CoinReadApi::new(api.clone());
331 let governance_api = GovernanceApi::new(api.clone());
332
333 Ok(IotaClient {
334 api,
335 transaction_builder,
336 read_api,
337 coin_read_api,
338 event_api,
339 quorum_driver_api,
340 governance_api,
341 })
342 }
343
344 pub async fn build_localnet(self) -> IotaRpcResult<IotaClient> {
364 self.build(IOTA_LOCAL_NETWORK_URL).await
365 }
366
367 pub async fn build_devnet(self) -> IotaRpcResult<IotaClient> {
386 self.build(IOTA_DEVNET_URL).await
387 }
388
389 pub async fn build_testnet(self) -> IotaRpcResult<IotaClient> {
408 self.build(IOTA_TESTNET_URL).await
409 }
410
411 pub async fn build_mainnet(self) -> IotaRpcResult<IotaClient> {
430 self.build(IOTA_MAINNET_URL).await
431 }
432
433 async fn get_server_info(
437 http: &HttpClient,
438 ws: &Option<WsClient>,
439 ) -> Result<ServerInfo, Error> {
440 let rpc_spec: Value = http.request("rpc.discover", rpc_params![]).await?;
441 let version = rpc_spec
442 .pointer("/info/version")
443 .and_then(|v| v.as_str())
444 .ok_or_else(|| {
445 Error::Data("Fail parsing server version from rpc.discover endpoint.".into())
446 })?;
447 let rpc_methods = Self::parse_methods(&rpc_spec)?;
448
449 let subscriptions = if let Some(ws) = ws {
450 match ws.request("rpc.discover", rpc_params![]).await {
451 Ok(rpc_spec) => Self::parse_methods(&rpc_spec)?,
452 Err(_) => Vec::new(),
453 }
454 } else {
455 Vec::new()
456 };
457 let iota_system_state_v2_support =
458 rpc_methods.contains(&"iotax_getLatestIotaSystemStateV2".to_string());
459 Ok(ServerInfo {
460 rpc_methods,
461 subscriptions,
462 version: version.to_string(),
463 iota_system_state_v2_support,
464 })
465 }
466
467 fn parse_methods(server_spec: &Value) -> Result<Vec<String>, Error> {
468 let methods = server_spec
469 .pointer("/methods")
470 .and_then(|methods| methods.as_array())
471 .ok_or_else(|| {
472 Error::Data("Fail parsing server information from rpc.discover endpoint.".into())
473 })?;
474
475 Ok(methods
476 .iter()
477 .flat_map(|method| method["name"].as_str())
478 .map(|s| s.into())
479 .collect())
480 }
481}
482
483#[derive(Clone)]
520pub struct IotaClient {
521 api: Arc<RpcClient>,
522 transaction_builder: TransactionBuilder,
523 read_api: Arc<ReadApi>,
524 coin_read_api: CoinReadApi,
525 event_api: EventApi,
526 quorum_driver_api: QuorumDriverApi,
527 governance_api: GovernanceApi,
528}
529
530pub(crate) struct RpcClient {
531 http: HttpClient,
532 ws: Option<WsClient>,
533 info: ServerInfo,
534}
535
536impl Debug for RpcClient {
537 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
538 write!(
539 f,
540 "RPC client. Http: {:?}, Websocket: {:?}",
541 self.http, self.ws
542 )
543 }
544}
545
546struct ServerInfo {
549 rpc_methods: Vec<String>,
550 subscriptions: Vec<String>,
551 version: String,
552 iota_system_state_v2_support: bool,
553}
554
555impl IotaClient {
556 pub fn available_rpc_methods(&self) -> &Vec<String> {
559 &self.api.info.rpc_methods
560 }
561
562 pub fn available_subscriptions(&self) -> &Vec<String> {
565 &self.api.info.subscriptions
566 }
567
568 pub fn api_version(&self) -> &str {
574 &self.api.info.version
575 }
576
577 pub fn check_api_version(&self) -> IotaRpcResult<()> {
580 let server_version = self.api_version();
581 let client_version = env!("CARGO_PKG_VERSION");
582 if server_version != client_version {
583 return Err(Error::ServerVersionMismatch {
584 client_version: client_version.to_string(),
585 server_version: server_version.to_string(),
586 });
587 };
588 Ok(())
589 }
590
591 pub fn coin_read_api(&self) -> &CoinReadApi {
593 &self.coin_read_api
594 }
595
596 pub fn event_api(&self) -> &EventApi {
598 &self.event_api
599 }
600
601 pub fn governance_api(&self) -> &GovernanceApi {
603 &self.governance_api
604 }
605
606 pub fn quorum_driver_api(&self) -> &QuorumDriverApi {
608 &self.quorum_driver_api
609 }
610
611 pub fn read_api(&self) -> &ReadApi {
613 &self.read_api
614 }
615
616 pub fn transaction_builder(&self) -> &TransactionBuilder {
618 &self.transaction_builder
619 }
620
621 pub fn http(&self) -> &HttpClient {
623 &self.api.http
624 }
625
626 pub fn ws(&self) -> Option<&WsClient> {
628 self.api.ws.as_ref()
629 }
630}
631
632#[async_trait]
633impl DataReader for ReadApi {
634 async fn get_owned_objects(
635 &self,
636 address: Address,
637 object_type: StructTag,
638 cursor: Option<ObjectId>,
639 limit: Option<usize>,
640 options: IotaObjectDataOptions,
641 ) -> Result<iota_json_rpc_types::ObjectsPage, anyhow::Error> {
642 let query = Some(IotaObjectResponseQuery {
643 filter: Some(IotaObjectDataFilter::StructType(object_type)),
644 options: Some(options),
645 });
646
647 Ok(self
648 .get_owned_objects(address, query, cursor, limit)
649 .await?)
650 }
651
652 async fn get_object_with_options(
653 &self,
654 object_id: ObjectId,
655 options: IotaObjectDataOptions,
656 ) -> Result<IotaObjectResponse, anyhow::Error> {
657 Ok(self.get_object_with_options(object_id, options).await?)
658 }
659
660 async fn get_reference_gas_price(&self) -> Result<u64, anyhow::Error> {
662 Ok(self.get_reference_gas_price().await?)
663 }
664}
665
666pub trait PagedFn<O, C, F, E>: Sized + Fn(Option<C>) -> F
669where
670 O: Send,
671 C: Send,
672 F: futures::Future<Output = Result<Page<O, C>, E>> + Send,
673{
674 fn collect<T>(self) -> impl futures::Future<Output = Result<T, E>>
676 where
677 T: Default + Extend<O>,
678 {
679 self.stream().try_collect::<T>()
680 }
681
682 fn stream(self) -> PagedStream<O, C, F, E, Self> {
684 PagedStream::new(self)
685 }
686}
687
688impl<O, C, F, E, Fun> PagedFn<O, C, F, E> for Fun
689where
690 Fun: Fn(Option<C>) -> F,
691 O: Send,
692 C: Send,
693 F: futures::Future<Output = Result<Page<O, C>, E>> + Send,
694{
695}
696
697pub struct PagedStream<O, C, F, E, Fun> {
700 fun: Fun,
701 fut: Pin<Box<F>>,
702 next: VecDeque<O>,
703 has_next_page: bool,
704 _data: PhantomData<(E, C)>,
705}
706
707impl<O, C, F, E, Fun> PagedStream<O, C, F, E, Fun>
708where
709 Fun: Fn(Option<C>) -> F,
710{
711 pub fn new(fun: Fun) -> Self {
712 let fut = fun(None);
713 Self {
714 fun,
715 fut: Box::pin(fut),
716 next: Default::default(),
717 has_next_page: true,
718 _data: PhantomData,
719 }
720 }
721}
722
723impl<O, C, F, E, Fun> futures::Stream for PagedStream<O, C, F, E, Fun>
724where
725 O: Send,
726 C: Send,
727 F: futures::Future<Output = Result<Page<O, C>, E>> + Send,
728 Fun: Fn(Option<C>) -> F,
729{
730 type Item = Result<O, E>;
731
732 fn poll_next(
733 self: std::pin::Pin<&mut Self>,
734 cx: &mut std::task::Context<'_>,
735 ) -> Poll<Option<Self::Item>> {
736 let this = unsafe { self.get_unchecked_mut() };
737 if this.next.is_empty() && this.has_next_page {
738 match this.fut.as_mut().poll(cx) {
739 Poll::Ready(res) => match res {
740 Ok(mut page) => {
741 this.next.extend(page.data);
742 this.has_next_page = page.has_next_page;
743 if this.has_next_page {
744 this.fut.set((this.fun)(page.next_cursor.take()));
745 }
746 }
747 Err(e) => {
748 this.has_next_page = false;
749 return Poll::Ready(Some(Err(e)));
750 }
751 },
752 Poll::Pending => return Poll::Pending,
753 }
754 }
755 Poll::Ready(this.next.pop_front().map(Ok))
756 }
757}
758
759#[cfg(test)]
760mod test {
761 use futures::StreamExt;
762 use iota_json_rpc_types::Page;
763
764 use super::*;
765
766 #[tokio::test]
767 async fn test_get_all_pages() {
768 let data = (0..10000).collect::<Vec<_>>();
769 struct Endpoint {
770 data: Vec<i32>,
771 }
772
773 impl Endpoint {
774 async fn get_page(&self, cursor: Option<usize>) -> anyhow::Result<Page<i32, usize>> {
775 const PAGE_SIZE: usize = 100;
776 anyhow::ensure!(cursor.is_none_or(|v| v < self.data.len()), "invalid cursor");
777 let index = cursor.unwrap_or_default();
778 let data = self.data[index..]
779 .iter()
780 .copied()
781 .take(PAGE_SIZE)
782 .collect::<Vec<_>>();
783 let has_next_page = self.data.len() > index + PAGE_SIZE;
784 Ok(Page {
785 data,
786 next_cursor: has_next_page.then_some(index + PAGE_SIZE),
787 has_next_page,
788 })
789 }
790 }
791
792 let endpoint = Endpoint { data };
793
794 let mut stream = PagedFn::stream(async |cursor| endpoint.get_page(cursor).await);
795
796 assert_eq!(
797 stream
798 .by_ref()
799 .take(9999)
800 .try_collect::<Vec<_>>()
801 .await
802 .unwrap(),
803 endpoint.data[..9999]
804 );
805 assert_eq!(stream.by_ref().try_next().await.unwrap(), Some(9999));
806 assert!(stream.try_next().await.unwrap().is_none());
807
808 let mut bad_stream = PagedFn::stream(async |_| endpoint.get_page(Some(99999)).await);
809
810 assert!(bad_stream.try_next().await.is_err());
811 }
812}