Skip to main content

iota_types/
config.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2024 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use iota_sdk_types::{StructTag, TypeTag};
6use serde::{Deserialize, Serialize};
7
8use crate::{MoveTypeTagTrait, base_types::EpochId};
9
10/// Rust representation of the Move type 0x2::config::Setting.
11#[derive(Debug, Serialize, Deserialize)]
12pub struct Setting<V> {
13    pub data: Option<SettingData<V>>,
14}
15
16/// Rust representation of the Move type 0x2::config::SettingData.
17#[derive(Debug, Serialize, Deserialize)]
18pub struct SettingData<V> {
19    pub newer_value_epoch: u64,
20    pub newer_value: Option<V>,
21    pub older_value_opt: Option<V>,
22}
23
24pub fn setting_type(value_tag: TypeTag) -> StructTag {
25    StructTag::new_config_setting(value_tag)
26}
27
28impl<V: MoveTypeTagTrait> MoveTypeTagTrait for Setting<V> {
29    fn get_type_tag() -> TypeTag {
30        TypeTag::Struct(Box::new(setting_type(V::get_type_tag())))
31    }
32}
33
34impl<V> Setting<V> {
35    /// Calls `SettingData::read_value` on the setting's data.
36    /// The `data` should never be `None`, but for safety, this method returns
37    /// `None` if it is.
38    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
39        self.data.as_ref()?.read_value(cur_epoch)
40    }
41}
42
43impl<V> SettingData<V> {
44    /// Reads the value of the setting, giving `newer_value` if the current
45    /// epoch is greater than `newer_value_epoch`, and `older_value_opt`
46    /// otherwise. If `cur_epoch` is `None`, the `newer_value` is always
47    /// returned.
48    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
49        let use_newer_value = match cur_epoch {
50            Some(cur_epoch) => cur_epoch > self.newer_value_epoch,
51            None => true,
52        };
53        if use_newer_value {
54            self.newer_value.as_ref()
55        } else {
56            self.older_value_opt.as_ref()
57        }
58    }
59}