odra_core/
sequence.rs

1use crate::module::Revertible;
2use crate::prelude::*;
3use crate::{
4    casper_types::{
5        bytesrepr::{FromBytes, ToBytes},
6        CLTyped
7    },
8    module::{ModuleComponent, ModulePrimitive},
9    ContractEnv
10};
11use num_traits::{Num, One, Zero};
12
13/// A module that stores a single value in the storage that can be read or incremented.
14pub struct Sequence<T>
15where
16    T: Num + One + ToBytes + FromBytes + CLTyped
17{
18    env: Rc<ContractEnv>,
19    index: u8,
20    value: Var<T>
21}
22
23impl<T> Revertible for Sequence<T>
24where
25    T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped
26{
27    fn revert<E: Into<OdraError>>(&self, e: E) -> ! {
28        self.env.revert(e)
29    }
30}
31
32impl<T> Sequence<T>
33where
34    T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped
35{
36    /// Returns the current value of the sequence.
37    pub fn get_current_value(&self) -> T {
38        self.value.get().unwrap_or_default()
39    }
40
41    /// Increments the value of the sequence and returns the new value.
42    pub fn next_value(&mut self) -> T {
43        match self.value.get() {
44            None => {
45                self.value.set(T::zero());
46                T::zero()
47            }
48            Some(value) => {
49                let next = value + T::one();
50                self.value.set(next);
51                next
52            }
53        }
54    }
55}
56
57impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> Sequence<T> {
58    /// Returns the ContractEnv.
59    pub fn env(&self) -> ContractEnv {
60        self.env.child(self.index)
61    }
62}
63
64/// Implements the `ModuleComponent` trait for the `Sequence` struct.
65impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> ModuleComponent
66    for Sequence<T>
67{
68    /// Creates a new instance of `Sequence` with the given environment and index.
69    fn instance(env: Rc<ContractEnv>, index: u8) -> Self {
70        Self {
71            env: env.clone(),
72            index,
73            value: Var::instance(env.child(index).into(), 0)
74        }
75    }
76}
77
78impl<T: Num + One + Zero + Default + Copy + ToBytes + FromBytes + CLTyped> ModulePrimitive
79    for Sequence<T>
80{
81}