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 MoveTypeTagTrait for Config {
35    fn get_type_tag() -> TypeTag {
36        TypeTag::Struct(Box::new(StructTag::new_config()))
37    }
38}
39
40impl<V: MoveTypeTagTrait> MoveTypeTagTrait for Setting<V> {
41    fn get_type_tag() -> TypeTag {
42        TypeTag::Struct(Box::new(setting_type(V::get_type_tag())))
43    }
44}
45
46impl<V> Setting<V> {
47    /// Calls `SettingData::read_value` on the setting's data.
48    /// The `data` should never be `None`, but for safety, this method returns
49    /// `None` if it is.
50    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
51        self.data.as_ref()?.read_value(cur_epoch)
52    }
53}
54
55impl<V> SettingData<V> {
56    /// Reads the value of the setting, giving `newer_value` if the current
57    /// epoch is greater than `newer_value_epoch`, and `older_value_opt`
58    /// otherwise. If `cur_epoch` is `None`, the `newer_value` is always
59    /// returned.
60    pub fn read_value(&self, cur_epoch: Option<EpochId>) -> Option<&V> {
61        let use_newer_value = match cur_epoch {
62            Some(cur_epoch) => cur_epoch > self.newer_value_epoch,
63            None => true,
64        };
65        if use_newer_value {
66            self.newer_value.as_ref()
67        } else {
68            self.older_value_opt.as_ref()
69        }
70    }
71}