1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
//! Abstractions facilitating error handling.
use crate::rules::validation::{Validation, VotingValidation};
use odra::contract_env::revert;
use odra::prelude::{boxed::Box, vec::Vec};

mod builder;
pub mod validation;

use crate::configuration::Configuration;
use crate::voting::voting_engine::voting_state_machine::VotingStateMachine;
pub use builder::RulesBuilder;

/// A set of validation rules.
///
/// If any rule fail, the current contract execution stops, and reverts
/// if the error raised by the first falling rule.
///
/// Rules related to voting must be given voting state.
pub struct Rules {
    validations: Vec<Box<dyn Validation>>,
    voting_validations: Vec<Box<dyn VotingValidation>>,
}

impl Rules {
    /// Validates only the rules that don't need voting state.
    pub fn validate_generic_validations(&self) {
        for validation in &self.validations {
            if let Err(error) = validation.validate() {
                revert(error)
            }
        }
    }

    /// Validates only the rules that require voting state.
    pub fn validate_voting_validations(
        &self,
        voting_state_machine: &VotingStateMachine,
        configuration: &Configuration,
    ) {
        for validation in &self.voting_validations {
            if let Err(error) = validation.validate(voting_state_machine, configuration) {
                revert(error)
            }
        }
    }

    /// Validates all the rules.
    pub fn validate(
        &self,
        voting_state_machine: &VotingStateMachine,
        configuration: &Configuration,
    ) {
        self.validate_generic_validations();
        self.validate_voting_validations(voting_state_machine, configuration);
    }
}