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, id::UID};
9
10/// Rust representation of the Move type 0x2::config::Config.
11#[derive(Debug, Serialize, Deserialize)]
12pub struct Config {
13    pub id: UID,
14}
15
16/// Rust representation of the Move type 0x2::config::Setting.
17#[derive(Debug, Serialize, Deserialize)]
18pub struct Setting<V> {
19    pub data: Option<SettingData<V>>,
20}
21
22/// Rust representation of the Move type 0x2::config::SettingData.
23#[derive(Debug, Serialize, Deserialize)]
24pub struct SettingData<V> {
25    pub newer_value_epoch: u64,
26    pub newer_value: Option<V>,
27    pub older_value_opt: Option<V>,
28}
29
30pub fn setting_type(value_tag: TypeTag) -> StructTag {
31    StructTag::new_config_setting(value_tag)
32}
33
34impl<V: MoveTypeTagTrait> MoveTypeTagTrait for Setting<V> {
35    fn get_type_tag() -> TypeTag {
36        TypeTag::Struct(Box::new(setting_type(V::get_type_tag())))
37    }
38}
39
40impl<V> Setting<V> {
41    /// Calls `SettingData::read_value` on the setting's data.
42    /// The `data` should never be `None`, but for safety, this method returns
43    /// `None` if it is.
44    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
45        self.data.as_ref()?.read_value(cur_epoch)
46    }
47}
48
49impl<V> SettingData<V> {
50    /// Reads the value of the setting, giving `newer_value` if the current
51    /// epoch is greater than `newer_value_epoch`, and `older_value_opt`
52    /// otherwise. If `cur_epoch` is `None`, the `newer_value` is always
53    /// returned.
54    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
55        let use_newer_value = match cur_epoch {
56            Some(cur_epoch) => cur_epoch > self.newer_value_epoch,
57            None => true,
58        };
59        if use_newer_value {
60            self.newer_value.as_ref()
61        } else {
62            self.older_value_opt.as_ref()
63        }
64    }
65}