iota_sdk/apis/
governance.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::sync::Arc;
6
7use iota_json_rpc_api::GovernanceReadApiClient;
8use iota_json_rpc_types::{DelegatedStake, IotaCommittee};
9use iota_types::{
10    base_types::IotaAddress, iota_serde::BigInt,
11    iota_system_state::iota_system_state_summary::IotaSystemStateSummary,
12};
13
14use crate::{RpcClient, error::IotaRpcResult};
15
16/// Defines methods to get committee and staking info.
17#[derive(Debug, Clone)]
18pub struct GovernanceApi {
19    api: Arc<RpcClient>,
20}
21
22impl GovernanceApi {
23    pub(crate) fn new(api: Arc<RpcClient>) -> Self {
24        Self { api }
25    }
26
27    /// Get a list of delegated stakes for the given address.
28    pub async fn get_stakes(&self, owner: IotaAddress) -> IotaRpcResult<Vec<DelegatedStake>> {
29        Ok(self.api.http.get_stakes(owner).await?)
30    }
31
32    /// Get committee information for the given epoch.
33    ///
34    /// The epoch defaults to the current epoch.
35    ///
36    /// # Examples
37    ///
38    /// ```rust,no_run
39    /// use iota_sdk::IotaClientBuilder;
40    ///
41    /// #[tokio::main]
42    /// async fn main() -> Result<(), anyhow::Error> {
43    ///     let iota = IotaClientBuilder::default().build_testnet().await?;
44    ///     let committee_info = iota.governance_api().get_committee_info(None).await?;
45    ///     Ok(())
46    /// }
47    /// ```
48    pub async fn get_committee_info(
49        &self,
50        epoch: impl Into<Option<BigInt<u64>>>,
51    ) -> IotaRpcResult<IotaCommittee> {
52        Ok(self.api.http.get_committee_info(epoch.into()).await?)
53    }
54
55    /// Get the latest IOTA system state object on-chain.
56    ///
57    /// Use this method to access system information, such as the current epoch,
58    /// the protocol version, the reference gas price, the total stake, active
59    /// validators, and much more.
60    #[allow(deprecated)]
61    pub async fn get_latest_iota_system_state(&self) -> IotaRpcResult<IotaSystemStateSummary> {
62        if self.api.info.iota_system_state_v2_support {
63            Ok(self.api.http.get_latest_iota_system_state_v2().await?)
64        } else {
65            // Fallback to v1, v2 is not available on networks with protocol version < 5
66            Ok(self
67                .api
68                .http
69                .get_latest_iota_system_state()
70                .await
71                .map(IotaSystemStateSummary::from)?)
72        }
73    }
74
75    /// Get the reference gas price for the network.
76    pub async fn get_reference_gas_price(&self) -> IotaRpcResult<u64> {
77        Ok(*self.api.http.get_reference_gas_price().await?)
78    }
79}