Skip to main content

ogmios_client/ledger_state_query/
client.rs

1//! Ledger State Query client implementation.
2
3use crate::connection::{
4    create_interaction_context, ConnectionConfig, InteractionContext, InteractionContextOptions,
5    InteractionType,
6};
7use crate::error::Result;
8use crate::schema::{
9    Address, BlockHeight, Epoch, EraStart, EraSummary, EraWithGenesis,
10    Constitution, GenesisConfiguration, GovernanceProposalState,
11    LiveStakeDistributionEntry, Point, ProjectedRewards, ProtocolParameters,
12    RewardAccount, RewardAccountSummary, Slot, StakeAddress, StakePoolId,
13    StakePoolPerformance, StakePoolView, Tip, TransactionOutputReference, UtcTime, Utxo,
14};
15use std::collections::HashMap;
16use std::sync::Arc;
17
18use super::query::{self, *};
19
20/// Options for creating a ledger state query client.
21#[derive(Debug, Clone, Default)]
22pub struct LedgerStateQueryClientOptions {
23    /// Automatically acquire ledger state at this point.
24    pub point: Option<Point>,
25}
26
27/// A ledger state query client for querying blockchain state.
28///
29/// This client provides methods for querying various aspects of the
30/// Cardano ledger state, such as UTXOs, stake pools, protocol parameters,
31/// and governance proposals.
32///
33/// # Example
34///
35/// ```rust,no_run
36/// use ogmios_client::ledger_state_query::LedgerStateQueryClient;
37/// use ogmios_client::connection::ConnectionConfig;
38///
39/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
40/// let client = LedgerStateQueryClient::connect(
41///     ConnectionConfig::default(),
42///     None
43/// ).await?;
44///
45/// // Get current epoch
46/// let epoch = client.epoch().await?;
47/// println!("Current epoch: {}", epoch);
48///
49/// // Get protocol parameters
50/// let params = client.protocol_parameters().await?;
51/// println!("Min fee coefficient: {}", params.min_fee_coefficient);
52///
53/// // Query UTXOs for an address
54/// let utxos = client.utxo_by_addresses(vec!["addr_test1...".to_string()]).await?;
55/// println!("Found {} UTXOs", utxos.len());
56///
57/// client.shutdown().await?;
58/// # Ok(())
59/// # }
60/// ```
61pub struct LedgerStateQueryClient {
62    /// The interaction context.
63    context: Arc<InteractionContext>,
64}
65
66impl LedgerStateQueryClient {
67    /// Create a new ledger state query client from an existing context.
68    pub fn new(context: InteractionContext) -> Self {
69        Self {
70            context: Arc::new(context),
71        }
72    }
73
74    /// Connect to Ogmios and create a new ledger state query client.
75    ///
76    /// # Arguments
77    ///
78    /// * `connection` - Connection configuration.
79    /// * `options` - Optional client options.
80    pub async fn connect(
81        connection: ConnectionConfig,
82        options: Option<LedgerStateQueryClientOptions>,
83    ) -> Result<Self> {
84        let context = create_interaction_context(InteractionContextOptions {
85            connection,
86            interaction_type: InteractionType::LongRunning,
87            ..Default::default()
88        })
89        .await?;
90
91        let client = Self::new(context);
92
93        // Optionally acquire ledger state at a specific point
94        if let Some(opts) = options {
95            if let Some(point) = opts.point {
96                client.acquire_ledger_state(Some(point)).await?;
97            }
98        }
99
100        Ok(client)
101    }
102
103    /// Get a reference to the interaction context.
104    pub fn context(&self) -> &InteractionContext {
105        &self.context
106    }
107
108    /// Acquire a ledger state at a specific point.
109    pub async fn acquire_ledger_state(&self, point: Option<Point>) -> Result<Slot> {
110        query::acquire_ledger_state(&self.context, point).await
111    }
112
113    /// Release the acquired ledger state.
114    pub async fn release_ledger_state(&self) -> Result<()> {
115        query::release_ledger_state(&self.context).await
116    }
117
118    /// Query the current constitution.
119    pub async fn constitution(&self) -> Result<Constitution> {
120        query::constitution(&self.context).await
121    }
122
123    /// Query the current epoch.
124    pub async fn epoch(&self) -> Result<Epoch> {
125        query::epoch(&self.context).await
126    }
127
128    /// Query the era start information.
129    pub async fn era_start(&self) -> Result<EraStart> {
130        query::era_start(&self.context).await
131    }
132
133    /// Query era summaries.
134    pub async fn era_summaries(&self) -> Result<Vec<EraSummary>> {
135        query::era_summaries(&self.context).await
136    }
137
138    /// Query genesis configuration for a specific era.
139    pub async fn genesis_configuration(&self, era: EraWithGenesis) -> Result<GenesisConfiguration> {
140        query::genesis_configuration(&self.context, era).await
141    }
142
143    /// Query governance proposals.
144    pub async fn governance_proposals(
145        &self,
146        filter: Option<GovernanceProposalFilter>,
147    ) -> Result<Vec<GovernanceProposalState>> {
148        query::governance_proposals(&self.context, filter).await
149    }
150
151    /// Query the ledger tip.
152    pub async fn ledger_tip(&self) -> Result<Point> {
153        query::ledger_tip(&self.context).await
154    }
155
156    /// Query the network tip.
157    pub async fn network_tip(&self) -> Result<Tip> {
158        query::network_tip(&self.context).await
159    }
160
161    /// Query the network block height.
162    pub async fn network_block_height(&self) -> Result<BlockHeight> {
163        query::network_block_height(&self.context).await
164    }
165
166    /// Query live stake distribution.
167    pub async fn live_stake_distribution(
168        &self,
169    ) -> Result<HashMap<StakePoolId, LiveStakeDistributionEntry>> {
170        query::live_stake_distribution(&self.context).await
171    }
172
173    /// Query the network start time.
174    pub async fn network_start_time(&self) -> Result<UtcTime> {
175        query::network_start_time(&self.context).await
176    }
177
178    /// Query projected rewards.
179    pub async fn projected_rewards(
180        &self,
181        stake_addresses: Vec<StakeAddress>,
182    ) -> Result<Vec<ProjectedRewards>> {
183        query::projected_rewards(
184            &self.context,
185            ProjectedRewardsFilter { stake_addresses },
186        )
187        .await
188    }
189
190    /// Query protocol parameters.
191    pub async fn protocol_parameters(&self) -> Result<ProtocolParameters> {
192        query::protocol_parameters(&self.context).await
193    }
194
195    /// Query reward account summaries.
196    pub async fn reward_account_summaries(
197        &self,
198        keys: Vec<StakeAddress>,
199    ) -> Result<HashMap<RewardAccount, RewardAccountSummary>> {
200        query::reward_account_summaries(&self.context, RewardAccountSummariesFilter { keys }).await
201    }
202
203    /// Query stake pools.
204    pub async fn stake_pools(
205        &self,
206        filter: Option<StakePoolsFilter>,
207        include_stake: bool,
208    ) -> Result<HashMap<StakePoolId, StakePoolView>> {
209        query::stake_pools(&self.context, filter, include_stake).await
210    }
211
212    /// Query stake pool performances.
213    pub async fn stake_pools_performances(
214        &self,
215    ) -> Result<HashMap<StakePoolId, StakePoolPerformance>> {
216        query::stake_pools_performances(&self.context).await
217    }
218
219    /// Query UTXOs.
220    pub async fn utxo(&self, filter: Option<UtxoFilter>) -> Result<Vec<Utxo>> {
221        query::utxo(&self.context, filter).await
222    }
223
224    /// Query UTXOs by addresses.
225    pub async fn utxo_by_addresses(&self, addresses: Vec<Address>) -> Result<Vec<Utxo>> {
226        query::utxo_by_addresses(&self.context, addresses).await
227    }
228
229    /// Query UTXOs by output references.
230    pub async fn utxo_by_output_references(
231        &self,
232        output_references: Vec<TransactionOutputReference>,
233    ) -> Result<Vec<Utxo>> {
234        query::utxo_by_output_references(&self.context, output_references).await
235    }
236
237    /// Shutdown the client.
238    pub async fn shutdown(&self) -> Result<()> {
239        self.context.shutdown().await
240    }
241}
242
243/// Create a ledger state query client.
244///
245/// This is a convenience function that creates a connection and client in one step.
246pub async fn create_ledger_state_query_client(
247    connection: ConnectionConfig,
248    options: Option<LedgerStateQueryClientOptions>,
249) -> Result<LedgerStateQueryClient> {
250    LedgerStateQueryClient::connect(connection, options).await
251}