Skip to main content

iota_json_rpc/
governance_api.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::{cmp::max, collections::BTreeMap, sync::Arc};
6
7use async_trait::async_trait;
8use cached::{SizedCache, proc_macro::cached};
9use iota_core::authority::AuthorityState;
10use iota_json_rpc_api::{
11    GovernanceReadApiOpenRpc, GovernanceReadApiServer, JsonRpcMetrics, QUERY_MAX_RESULT_LIMIT,
12    error_object_from_rpc,
13};
14use iota_json_rpc_types::{
15    DelegatedStake, DelegatedTimelockedStake, IotaCommittee,
16    IotaSystemStateSummary as IotaSystemStateSummarySchema,
17    IotaSystemStateSummaryV1 as IotaSystemStateSummaryV1Schema, Stake, StakeStatus,
18    TimelockedStake, ValidatorApy, ValidatorApys,
19};
20use iota_metrics::{spawn_monitored_blocking, spawn_monitored_task};
21use iota_open_rpc::Module;
22use iota_sdk_move_types::{
23    iota_framework::{dynamic_field::Field, object::ID},
24    iota_system::validator_wrapper::Validator,
25};
26use iota_sdk_types::{Address, ObjectId};
27use iota_types::{
28    committee::EpochId,
29    error::{IotaError, UserInputError},
30    governance::StakedIota,
31    iota_serde::BigInt,
32    iota_system_state::{
33        IotaSystemState, IotaSystemStateTrait, PoolTokenExchangeRate,
34        iota_system_state_summary::{
35            IotaSystemStateSummary, IotaSystemStateSummaryV1, IotaSystemStateSummaryV2,
36        },
37        validator_summary_from_wrapper,
38    },
39    object::{Object, ObjectRead},
40    timelock::timelocked_staked_iota::TimelockedStakedIota,
41};
42use itertools::Itertools;
43use jsonrpsee::{RpcModule, core::RpcResult};
44use serde::de::DeserializeOwned;
45use statrs::statistics::{Data, Median};
46use tokio::sync::{OwnedSemaphorePermit, Semaphore};
47use tracing::{info, instrument, warn};
48
49use crate::{
50    IotaRpcModule, ObjectProvider,
51    authority_state::StateRead,
52    error::{Error, IotaRpcInputError, RpcInterimResult},
53    logger::FutureWithTracing as _,
54};
55
56type ValidatorTable = (Address, ObjectId, ObjectId, u64, bool);
57
58/// Maximum number of stake reads that run at once. Each one reads every object
59/// the address owns on a thread of the shared blocking pool.
60const MAX_CONCURRENT_STAKE_READS: usize = 8;
61
62#[derive(Clone)]
63pub struct GovernanceReadApi {
64    state: Arc<dyn StateRead>,
65    pub metrics: Arc<JsonRpcMetrics>,
66    stake_read_permits: Arc<Semaphore>,
67}
68
69impl GovernanceReadApi {
70    pub fn new(state: Arc<AuthorityState>, metrics: Arc<JsonRpcMetrics>) -> Self {
71        Self {
72            state,
73            metrics,
74            stake_read_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_STAKE_READS)),
75        }
76    }
77
78    /// The latest system state summary, reporting the validator count limits
79    /// and stake thresholds that the protocol config enforces.
80    fn latest_system_state_summary(&self) -> Result<IotaSystemStateSummary, Error> {
81        let mut summary = self
82            .state
83            .get_system_state()?
84            .into_iota_system_state_summary();
85        summary
86            .apply_protocol_config_validator_parameters(self.state.get_chain_identifier()?.chain());
87        Ok(summary)
88    }
89
90    /// Waits until fewer than [`MAX_CONCURRENT_STAKE_READS`] stake reads run.
91    async fn acquire_stake_read_permit(&self) -> Result<OwnedSemaphorePermit, Error> {
92        self.stake_read_permits
93            .clone()
94            .acquire_owned()
95            .await
96            .map_err(|e| Error::Internal(e.into()))
97    }
98
99    async fn get_staked_iota(&self, owner: Address) -> Result<Vec<StakedIota>, Error> {
100        let state = self.state.clone();
101        let permit = self.acquire_stake_read_permit().await?;
102        let result = spawn_monitored_blocking!(move || {
103            let _permit = permit;
104            state.get_staked_iota(owner)
105        })
106        .await??;
107
108        self.metrics
109            .get_stake_iota_result_size
110            .observe(result.len() as f64);
111        self.metrics
112            .get_stake_iota_result_size_total
113            .inc_by(result.len() as u64);
114        Ok(result)
115    }
116
117    async fn get_timelocked_staked_iota(
118        &self,
119        owner: Address,
120    ) -> Result<Vec<TimelockedStakedIota>, Error> {
121        let state = self.state.clone();
122        let permit = self.acquire_stake_read_permit().await?;
123        let result = spawn_monitored_blocking!(move || {
124            let _permit = permit;
125            state.get_timelocked_staked_iota(owner)
126        })
127        .await??;
128
129        self.metrics
130            .get_stake_iota_result_size
131            .observe(result.len() as f64);
132        self.metrics
133            .get_stake_iota_result_size_total
134            .inc_by(result.len() as u64);
135        Ok(result)
136    }
137
138    async fn get_stakes_by_ids(
139        &self,
140        staked_iota_ids: Vec<ObjectId>,
141    ) -> Result<Vec<DelegatedStake>, Error> {
142        if staked_iota_ids.len() > *QUERY_MAX_RESULT_LIMIT {
143            Err(IotaRpcInputError::SizeLimitExceeded(
144                QUERY_MAX_RESULT_LIMIT.to_string(),
145            ))?
146        }
147        let state = self.state.clone();
148        let stakes_read = spawn_monitored_task!(async move {
149            staked_iota_ids
150                .iter()
151                .map(|id| state.get_object_read(id))
152                .collect::<Result<Vec<_>, _>>()
153        })
154        .await??;
155
156        if stakes_read.is_empty() {
157            return Ok(vec![]);
158        }
159
160        let stakes: Vec<(StakedIota, bool)> = self
161            .stakes_with_status(stakes_read.into_iter())
162            .await?
163            .into_iter()
164            .map(|(o, b)| StakedIota::try_from(&o).map(|stake| (stake, b)))
165            .collect::<Result<_, _>>()?;
166
167        self.get_delegated_stakes(stakes).await
168    }
169
170    async fn get_stakes(&self, owner: Address) -> Result<Vec<DelegatedStake>, Error> {
171        let timer = self.metrics.get_stake_iota_latency.start_timer();
172        let stakes = self.get_staked_iota(owner).await?;
173        if stakes.is_empty() {
174            return Ok(vec![]);
175        }
176        drop(timer);
177
178        let _timer = self.metrics.get_delegated_iota_latency.start_timer();
179
180        let self_clone = self.clone();
181        spawn_monitored_task!(
182            self_clone.get_delegated_stakes(stakes.into_iter().map(|s| (s, true)).collect())
183        )
184        .await?
185    }
186
187    async fn get_timelocked_stakes_by_ids(
188        &self,
189        timelocked_staked_iota_ids: Vec<ObjectId>,
190    ) -> Result<Vec<DelegatedTimelockedStake>, Error> {
191        if timelocked_staked_iota_ids.len() > *QUERY_MAX_RESULT_LIMIT {
192            Err(IotaRpcInputError::SizeLimitExceeded(
193                QUERY_MAX_RESULT_LIMIT.to_string(),
194            ))?
195        }
196        let state = self.state.clone();
197        let stakes_read = spawn_monitored_task!(async move {
198            timelocked_staked_iota_ids
199                .iter()
200                .map(|id| state.get_object_read(id))
201                .collect::<Result<Vec<_>, _>>()
202        })
203        .await??;
204
205        if stakes_read.is_empty() {
206            return Ok(vec![]);
207        }
208
209        let stakes: Vec<(TimelockedStakedIota, bool)> = self
210            .stakes_with_status(stakes_read.into_iter())
211            .await?
212            .into_iter()
213            .map(|(o, b)| TimelockedStakedIota::try_from(&o).map(|stake| (stake, b)))
214            .collect::<Result<_, _>>()?;
215
216        self.get_delegated_timelocked_stakes(stakes).await
217    }
218
219    async fn get_timelocked_stakes(
220        &self,
221        owner: Address,
222    ) -> Result<Vec<DelegatedTimelockedStake>, Error> {
223        let timer = self.metrics.get_stake_iota_latency.start_timer();
224        let stakes = self.get_timelocked_staked_iota(owner).await?;
225        if stakes.is_empty() {
226            return Ok(vec![]);
227        }
228        drop(timer);
229
230        let _timer = self.metrics.get_delegated_iota_latency.start_timer();
231
232        let self_clone = self.clone();
233        spawn_monitored_task!(
234            self_clone
235                .get_delegated_timelocked_stakes(stakes.into_iter().map(|s| (s, true)).collect())
236        )
237        .await?
238    }
239
240    async fn get_delegated_stakes(
241        &self,
242        stakes: Vec<(StakedIota, bool)>,
243    ) -> Result<Vec<DelegatedStake>, Error> {
244        let pools = stakes.into_iter().fold(
245            BTreeMap::<_, Vec<_>>::new(),
246            |mut pools, (stake, exists)| {
247                pools
248                    .entry(stake.pool_id())
249                    .or_default()
250                    .push((stake, exists));
251                pools
252            },
253        );
254
255        let system_state = self.get_system_state()?;
256        let system_state_summary = IotaSystemStateSummaryV2::try_from(
257            system_state.clone().into_iota_system_state_summary(),
258        )?;
259
260        let rates = exchange_rates(&self.state, system_state_summary.epoch)
261            .await?
262            .into_iter()
263            // Try to find for any candidate validator exchange rate
264            .chain(candidate_validators_exchange_rate(&self.state)?)
265            // Try to find for any pending validator exchange rate
266            .chain(pending_validators_exchange_rate(&self.state)?)
267            .map(|rates| (rates.pool_id, rates))
268            .collect::<BTreeMap<_, _>>();
269
270        let mut delegated_stakes = vec![];
271        for (pool_id, stakes) in pools {
272            // Rate table and rate can be null when the pool is not active
273            let rate_table = rates.get(&pool_id).ok_or_else(|| {
274                IotaRpcInputError::GenericNotFound(format!(
275                    "Cannot find rates for staking pool {pool_id}"
276                ))
277            })?;
278            let current_rate = rate_table.rates.first().map(|(_, rate)| rate);
279
280            let mut delegations = vec![];
281            for (stake, exists) in stakes {
282                let status = stake_status(
283                    system_state_summary.epoch,
284                    stake.activation_epoch(),
285                    stake.principal(),
286                    exists,
287                    current_rate,
288                    rate_table,
289                );
290                delegations.push(Stake {
291                    staked_iota_id: stake.id(),
292                    // TODO: this might change when we implement warm up period.
293                    stake_request_epoch: stake.activation_epoch() - 1,
294                    stake_active_epoch: stake.activation_epoch(),
295                    principal: stake.principal(),
296                    status,
297                })
298            }
299            delegated_stakes.push(DelegatedStake {
300                validator_address: rate_table.address,
301                staking_pool: pool_id,
302                stakes: delegations,
303            })
304        }
305        Ok(delegated_stakes)
306    }
307
308    async fn get_delegated_timelocked_stakes(
309        &self,
310        stakes: Vec<(TimelockedStakedIota, bool)>,
311    ) -> Result<Vec<DelegatedTimelockedStake>, Error> {
312        let pools = stakes.into_iter().fold(
313            BTreeMap::<_, Vec<_>>::new(),
314            |mut pools, (stake, exists)| {
315                pools
316                    .entry(stake.pool_id())
317                    .or_default()
318                    .push((stake, exists));
319                pools
320            },
321        );
322
323        let system_state = self.get_system_state()?;
324        let system_state_summary = IotaSystemStateSummaryV2::try_from(
325            system_state.clone().into_iota_system_state_summary(),
326        )?;
327
328        let rates = exchange_rates(&self.state, system_state_summary.epoch)
329            .await?
330            .into_iter()
331            // Try to find for any candidate validator exchange rate
332            .chain(candidate_validators_exchange_rate(&self.state)?)
333            // Try to find for any pending validator exchange rate
334            .chain(pending_validators_exchange_rate(&self.state)?)
335            .map(|rates| (rates.pool_id, rates))
336            .collect::<BTreeMap<_, _>>();
337
338        let mut delegated_stakes = vec![];
339        for (pool_id, stakes) in pools {
340            // Rate table and rate can be null when the pool is not active
341            let rate_table = rates.get(&pool_id).ok_or_else(|| {
342                IotaRpcInputError::GenericNotFound(format!(
343                    "Cannot find rates for staking pool {pool_id}"
344                ))
345            })?;
346            let current_rate = rate_table.rates.first().map(|(_, rate)| rate);
347
348            let mut delegations = vec![];
349            for (stake, exists) in stakes {
350                let status = stake_status(
351                    system_state_summary.epoch,
352                    stake.activation_epoch(),
353                    stake.principal(),
354                    exists,
355                    current_rate,
356                    rate_table,
357                );
358                delegations.push(TimelockedStake {
359                    timelocked_staked_iota_id: stake.id(),
360                    // TODO: this might change when we implement warm up period.
361                    stake_request_epoch: stake.activation_epoch() - 1,
362                    stake_active_epoch: stake.activation_epoch(),
363                    principal: stake.principal(),
364                    status,
365                    expiration_timestamp_ms: stake.expiration_timestamp_ms(),
366                    label: stake.label().clone(),
367                })
368            }
369            delegated_stakes.push(DelegatedTimelockedStake {
370                validator_address: rate_table.address,
371                staking_pool: pool_id,
372                stakes: delegations,
373            })
374        }
375        Ok(delegated_stakes)
376    }
377
378    async fn stakes_with_status(
379        &self,
380        iter: impl Iterator<Item = ObjectRead>,
381    ) -> Result<Vec<(Object, bool)>, Error> {
382        let mut stakes = vec![];
383
384        for stake in iter {
385            match stake {
386                ObjectRead::Exists(_, o, _) => stakes.push((o, true)),
387                ObjectRead::Deleted(object_ref) => {
388                    let Some(o) = self
389                        .state
390                        .find_object_lt_or_eq_version(
391                            &object_ref.object_id,
392                            &object_ref.version.previous().unwrap(),
393                        )
394                        .await?
395                    else {
396                        Err(IotaRpcInputError::UserInput(
397                            UserInputError::ObjectNotFound {
398                                object_id: object_ref.object_id,
399                                version: None,
400                            },
401                        ))?
402                    };
403                    stakes.push((o, false));
404                }
405                ObjectRead::NotExists(id) => Err(IotaRpcInputError::UserInput(
406                    UserInputError::ObjectNotFound {
407                        object_id: id,
408                        version: None,
409                    },
410                ))?,
411            }
412        }
413
414        Ok(stakes)
415    }
416
417    fn get_system_state(&self) -> Result<IotaSystemState, Error> {
418        Ok(self.state.get_system_state()?)
419    }
420}
421
422#[async_trait]
423impl GovernanceReadApiServer for GovernanceReadApi {
424    #[instrument(skip(self, staked_iota_ids), fields(staked_iota_ids = staked_iota_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>().join(", ")))]
425    async fn get_stakes_by_ids(
426        &self,
427        staked_iota_ids: Vec<ObjectId>,
428    ) -> RpcResult<Vec<DelegatedStake>> {
429        self.get_stakes_by_ids(staked_iota_ids).trace().await
430    }
431
432    #[instrument(skip(self, owner), fields(owner = %owner))]
433    async fn get_stakes(&self, owner: Address) -> RpcResult<Vec<DelegatedStake>> {
434        self.get_stakes(owner).trace().await
435    }
436
437    #[instrument(skip(self, timelocked_staked_iota_ids), fields(timelocked_staked_iota_ids = timelocked_staked_iota_ids.iter().map(|id| id.to_string()).collect::<Vec<String>>().join(", ")))]
438    async fn get_timelocked_stakes_by_ids(
439        &self,
440        timelocked_staked_iota_ids: Vec<ObjectId>,
441    ) -> RpcResult<Vec<DelegatedTimelockedStake>> {
442        self.get_timelocked_stakes_by_ids(timelocked_staked_iota_ids)
443            .trace()
444            .await
445    }
446
447    #[instrument(skip(self, owner), fields(owner = %owner))]
448    async fn get_timelocked_stakes(
449        &self,
450        owner: Address,
451    ) -> RpcResult<Vec<DelegatedTimelockedStake>> {
452        self.get_timelocked_stakes(owner).trace().await
453    }
454
455    #[instrument(skip(self))]
456    async fn get_committee_info(&self, epoch: Option<BigInt<u64>>) -> RpcResult<IotaCommittee> {
457        async move {
458            self.state
459                .get_or_latest_committee(epoch)
460                .map(|committee| committee.into())
461                .map_err(Error::from)
462        }
463        .trace()
464        .await
465    }
466
467    #[instrument(skip(self))]
468    async fn get_latest_iota_system_state_v2(&self) -> RpcResult<IotaSystemStateSummarySchema> {
469        async move { Ok(self.latest_system_state_summary()?.try_into()?) }
470            .trace()
471            .await
472    }
473
474    #[instrument(skip(self))]
475    async fn get_latest_iota_system_state(&self) -> RpcResult<IotaSystemStateSummaryV1Schema> {
476        async move {
477            Ok(IotaSystemStateSummaryV1::try_from(self.latest_system_state_summary()?)?.into())
478        }
479        .trace()
480        .await
481    }
482
483    #[instrument(skip(self))]
484    async fn get_reference_gas_price(&self) -> RpcResult<BigInt<u64>> {
485        async move {
486            let epoch_store = self.state.load_epoch_store_one_call_per_task();
487            Ok(epoch_store.reference_gas_price().into())
488        }
489        .trace()
490        .await
491    }
492
493    #[instrument(skip(self))]
494    async fn get_validators_apy(&self) -> RpcResult<ValidatorApys> {
495        info!("get_validator_apy");
496        let system_state_summary = self.get_latest_iota_system_state().await?;
497
498        let exchange_rate_table = exchange_rates(&self.state, system_state_summary.epoch)
499            .await
500            .map_err(|e| error_object_from_rpc(e.into()))?;
501
502        let apys = calculate_apys(exchange_rate_table);
503
504        Ok(ValidatorApys {
505            apys,
506            epoch: system_state_summary.epoch,
507        })
508    }
509}
510
511pub fn calculate_apys(exchange_rate_table: Vec<ValidatorExchangeRates>) -> Vec<ValidatorApy> {
512    let mut apys = vec![];
513
514    for rates in exchange_rate_table.into_iter().filter(|r| r.active) {
515        let exchange_rates = rates.rates.iter().map(|(_, rate)| rate);
516
517        let mean_apy = mean_apy_from_exchange_rates(exchange_rates);
518        apys.push(ValidatorApy {
519            address: rates.address,
520            apy: mean_apy,
521        });
522    }
523    apys
524}
525
526/// Calculate the APY using a 7-epoch moving average.
527///
528/// Returns the Mean by default, but falls back to the Median if outliers are
529/// detected. Outliers are defined as any APY > `MAX_VALID_APY` (100%) or if the
530/// trailing 8th epoch exchange rate is missing. This fallback protects against
531/// skewed results caused by large staking events or the spikes seen after
532/// missing exchange rates.
533pub fn mean_apy_from_exchange_rates<'er>(
534    exchange_rates: impl DoubleEndedIterator<Item = &'er PoolTokenExchangeRate> + Clone,
535) -> f64 {
536    // We set this value after observing the APY of validators in mainnet.
537    const MAX_VALID_APY: f64 = 1.00;
538    const SAMPLES: usize = 7;
539
540    let rates = exchange_rates.clone().dropping(1);
541    let rates_next = exchange_rates.dropping_back(1);
542
543    let mut apys = rates
544        .zip(rates_next)
545        .take(SAMPLES + 1)
546        .map(|(er, er_next)| calculate_apy(er, er_next))
547        .collect::<Vec<_>>();
548
549    // Return 0.0 if there is no data OR if any APY is negative
550    if apys.is_empty() || apys.iter().any(|&apy| apy < 0.0) {
551        return 0.0;
552    }
553    // If any single epoch has outliers (that is APY > MAX_VALID_APY or exchange
554    // rate for epoch e-8 is missing), we switch to Median. Otherwise, we use
555    // the standard Mean.
556    let has_outlier = apys.get(SAMPLES).is_some_and(|&apy| apy <= 0.0)
557        || apys.iter().any(|&apy| apy > MAX_VALID_APY);
558
559    apys.truncate(SAMPLES);
560
561    if has_outlier {
562        Data::new(apys).median()
563    } else {
564        let sum: f64 = apys.iter().sum();
565        sum / SAMPLES as f64
566    }
567}
568
569/// APY magnitudes below this threshold are treated as exactly zero.
570const APY_DUST_THRESHOLD: f64 = 1e-9;
571
572/// Calculate the APY from the exchange rate of two consecutive epochs
573/// (`er` is the older epoch, `er_next` the newer one).
574///
575/// The formula used is `APY_e = (er.rate - er_next.rate) / er_next.rate * 365`.
576fn calculate_apy(er: &PoolTokenExchangeRate, er_next: &PoolTokenExchangeRate) -> f64 {
577    let apy = ((er.rate() - er_next.rate()) / er_next.rate()) * 365.0;
578    if apy.abs() < APY_DUST_THRESHOLD {
579        0.0
580    } else {
581        apy
582    }
583}
584
585fn stake_status(
586    epoch: u64,
587    activation_epoch: u64,
588    principal: u64,
589    exists: bool,
590    current_rate: Option<&PoolTokenExchangeRate>,
591    rate_table: &ValidatorExchangeRates,
592) -> StakeStatus {
593    if !exists {
594        StakeStatus::Unstaked
595    } else if epoch >= activation_epoch {
596        // TODO: use dev_inspect to call a move function to get the estimated reward
597        let estimated_reward = if let Some(current_rate) = current_rate {
598            let stake_rate = rate_table
599                .rates
600                .iter()
601                .find_map(|(epoch, rate)| (*epoch == activation_epoch).then(|| rate.clone()))
602                .unwrap_or_default();
603            let estimated_reward =
604                ((stake_rate.rate() / current_rate.rate()) - 1.0) * principal as f64;
605            max(0, estimated_reward.round() as u64)
606        } else {
607            0
608        };
609        StakeStatus::Active { estimated_reward }
610    } else {
611        StakeStatus::Pending
612    }
613}
614
615/// Cached exchange rates for validators for the given epoch, the cache size is
616/// 1, it will be cleared when the epoch changes. rates are in descending order
617/// by epoch.
618#[cached(
619    type = "SizedCache<EpochId, Vec<ValidatorExchangeRates>>",
620    create = "{ SizedCache::with_size(1) }",
621    convert = "{ _current_epoch }",
622    result = true
623)]
624async fn exchange_rates(
625    state: &Arc<dyn StateRead>,
626    _current_epoch: EpochId,
627) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
628    Ok(active_validators_exchange_rates(state)?
629        .into_iter()
630        .chain(inactive_validators_exchange_rates(state)?.into_iter())
631        .collect())
632}
633
634// `cached` keeps results by the input key -- `current_epoch`.
635// `exchange_rates` is not a pure function, has effects via `state`
636// which `cached` is not aware of.
637// In normal node operation this does not create issues.
638// In tests that run several different networks the latter calls
639// will get incorrect/outdated cached results.
640// This function allows to clear `cached` cache for `exchange_rates`.
641#[cfg(msim)]
642pub async fn clear_exchange_rates_cache_for_testing() {
643    use cached::Cached;
644    if let Some(mutex) = ::cached::once_cell::sync::Lazy::get(&EXCHANGE_RATES) {
645        let mut cache = mutex.lock().await;
646        cache.cache_clear();
647    }
648}
649
650/// Get validator exchange rates
651fn validator_exchange_rates(
652    state: &Arc<dyn StateRead>,
653    tables: Vec<ValidatorTable>,
654) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
655    if tables.is_empty() {
656        return Ok(vec![]);
657    };
658
659    let mut exchange_rates = vec![];
660    // Get exchange rates for each validator
661    for (address, pool_id, exchange_rates_id, exchange_rates_size, active) in tables {
662        let mut rates = state
663            .get_dynamic_field_objects(exchange_rates_id, exchange_rates_size as usize)?
664            .into_iter()
665            .filter_map(|(object_id, object)| {
666                if object.is_none() {
667                    // The table's size says how many rates exist, so a row
668                    // that no longer resolves skews the APY inputs.
669                    warn!(?object_id, "an exchange-rate table entry did not resolve");
670                }
671                object
672            })
673            .map(|object| {
674                let field: Field<EpochId, PoolTokenExchangeRate> = decode_field(&object)?;
675                Ok::<_, IotaError>((field.name, field.value))
676            })
677            .collect::<Result<Vec<_>, _>>()?;
678
679        // Rates for some epochs might be missing due to safe mode, we need to backfill
680        // them.
681        rates = backfill_rates(rates);
682
683        exchange_rates.push(ValidatorExchangeRates {
684            address,
685            pool_id,
686            active,
687            rates,
688        });
689    }
690
691    Ok(exchange_rates)
692}
693
694/// Check for validators in the `Active` state and get its exchange rate
695fn active_validators_exchange_rates(
696    state: &Arc<dyn StateRead>,
697) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
698    let system_state_summary = IotaSystemStateSummaryV2::try_from(
699        state.get_system_state()?.into_iota_system_state_summary(),
700    )?;
701
702    let tables = system_state_summary
703        .active_validators
704        .into_iter()
705        .map(|validator| {
706            (
707                validator.iota_address,
708                validator.staking_pool_id,
709                validator.exchange_rates_id,
710                validator.exchange_rates_size,
711                true,
712            )
713        })
714        .collect();
715
716    validator_exchange_rates(state, tables)
717}
718
719/// Check for validators in the `Inactive` state and get its exchange rate
720fn inactive_validators_exchange_rates(
721    state: &Arc<dyn StateRead>,
722) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
723    let system_state_summary = IotaSystemStateSummaryV2::try_from(
724        state.get_system_state()?.into_iota_system_state_summary(),
725    )?;
726
727    let tables = validator_summary_from_system_state::<ID>(
728        state,
729        system_state_summary.inactive_pools_id,
730        system_state_summary.inactive_pools_size,
731        Some(system_state_summary.protocol_version),
732    )?;
733
734    validator_exchange_rates(state, tables)
735}
736
737/// Check for validators in the `Pending` state and get its exchange rate. For
738/// these validators, their exchange rates should not be cached as their state
739/// can occur during an epoch or across multiple ones. In contrast, exchange
740/// rates for `Active` and `Inactive` validators can be cached, as their state
741/// changes only at epoch change.
742fn pending_validators_exchange_rate(
743    state: &Arc<dyn StateRead>,
744) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
745    let system_state = state.get_system_state()?;
746    let object_store = state.get_object_store();
747
748    // Try to find for any pending active validator
749    let tables = system_state
750        .get_pending_active_validators(object_store)?
751        .into_iter()
752        .map(|pending_active_validator| {
753            (
754                pending_active_validator.iota_address,
755                pending_active_validator.staking_pool_id,
756                pending_active_validator.exchange_rates_id,
757                pending_active_validator.exchange_rates_size,
758                false,
759            )
760        })
761        .collect::<Vec<ValidatorTable>>();
762
763    validator_exchange_rates(state, tables)
764}
765
766/// Check for validators in the `Candidate` state and get its exchange rate. For
767/// these validators, their exchange rates should not be cached as their state
768/// can occur during an epoch or across multiple ones. In contrast, exchange
769/// rates for `Active` and `Inactive` validators can be cached, as their state
770/// changes only at epoch change.
771fn candidate_validators_exchange_rate(
772    state: &Arc<dyn StateRead>,
773) -> RpcInterimResult<Vec<ValidatorExchangeRates>> {
774    let system_state_summary = IotaSystemStateSummaryV2::try_from(
775        state.get_system_state()?.into_iota_system_state_summary(),
776    )?;
777
778    // From validator_candidates_id table get validator info using as key its
779    // Address
780    let tables = validator_summary_from_system_state::<Address>(
781        state,
782        system_state_summary.validator_candidates_id,
783        system_state_summary.validator_candidates_size,
784        Some(system_state_summary.protocol_version),
785    )?;
786
787    validator_exchange_rates(state, tables)
788}
789
790/// Fetches validator status information from `StateRead`.
791///
792/// This makes sense for validators not included in `IotaSystemStateSummary`.
793/// `IotaSystemStateSummary` only contains information about `Active`
794/// validators. To retrieve information about `Inactive`, `Candidate`, and
795/// `Pending` validators, we need to access dynamic fields within specific
796/// Move tables.
797///
798/// To retrieve validator status information, this function utilizes the
799/// corresponding `table_id` (an `ObjectId` value) and a `limit` to specify the
800/// number of records to fetch. Both the `table_id` and `limit` can be obtained
801/// from `IotaSystemStateSummary` in the caller. `K` is the type of the table's
802/// keys.
803///
804/// # Example
805///
806/// ```text
807/// // Get inactive validators
808/// let system_state_summary = state.get_system_state()?.into_iota_system_state_summary();
809/// let _ = validator_summary_from_system_state::<ID>(
810///     state,
811///     // ID of the object that maps from a staking pool ID to the inactive validator that has that pool as its staking pool.
812///     system_state_summary.inactive_pools_id,
813///     // Number of inactive staking pools.
814///     system_state_summary.inactive_pools_size,
815///     Some(system_state_summary.protocol_version),
816/// ).unwrap();
817/// ```
818///
819/// # Example
820///
821/// ```text
822/// // Get candidate validators
823/// let system_state_summary = state.get_system_state()?.into_iota_system_state_summary();
824/// let _ = validator_summary_from_system_state::<Address>(
825///     state,
826///     // ID of the object that stores preactive validators, mapping their addresses to their Validator structs
827///     system_state_summary.validator_candidates_id,
828///     // Number of preactive validators
829///     system_state_summary.validator_candidates_size,
830///     Some(system_state_summary.protocol_version),
831/// ).unwrap();
832/// ```
833fn validator_summary_from_system_state<K: DeserializeOwned>(
834    state: &Arc<dyn StateRead>,
835    table_id: ObjectId,
836    limit: u64,
837    protocol_version: Option<u64>,
838) -> RpcInterimResult<Vec<ValidatorTable>> {
839    let object_store = state.get_object_store();
840
841    state
842        .get_dynamic_field_objects(table_id, limit as usize)?
843        .into_iter()
844        .filter_map(|(object_id, object)| {
845            if object.is_none() {
846                // The table's size says how many validators exist, so a row
847                // that no longer resolves silently shortens the result.
848                warn!(?object_id, "a validator table entry did not resolve");
849            }
850            object
851        })
852        .map(|object| {
853            let field: Field<K, Validator> = decode_field(&object)?;
854            let validator_summary = validator_summary_from_wrapper(
855                object_store.as_ref(),
856                field.value,
857                protocol_version,
858            )?;
859
860            Ok((
861                validator_summary.iota_address,
862                validator_summary.staking_pool_id,
863                validator_summary.exchange_rates_id,
864                validator_summary.exchange_rates_size,
865                false,
866            ))
867        })
868        .collect()
869}
870
871/// Decodes a table entry's `Field` object.
872fn decode_field<K: DeserializeOwned, V: DeserializeOwned>(
873    object: &Object,
874) -> Result<Field<K, V>, IotaError> {
875    let move_object = object.data.as_opt_struct().ok_or_else(|| {
876        IotaError::DynamicFieldRead(format!(
877            "Dynamic field {:?} is not a Move object",
878            object.id()
879        ))
880    })?;
881    bcs::from_bytes(move_object.contents()).map_err(|e| IotaError::DynamicFieldRead(e.to_string()))
882}
883
884#[derive(Clone, Debug)]
885pub struct ValidatorExchangeRates {
886    pub address: Address,
887    pub pool_id: ObjectId,
888    pub active: bool,
889    pub rates: Vec<(EpochId, PoolTokenExchangeRate)>,
890}
891
892/// Backfill missing rates for some epochs due to safe mode. If a rate is
893/// missing for epoch e, we will use the rate for epoch e-1 to fill it. Rates
894/// returned are in descending order by epoch.
895fn backfill_rates(
896    mut rates: Vec<(EpochId, PoolTokenExchangeRate)>,
897) -> Vec<(EpochId, PoolTokenExchangeRate)> {
898    if rates.is_empty() {
899        return rates;
900    }
901    // ensure epochs are processed in increasing order
902    rates.sort_unstable_by_key(|(epoch_id, _)| *epoch_id);
903
904    // Check if there are any gaps in the epochs
905    let (min_epoch, _) = rates.first().expect("rates should not be empty");
906    let (max_epoch, _) = rates.last().expect("rates should not be empty");
907    let expected_len = (max_epoch - min_epoch + 1) as usize;
908    let current_len = rates.len();
909
910    // Only perform backfilling if there are gaps
911    if current_len == expected_len {
912        rates.reverse();
913        return rates;
914    }
915
916    let mut filled_rates: Vec<(EpochId, PoolTokenExchangeRate)> = Vec::with_capacity(expected_len);
917    let mut missing_rates = Vec::with_capacity(expected_len - current_len);
918    for (epoch_id, rate) in rates {
919        // fill gaps between the last processed epoch and the current one
920        if let Some((prev_epoch_id, prev_rate)) = filled_rates.last() {
921            for missing_epoch_id in prev_epoch_id + 1..epoch_id {
922                missing_rates.push((missing_epoch_id, prev_rate.clone()));
923            }
924        };
925
926        // append any missing_rates before adding the current epoch.
927        // if empty, nothing gets appended.
928        // if not empty, it will be empty afterwards because it was moved into
929        // filled_rates
930        filled_rates.append(&mut missing_rates);
931        filled_rates.push((epoch_id, rate));
932    }
933    filled_rates.reverse();
934    filled_rates
935}
936
937impl IotaRpcModule for GovernanceReadApi {
938    fn rpc(self) -> RpcModule<Self> {
939        self.into_rpc()
940    }
941
942    fn rpc_doc_module() -> Module {
943        GovernanceReadApiOpenRpc::module_doc()
944    }
945}
946
947#[cfg(test)]
948mod tests {
949    use std::sync::atomic::{AtomicUsize, Ordering};
950
951    use iota_types::iota_system_state::PoolTokenExchangeRate;
952    use jsonrpsee::types::error::INVALID_PARAMS_CODE;
953
954    use super::*;
955    use crate::authority_state::MockStateRead;
956
957    /// An API whose state answers every object read with `NotExists` and
958    /// counts the reads in `reads`.
959    fn api_counting_object_reads(reads: Arc<AtomicUsize>) -> GovernanceReadApi {
960        let mut state = MockStateRead::new();
961        state.expect_get_object_read().returning(move |id| {
962            reads.fetch_add(1, Ordering::Relaxed);
963            Ok(ObjectRead::NotExists(*id))
964        });
965        GovernanceReadApi {
966            state: Arc::new(state),
967            metrics: Arc::new(JsonRpcMetrics::new_for_tests()),
968            stake_read_permits: Arc::new(Semaphore::new(MAX_CONCURRENT_STAKE_READS)),
969        }
970    }
971
972    fn random_ids(count: usize) -> Vec<ObjectId> {
973        std::iter::repeat_with(ObjectId::random)
974            .take(count)
975            .collect()
976    }
977
978    fn size_limit_exceeded_msg() -> String {
979        IotaRpcInputError::SizeLimitExceeded(QUERY_MAX_RESULT_LIMIT.to_string()).to_string()
980    }
981
982    fn object_not_found_msg(id: ObjectId) -> String {
983        IotaRpcInputError::UserInput(UserInputError::ObjectNotFound {
984            object_id: id,
985            version: None,
986        })
987        .to_string()
988    }
989
990    #[tokio::test]
991    async fn stakes_by_ids_rejects_more_ids_than_the_limit_before_reading() {
992        let reads = Arc::new(AtomicUsize::new(0));
993        let api = api_counting_object_reads(reads.clone());
994
995        let err = GovernanceReadApiServer::get_stakes_by_ids(
996            &api,
997            random_ids(*QUERY_MAX_RESULT_LIMIT + 1),
998        )
999        .await
1000        .unwrap_err();
1001        assert_eq!(err.code(), INVALID_PARAMS_CODE);
1002        assert_eq!(err.message(), size_limit_exceeded_msg());
1003        assert_eq!(reads.load(Ordering::Relaxed), 0);
1004    }
1005
1006    #[tokio::test]
1007    async fn timelocked_stakes_by_ids_rejects_more_ids_than_the_limit_before_reading() {
1008        let reads = Arc::new(AtomicUsize::new(0));
1009        let api = api_counting_object_reads(reads.clone());
1010
1011        let err = GovernanceReadApiServer::get_timelocked_stakes_by_ids(
1012            &api,
1013            random_ids(*QUERY_MAX_RESULT_LIMIT + 1),
1014        )
1015        .await
1016        .unwrap_err();
1017        assert_eq!(err.code(), INVALID_PARAMS_CODE);
1018        assert_eq!(err.message(), size_limit_exceeded_msg());
1019        assert_eq!(reads.load(Ordering::Relaxed), 0);
1020    }
1021
1022    #[tokio::test]
1023    async fn stakes_and_timelocked_stakes_by_ids_read_every_id_at_the_limit() {
1024        let reads = Arc::new(AtomicUsize::new(0));
1025        let api = api_counting_object_reads(reads.clone());
1026
1027        let ids = random_ids(*QUERY_MAX_RESULT_LIMIT);
1028        let err = GovernanceReadApiServer::get_stakes_by_ids(&api, ids.clone())
1029            .await
1030            .unwrap_err();
1031        assert_eq!(err.message(), object_not_found_msg(ids[0]));
1032        assert_eq!(reads.load(Ordering::Relaxed), *QUERY_MAX_RESULT_LIMIT);
1033
1034        let ids = random_ids(*QUERY_MAX_RESULT_LIMIT);
1035        let err = GovernanceReadApiServer::get_timelocked_stakes_by_ids(&api, ids.clone())
1036            .await
1037            .unwrap_err();
1038        assert_eq!(err.message(), object_not_found_msg(ids[0]));
1039        assert_eq!(reads.load(Ordering::Relaxed), 2 * *QUERY_MAX_RESULT_LIMIT);
1040    }
1041
1042    #[test]
1043    fn calculate_apys_with_outliers() {
1044        let file =
1045            std::fs::File::open("src/unit_tests/data/validator_exchange_rate/rates-test.json")
1046                .unwrap();
1047        let rates: BTreeMap<String, Vec<(u64, PoolTokenExchangeRate)>> =
1048            serde_json::from_reader(file).unwrap();
1049
1050        let mut address_map = BTreeMap::new();
1051
1052        let exchange_rates = rates
1053            .into_iter()
1054            .map(|(validator, rates_vec)| {
1055                let address = Address::random();
1056                address_map.insert(address, validator);
1057                ValidatorExchangeRates {
1058                    address,
1059                    pool_id: ObjectId::random(),
1060                    active: true,
1061                    rates: backfill_rates(rates_vec),
1062                }
1063            })
1064            .collect();
1065
1066        let apys = calculate_apys(exchange_rates);
1067
1068        for apy in &apys {
1069            println!("{}: {}", address_map[&apy.address], apy.apy);
1070            assert!(apy.apy < 0.15)
1071        }
1072    }
1073
1074    #[test]
1075    fn calculate_apys_without_outliers() {
1076        let file =
1077            std::fs::File::open("src/unit_tests/data/validator_exchange_rate/rates-feb26.json")
1078                .unwrap();
1079        let rates: BTreeMap<String, Vec<(u64, PoolTokenExchangeRate)>> =
1080            serde_json::from_reader(file).unwrap();
1081
1082        let mut address_map = BTreeMap::new();
1083
1084        let exchange_rates = rates
1085            .into_iter()
1086            .map(|(validator, rates_vec)| {
1087                let address = Address::random();
1088                address_map.insert(address, validator);
1089                ValidatorExchangeRates {
1090                    address,
1091                    pool_id: ObjectId::random(),
1092                    active: true,
1093                    rates: backfill_rates(rates_vec),
1094                }
1095            })
1096            .collect();
1097
1098        let apys = calculate_apys(exchange_rates);
1099
1100        for apy in &apys {
1101            println!("{}: {}", address_map[&apy.address], apy.apy);
1102            assert!(apy.apy < 0.15)
1103        }
1104    }
1105
1106    #[test]
1107    fn calculate_apy_is_not_negative_for_zero_reward_epoch() {
1108        // Real mainnet exchange rates for two validators transitioning from
1109        // epoch 381 to 382, an epoch in which they earned no rewards. The rate is
1110        // therefore unchanged up to integer-truncation dust, so `calculate_apy`
1111        // must report an effectively-zero APY (within
1112        // `[0, APY_DUST_THRESHOLD)`).
1113        let cases = [
1114            (
1115                (48_913_429_030_426_080u64, 43_331_127_650_932_384u64),
1116                (48_641_042_011_532_656u64, 43_089_827_114_043_304u64),
1117            ),
1118            (
1119                (33_370_417_056_337_732u64, 29_578_114_234_284_444u64),
1120                (33_370_374_157_145_896u64, 29_578_076_210_270_704u64),
1121            ),
1122        ];
1123
1124        for ((i_old, t_old), (i_new, t_new)) in cases {
1125            let er = PoolTokenExchangeRate::new_for_testing(i_old, t_old);
1126            let er_next = PoolTokenExchangeRate::new_for_testing(i_new, t_new);
1127            let apy = calculate_apy(&er, &er_next);
1128            assert!(
1129                (0.0..APY_DUST_THRESHOLD).contains(&apy),
1130                "expected an effectively-zero, non-negative APY, got {apy}"
1131            );
1132        }
1133    }
1134
1135    #[test]
1136    fn test_backfill_rates_empty() {
1137        let rates = vec![];
1138        assert_eq!(backfill_rates(rates), vec![]);
1139    }
1140
1141    #[test]
1142    fn test_backfill_rates_no_gaps() {
1143        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1144        let rate2 = PoolTokenExchangeRate::new_for_testing(200, 220);
1145        let rate3 = PoolTokenExchangeRate::new_for_testing(300, 330);
1146        let rates = vec![(2, rate2.clone()), (3, rate3.clone()), (1, rate1.clone())];
1147
1148        let expected: Vec<(u64, PoolTokenExchangeRate)> = vec![(3, rate3), (2, rate2), (1, rate1)];
1149        assert_eq!(backfill_rates(rates), expected);
1150    }
1151
1152    #[test]
1153    fn test_backfill_single_rate() {
1154        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1155        let rates = vec![(1, rate1.clone())];
1156        let expected = vec![(1, rate1)];
1157        assert_eq!(backfill_rates(rates), expected);
1158    }
1159
1160    #[test]
1161    fn test_backfill_rates_with_gaps() {
1162        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1163        let rate3 = PoolTokenExchangeRate::new_for_testing(300, 330);
1164        let rate5 = PoolTokenExchangeRate::new_for_testing(500, 550);
1165        let rates = vec![(3, rate3.clone()), (1, rate1.clone()), (5, rate5.clone())];
1166
1167        let expected = vec![
1168            (5, rate5),
1169            (4, rate3.clone()),
1170            (3, rate3),
1171            (2, rate1.clone()),
1172            (1, rate1),
1173        ];
1174        assert_eq!(backfill_rates(rates), expected);
1175    }
1176
1177    #[test]
1178    fn test_backfill_rates_missing_middle_epoch() {
1179        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1180        let rate3 = PoolTokenExchangeRate::new_for_testing(300, 330);
1181        let rates = vec![(1, rate1.clone()), (3, rate3.clone())];
1182        let expected = vec![(3, rate3), (2, rate1.clone()), (1, rate1)];
1183        assert_eq!(backfill_rates(rates), expected);
1184    }
1185
1186    #[test]
1187    fn test_backfill_rates_missing_middle_epochs() {
1188        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1189        let rate4 = PoolTokenExchangeRate::new_for_testing(400, 440);
1190        let rates = vec![(1, rate1.clone()), (4, rate4.clone())];
1191        let expected = vec![
1192            (4, rate4),
1193            (3, rate1.clone()),
1194            (2, rate1.clone()),
1195            (1, rate1),
1196        ];
1197        assert_eq!(backfill_rates(rates), expected);
1198    }
1199
1200    #[test]
1201    fn test_backfill_rates_unordered_input() {
1202        let rate1 = PoolTokenExchangeRate::new_for_testing(100, 100);
1203        let rate3 = PoolTokenExchangeRate::new_for_testing(300, 330);
1204        let rate4 = PoolTokenExchangeRate::new_for_testing(400, 440);
1205        let rates = vec![(3, rate3.clone()), (1, rate1.clone()), (4, rate4.clone())];
1206        let expected = vec![(4, rate4), (3, rate3), (2, rate1.clone()), (1, rate1)];
1207        assert_eq!(backfill_rates(rates), expected);
1208    }
1209}