1use std::collections::{BTreeMap, BTreeSet, HashMap};
6
7use async_graphql::{connection::Connection, dataloader::Loader, *};
8use diesel::{ExpressionMethods, OptionalExtension, QueryDsl, SelectableHelper};
9use fastcrypto::encoding::{Base58, Encoding};
10use iota_indexer::{models::epoch::QueryableEpochInfo, schema::epochs};
11use iota_sdk_types::CheckpointCommitment as EpochCommitment;
12
13use crate::{
14 config::DEFAULT_PAGE_SIZE,
15 context_data::db_data_provider::PgManager,
16 data::{DataLoader, Db, DbConnection, QueryExecutor},
17 error::Error,
18 server::watermark_task::Watermark,
19 types::{
20 big_int::BigInt,
21 chain_identifier::ChainIdentifierCache,
22 checkpoint::{self, Checkpoint, CheckpointConnection},
23 cursor::Page,
24 date_time::DateTime,
25 protocol_config::ProtocolConfigs,
26 system_state_summary::{NativeStateValidatorInfo, SystemStateSummary},
27 transaction_block::{
28 self, TransactionBlock, TransactionBlockConnection, TransactionBlockFilter,
29 },
30 uint53::UInt53,
31 validator_set::ValidatorSet,
32 },
33};
34
35#[derive(Clone)]
36pub(crate) struct Epoch {
37 pub stored: QueryableEpochInfo,
38 pub checkpoint_viewed_at: u64,
39}
40
41#[derive(Copy, Clone, Hash, Eq, PartialEq, Debug)]
44struct EpochKey {
45 pub epoch_id: u64,
46 pub checkpoint_viewed_at: u64,
47}
48
49#[Object]
57impl Epoch {
58 async fn epoch_id(&self) -> Result<UInt53> {
61 UInt53::try_from(self.stored.epoch as u64).extend()
62 }
63
64 async fn reference_gas_price(&self) -> Option<BigInt> {
67 Some(BigInt::from(self.stored.reference_gas_price as u64))
68 }
69
70 async fn validator_set(&self, ctx: &Context<'_>) -> Result<Option<ValidatorSet>> {
75 let system_state = ctx
76 .data_unchecked::<PgManager>()
77 .fetch_iota_system_state(Some(self.stored.epoch as u64))
78 .await?;
79
80 let validator_set = NativeStateValidatorInfo::from(system_state).into_validator_set(
81 self.stored.total_stake as u64,
82 self.checkpoint_viewed_at,
83 self.stored.epoch as u64,
84 )?;
85 Ok(Some(validator_set))
86 }
87
88 async fn start_timestamp(&self) -> Result<DateTime, Error> {
90 DateTime::from_ms(self.stored.epoch_start_timestamp)
91 }
92
93 async fn end_timestamp(&self) -> Result<Option<DateTime>, Error> {
95 self.stored
96 .epoch_end_timestamp
97 .map(DateTime::from_ms)
98 .transpose()
99 }
100
101 async fn total_checkpoints(&self, ctx: &Context<'_>) -> Result<Option<UInt53>> {
103 let last = match self.stored.last_checkpoint_id {
104 Some(last) => last as u64,
105 None => {
106 let Watermark { checkpoint, .. } = *ctx.data_unchecked();
107 checkpoint
108 }
109 };
110
111 Ok(Some(
112 UInt53::try_from(last - self.stored.first_checkpoint_id as u64 + 1).extend()?,
113 ))
114 }
115
116 async fn total_transactions(&self) -> Result<Option<UInt53>> {
118 self.stored
120 .epoch_total_transactions()
121 .map(|v| UInt53::try_from(v as u64))
122 .transpose()
123 .extend()
124 }
125
126 async fn total_gas_fees(&self) -> Option<BigInt> {
128 self.stored.total_gas_fees.map(BigInt::from)
129 }
130
131 async fn total_stake_rewards(&self) -> Option<BigInt> {
133 self.stored
134 .total_stake_rewards_distributed
135 .map(BigInt::from)
136 }
137
138 async fn fund_size(&self) -> Option<BigInt> {
142 Some(BigInt::from(self.stored.storage_fund_balance))
143 }
144
145 async fn net_inflow(&self) -> Option<BigInt> {
148 if let (Some(fund_inflow), Some(fund_outflow)) =
149 (self.stored.storage_charge, self.stored.storage_rebate)
150 {
151 Some(BigInt::from(fund_inflow - fund_outflow))
152 } else {
153 None
154 }
155 }
156
157 async fn fund_inflow(&self) -> Option<BigInt> {
159 self.stored.storage_charge.map(BigInt::from)
160 }
161
162 async fn fund_outflow(&self) -> Option<BigInt> {
165 self.stored.storage_rebate.map(BigInt::from)
166 }
167
168 async fn protocol_configs(&self, ctx: &Context<'_>) -> Result<ProtocolConfigs> {
171 ProtocolConfigs::query(ctx.data_unchecked(), Some(self.protocol_version()))
172 .await
173 .extend()
174 }
175
176 #[graphql(flatten)]
177 async fn system_state_summary(&self, ctx: &Context<'_>) -> Result<SystemStateSummary> {
178 let mut state = ctx
179 .data_unchecked::<PgManager>()
180 .fetch_iota_system_state(Some(self.stored.epoch as u64))
181 .await?;
182 let chain = ctx
183 .data_unchecked::<ChainIdentifierCache>()
184 .read(ctx.data_unchecked(), ctx.data_unchecked())
185 .await
186 .extend()?
187 .into_inner()
188 .chain();
189 state.apply_protocol_config_validator_parameters(chain);
190 Ok(SystemStateSummary { native: state })
191 }
192
193 async fn live_object_set_digest(&self) -> Result<Option<String>> {
197 let Some(commitments) = self.stored.epoch_commitments.as_ref() else {
198 return Ok(None);
199 };
200 let commitments: Vec<EpochCommitment> = bcs::from_bytes(commitments).map_err(|e| {
201 Error::Internal(format!("Error deserializing commitments: {e}")).extend()
202 })?;
203
204 let digest = commitments.into_iter().next().map(|commitment| {
205 let EpochCommitment::EcmhLiveObjectSet { digest } = commitment else {
206 panic!("a new CheckpointCommitment variant was added and must be handled")
207 };
208 Base58::encode(digest.into_bytes())
209 });
210
211 Ok(digest)
212 }
213
214 async fn checkpoints(
216 &self,
217 ctx: &Context<'_>,
218 first: Option<u64>,
219 after: Option<checkpoint::Cursor>,
220 last: Option<u64>,
221 before: Option<checkpoint::Cursor>,
222 ) -> Result<CheckpointConnection> {
223 let page = Page::from_params(ctx.data_unchecked(), first, after, last, before)?;
224 let epoch = self.stored.epoch as u64;
225 Checkpoint::paginate(
226 ctx.data_unchecked(),
227 page,
228 Some(epoch),
229 self.checkpoint_viewed_at,
230 )
231 .await
232 .extend()
233 }
234
235 #[graphql(
237 complexity = "first.or(last).unwrap_or(DEFAULT_PAGE_SIZE as u64) as usize * child_complexity"
238 )]
239 async fn transaction_blocks(
240 &self,
241 ctx: &Context<'_>,
242 first: Option<u64>,
243 after: Option<transaction_block::Cursor>,
244 last: Option<u64>,
245 before: Option<transaction_block::Cursor>,
246 filter: Option<TransactionBlockFilter>,
247 ) -> Result<TransactionBlockConnection> {
248 let page = Page::from_params(ctx.data_unchecked(), first, after, last, before)?;
249
250 let Some(filter) = filter
251 .unwrap_or_default()
252 .intersect(TransactionBlockFilter {
253 after_checkpoint: (self.stored.first_checkpoint_id > 0)
255 .then(|| UInt53::try_from(self.stored.first_checkpoint_id as u64 - 1))
256 .transpose()
257 .extend()?,
258 before_checkpoint: self
259 .stored
260 .last_checkpoint_id
261 .map(|id| UInt53::try_from(id as u64 + 1))
262 .transpose()
263 .extend()?,
264 ..Default::default()
265 })
266 else {
267 return Ok(Connection::with_additional_fields(
268 false,
269 false,
270 Default::default(),
271 ));
272 };
273
274 TransactionBlock::paginate(ctx, page, filter, self.checkpoint_viewed_at)
275 .await
276 .extend()
277 }
278}
279
280impl Epoch {
281 pub(crate) fn protocol_version(&self) -> u64 {
283 self.stored.protocol_version as u64
284 }
285
286 pub(crate) async fn query(
289 ctx: &Context<'_>,
290 filter: Option<u64>,
291 checkpoint_viewed_at: u64,
292 ) -> Result<Option<Self>, Error> {
293 if let Some(epoch_id) = filter {
294 let DataLoader(dl) = ctx.data_unchecked();
295 dl.load_one(EpochKey {
296 epoch_id,
297 checkpoint_viewed_at,
298 })
299 .await
300 } else {
301 Self::query_latest_at(ctx.data_unchecked(), checkpoint_viewed_at).await
302 }
303 }
304
305 pub(crate) async fn query_latest_at(
309 db: &Db,
310 checkpoint_viewed_at: u64,
311 ) -> Result<Option<Self>, Error> {
312 use epochs::dsl;
313
314 let stored: Option<QueryableEpochInfo> = db
315 .execute(move |conn| {
316 conn.first(move || {
317 dsl::epochs
321 .select(QueryableEpochInfo::as_select())
322 .filter(dsl::first_checkpoint_id.le(checkpoint_viewed_at as i64))
323 .order_by(dsl::first_checkpoint_id.desc())
324 })
325 .optional()
326 })
327 .await
328 .map_err(|e| Error::Internal(format!("Failed to fetch epoch: {e}")))?;
329
330 Ok(stored.map(|stored| Epoch {
331 stored,
332 checkpoint_viewed_at,
333 }))
334 }
335}
336
337impl Loader<EpochKey> for Db {
338 type Value = Epoch;
339 type Error = Error;
340
341 async fn load(&self, keys: &[EpochKey]) -> Result<HashMap<EpochKey, Epoch>, Error> {
342 use epochs::dsl;
343
344 let epoch_ids: BTreeSet<_> = keys.iter().map(|key| key.epoch_id as i64).collect();
345 let epochs: Vec<QueryableEpochInfo> = self
346 .execute_repeatable(move |conn| {
347 conn.results(move || {
348 dsl::epochs
349 .select(QueryableEpochInfo::as_select())
350 .filter(dsl::epoch.eq_any(epoch_ids.iter().cloned()))
351 })
352 })
353 .await
354 .map_err(|e| Error::Internal(format!("Failed to fetch epochs: {e}")))?;
355
356 let epoch_id_to_stored: BTreeMap<_, _> = epochs
357 .into_iter()
358 .map(|stored| (stored.epoch as u64, stored))
359 .collect();
360
361 Ok(keys
362 .iter()
363 .filter_map(|key| {
364 let stored = epoch_id_to_stored.get(&key.epoch_id).cloned()?;
365 let epoch = Epoch {
366 stored,
367 checkpoint_viewed_at: key.checkpoint_viewed_at,
368 };
369
370 let start = epoch.stored.first_checkpoint_id as u64;
376 (key.checkpoint_viewed_at >= start).then_some((*key, epoch))
377 })
378 .collect())
379 }
380}