diff --git a/contracts/cw3-fixed-multisig/src/contract.rs b/contracts/cw3-fixed-multisig/src/contract.rs index 2f2ef70d5..ece844dc0 100644 --- a/contracts/cw3-fixed-multisig/src/contract.rs +++ b/contracts/cw3-fixed-multisig/src/contract.rs @@ -9,11 +9,11 @@ use cosmwasm_std::{ use cw2::set_contract_version; use cw3::{ - ProposalListResponse, ProposalResponse, Status, ThresholdResponse, Vote, VoteInfo, - VoteListResponse, VoteResponse, VoterDetail, VoterListResponse, VoterResponse, + ProposalListResponse, ProposalResponse, Status, Vote, VoteInfo, VoteListResponse, VoteResponse, + VoterDetail, VoterListResponse, VoterResponse, }; use cw_storage_plus::Bound; -use utils::Expiration; +use utils::{Expiration, ThresholdResponse}; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; diff --git a/contracts/cw3-flex-multisig/src/contract.rs b/contracts/cw3-flex-multisig/src/contract.rs index 38169b6b5..d870652c5 100644 --- a/contracts/cw3-flex-multisig/src/contract.rs +++ b/contracts/cw3-flex-multisig/src/contract.rs @@ -9,12 +9,12 @@ use cosmwasm_std::{ use cw2::set_contract_version; use cw3::{ - ProposalListResponse, ProposalResponse, Status, ThresholdResponse, Vote, VoteInfo, - VoteListResponse, VoteResponse, VoterDetail, VoterListResponse, VoterResponse, + ProposalListResponse, ProposalResponse, Status, Vote, VoteInfo, VoteListResponse, VoteResponse, + VoterDetail, VoterListResponse, VoterResponse, }; use cw4::{Cw4Contract, MemberChangedHookMsg, MemberDiff}; use cw_storage_plus::Bound; -use utils::{maybe_addr, Expiration}; +use utils::{maybe_addr, Expiration, ThresholdResponse}; use crate::error::ContractError; use crate::msg::{ExecuteMsg, InstantiateMsg, QueryMsg}; @@ -431,10 +431,9 @@ mod tests { use cw4::{Cw4ExecuteMsg, Member}; use cw4_group::helpers::Cw4GroupContract; use cw_multi_test::{next_block, App, AppBuilder, Contract, ContractWrapper, Executor}; - use utils::Duration; + use utils::{Duration, Threshold}; use super::*; - use crate::msg::Threshold; const OWNER: &str = "admin0001"; const VOTER1: &str = "voter0001"; @@ -625,7 +624,10 @@ mod tests { None, ) .unwrap_err(); - assert_eq!(ContractError::InvalidThreshold {}, err.downcast().unwrap()); + assert_eq!( + ContractError::Threshold(utils::ThresholdError::InvalidThreshold {}), + err.downcast().unwrap() + ); // Total weight less than required weight not allowed let instantiate_msg = InstantiateMsg { @@ -643,7 +645,10 @@ mod tests { None, ) .unwrap_err(); - assert_eq!(ContractError::UnreachableWeight {}, err.downcast().unwrap()); + assert_eq!( + ContractError::Threshold(utils::ThresholdError::UnreachableWeight {}), + err.downcast().unwrap() + ); // All valid let instantiate_msg = InstantiateMsg { diff --git a/contracts/cw3-flex-multisig/src/error.rs b/contracts/cw3-flex-multisig/src/error.rs index 0c104222a..4a56312bb 100644 --- a/contracts/cw3-flex-multisig/src/error.rs +++ b/contracts/cw3-flex-multisig/src/error.rs @@ -1,4 +1,6 @@ use cosmwasm_std::StdError; +use utils::ThresholdError; + use thiserror::Error; #[derive(Error, Debug, PartialEq)] @@ -6,20 +8,8 @@ pub enum ContractError { #[error("{0}")] Std(#[from] StdError), - #[error("Invalid voting threshold percentage, must be in the 0.5-1.0 range")] - InvalidThreshold {}, - - #[error("Required quorum threshold cannot be zero")] - ZeroQuorumThreshold {}, - - #[error("Not possible to reach required quorum threshold")] - UnreachableQuorumThreshold {}, - - #[error("Required weight cannot be zero")] - ZeroWeight {}, - - #[error("Not possible to reach required (passing) weight")] - UnreachableWeight {}, + #[error("{0}")] + Threshold(#[from] ThresholdError), #[error("Group contract invalid address '{addr}'")] InvalidGroup { addr: String }, diff --git a/contracts/cw3-flex-multisig/src/msg.rs b/contracts/cw3-flex-multisig/src/msg.rs index 1bb2301d4..9b6fa67ef 100644 --- a/contracts/cw3-flex-multisig/src/msg.rs +++ b/contracts/cw3-flex-multisig/src/msg.rs @@ -1,11 +1,10 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; -use crate::error::ContractError; -use cosmwasm_std::{CosmosMsg, Decimal, Empty}; -use cw3::{ThresholdResponse, Vote}; +use cosmwasm_std::{CosmosMsg, Empty}; +use cw3::Vote; use cw4::MemberChangedHookMsg; -use utils::{Duration, Expiration}; +use utils::{Duration, Expiration, Threshold}; #[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] pub struct InstantiateMsg { @@ -15,102 +14,6 @@ pub struct InstantiateMsg { pub max_voting_period: Duration, } -/// This defines the different ways tallies can happen. -/// -/// The total_weight used for calculating success as well as the weights of each -/// individual voter used in tallying should be snapshotted at the beginning of -/// the block at which the proposal starts (this is likely the responsibility of a -/// correct cw4 implementation). -/// See also `ThresholdResponse` in the cw3 spec. -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] -#[serde(rename_all = "snake_case")] -pub enum Threshold { - /// Declares that a fixed weight of Yes votes is needed to pass. - /// See `ThresholdResponse.AbsoluteCount` in the cw3 spec for details. - AbsoluteCount { weight: u64 }, - - /// Declares a percentage of the total weight that must cast Yes votes in order for - /// a proposal to pass. - /// See `ThresholdResponse.AbsolutePercentage` in the cw3 spec for details. - AbsolutePercentage { percentage: Decimal }, - - /// Declares a `quorum` of the total votes that must participate in the election in order - /// for the vote to be considered at all. - /// See `ThresholdResponse.ThresholdQuorum` in the cw3 spec for details. - ThresholdQuorum { threshold: Decimal, quorum: Decimal }, -} - -impl Threshold { - /// returns error if this is an unreachable value, - /// given a total weight of all members in the group - pub fn validate(&self, total_weight: u64) -> Result<(), ContractError> { - match self { - Threshold::AbsoluteCount { - weight: weight_needed, - } => { - if *weight_needed == 0 { - Err(ContractError::ZeroWeight {}) - } else if *weight_needed > total_weight { - Err(ContractError::UnreachableWeight {}) - } else { - Ok(()) - } - } - Threshold::AbsolutePercentage { - percentage: percentage_needed, - } => valid_threshold(percentage_needed), - Threshold::ThresholdQuorum { - threshold, - quorum: quroum, - } => { - valid_threshold(threshold)?; - valid_quorum(quroum) - } - } - } - - /// Creates a response from the saved data, just missing the total_weight info - pub fn to_response(&self, total_weight: u64) -> ThresholdResponse { - match self.clone() { - Threshold::AbsoluteCount { weight } => ThresholdResponse::AbsoluteCount { - weight, - total_weight, - }, - Threshold::AbsolutePercentage { percentage } => ThresholdResponse::AbsolutePercentage { - percentage, - total_weight, - }, - Threshold::ThresholdQuorum { threshold, quorum } => { - ThresholdResponse::ThresholdQuorum { - threshold, - quorum, - total_weight, - } - } - } - } -} - -/// Asserts that the 0.5 < percent <= 1.0 -fn valid_threshold(percent: &Decimal) -> Result<(), ContractError> { - if *percent > Decimal::percent(100) || *percent < Decimal::percent(50) { - Err(ContractError::InvalidThreshold {}) - } else { - Ok(()) - } -} - -/// Asserts that the 0.5 < percent <= 1.0 -fn valid_quorum(percent: &Decimal) -> Result<(), ContractError> { - if percent.is_zero() { - Err(ContractError::ZeroQuorumThreshold {}) - } else if *percent > Decimal::one() { - Err(ContractError::UnreachableQuorumThreshold {}) - } else { - Ok(()) - } -} - // TODO: add some T variants? Maybe good enough as fixed Empty for now #[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] #[serde(rename_all = "snake_case")] @@ -170,153 +73,3 @@ pub enum QueryMsg { limit: Option, }, } - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn validate_quorum_percentage() { - // TODO: test the error messages - - // 0 is never a valid percentage - let err = valid_quorum(&Decimal::zero()).unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::ZeroQuorumThreshold {}.to_string() - ); - - // 100% is - valid_quorum(&Decimal::one()).unwrap(); - - // 101% is not - let err = valid_quorum(&Decimal::percent(101)).unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::UnreachableQuorumThreshold {}.to_string() - ); - // not 100.1% - let err = valid_quorum(&Decimal::permille(1001)).unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::UnreachableQuorumThreshold {}.to_string() - ); - } - - #[test] - fn validate_threshold_percentage() { - // other values in between 0.5 and 1 are valid - valid_threshold(&Decimal::percent(51)).unwrap(); - valid_threshold(&Decimal::percent(67)).unwrap(); - valid_threshold(&Decimal::percent(99)).unwrap(); - let err = valid_threshold(&Decimal::percent(101)).unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::InvalidThreshold {}.to_string() - ); - } - - #[test] - fn validate_threshold() { - // absolute count ensures 0 < required <= total_weight - let err = Threshold::AbsoluteCount { weight: 0 } - .validate(5) - .unwrap_err(); - // TODO: remove to_string() when PartialEq implemented - assert_eq!(err.to_string(), ContractError::ZeroWeight {}.to_string()); - let err = Threshold::AbsoluteCount { weight: 6 } - .validate(5) - .unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::UnreachableWeight {}.to_string() - ); - - Threshold::AbsoluteCount { weight: 1 }.validate(5).unwrap(); - Threshold::AbsoluteCount { weight: 5 }.validate(5).unwrap(); - - // AbsolutePercentage just enforces valid_percentage (tested above) - let err = Threshold::AbsolutePercentage { - percentage: Decimal::zero(), - } - .validate(5) - .unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::InvalidThreshold {}.to_string() - ); - Threshold::AbsolutePercentage { - percentage: Decimal::percent(51), - } - .validate(5) - .unwrap(); - - // Quorum enforces both valid just enforces valid_percentage (tested above) - Threshold::ThresholdQuorum { - threshold: Decimal::percent(51), - quorum: Decimal::percent(40), - } - .validate(5) - .unwrap(); - let err = Threshold::ThresholdQuorum { - threshold: Decimal::percent(101), - quorum: Decimal::percent(40), - } - .validate(5) - .unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::InvalidThreshold {}.to_string() - ); - let err = Threshold::ThresholdQuorum { - threshold: Decimal::percent(51), - quorum: Decimal::percent(0), - } - .validate(5) - .unwrap_err(); - assert_eq!( - err.to_string(), - ContractError::ZeroQuorumThreshold {}.to_string() - ); - } - - #[test] - fn threshold_response() { - let total_weight: u64 = 100; - - let res = Threshold::AbsoluteCount { weight: 42 }.to_response(total_weight); - assert_eq!( - res, - ThresholdResponse::AbsoluteCount { - weight: 42, - total_weight - } - ); - - let res = Threshold::AbsolutePercentage { - percentage: Decimal::percent(51), - } - .to_response(total_weight); - assert_eq!( - res, - ThresholdResponse::AbsolutePercentage { - percentage: Decimal::percent(51), - total_weight - } - ); - - let res = Threshold::ThresholdQuorum { - threshold: Decimal::percent(66), - quorum: Decimal::percent(50), - } - .to_response(total_weight); - assert_eq!( - res, - ThresholdResponse::ThresholdQuorum { - threshold: Decimal::percent(66), - quorum: Decimal::percent(50), - total_weight - } - ); - } -} diff --git a/contracts/cw3-flex-multisig/src/state.rs b/contracts/cw3-flex-multisig/src/state.rs index 013757beb..59b1518b4 100644 --- a/contracts/cw3-flex-multisig/src/state.rs +++ b/contracts/cw3-flex-multisig/src/state.rs @@ -6,9 +6,7 @@ use cosmwasm_std::{Addr, BlockInfo, CosmosMsg, Decimal, Empty, StdResult, Storag use cw3::{Status, Vote}; use cw4::Cw4Contract; use cw_storage_plus::{Item, Map}; -use utils::{Duration, Expiration}; - -use crate::msg::Threshold; +use utils::{Duration, Expiration, Threshold}; // we multiply by this when calculating needed_votes in order to round up properly // Note: `10u128.pow(9)` fails as "u128::pow` is not yet stable as a const fn" diff --git a/packages/cw3/examples/schema.rs b/packages/cw3/examples/schema.rs index 2cbd5f59b..53329e81e 100644 --- a/packages/cw3/examples/schema.rs +++ b/packages/cw3/examples/schema.rs @@ -4,9 +4,10 @@ use std::fs::create_dir_all; use cosmwasm_schema::{export_schema, export_schema_with_title, remove_schemas, schema_for}; use cw3::{ - Cw3ExecuteMsg, Cw3QueryMsg, ProposalListResponse, ProposalResponse, ThresholdResponse, - VoteListResponse, VoteResponse, VoterDetail, VoterListResponse, VoterResponse, + Cw3ExecuteMsg, Cw3QueryMsg, ProposalListResponse, ProposalResponse, VoteListResponse, + VoteResponse, VoterDetail, VoterListResponse, VoterResponse, }; +use utils::ThresholdResponse; fn main() { let mut out_dir = current_dir().unwrap(); diff --git a/packages/cw3/src/lib.rs b/packages/cw3/src/lib.rs index 307bea09a..bda9d2d93 100644 --- a/packages/cw3/src/lib.rs +++ b/packages/cw3/src/lib.rs @@ -6,14 +6,6 @@ mod query; pub use crate::helpers::Cw3Contract; pub use crate::msg::{Cw3ExecuteMsg, Vote}; pub use crate::query::{ - Cw3QueryMsg, ProposalListResponse, ProposalResponse, Status, ThresholdResponse, VoteInfo, - VoteListResponse, VoteResponse, VoterDetail, VoterListResponse, VoterResponse, + Cw3QueryMsg, ProposalListResponse, ProposalResponse, Status, VoteInfo, VoteListResponse, + VoteResponse, VoterDetail, VoterListResponse, VoterResponse, }; - -#[cfg(test)] -mod tests { - #[test] - fn it_works() { - // test me - } -} diff --git a/packages/cw3/src/query.rs b/packages/cw3/src/query.rs index 5cfd17189..ea28e918e 100644 --- a/packages/cw3/src/query.rs +++ b/packages/cw3/src/query.rs @@ -2,8 +2,8 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use std::fmt; -use cosmwasm_std::{CosmosMsg, Decimal, Empty}; -use utils::Expiration; +use cosmwasm_std::{CosmosMsg, Empty}; +use utils::{Expiration, ThresholdResponse}; use crate::msg::Vote; @@ -49,75 +49,6 @@ pub enum Cw3QueryMsg { }, } -/// This defines the different ways tallies can happen. -/// Every contract should support a subset of these, ideally all. -/// -/// The total_weight used for calculating success as well as the weights of each -/// individual voter used in tallying should be snapshotted at the beginning of -/// the block at which the proposal starts (this is likely the responsibility of a -/// correct cw4 implementation). -#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] -#[serde(rename_all = "snake_case")] -pub enum ThresholdResponse { - /// Declares that a fixed weight of yes votes is needed to pass. - /// It does not matter how many no votes are cast, or how many do not vote, - /// as long as `weight` yes votes are cast. - /// - /// This is the simplest format and usually suitable for small multisigs of trusted parties, - /// like 3 of 5. (weight: 3, total_weight: 5) - /// - /// A proposal of this type can pass early as soon as the needed weight of yes votes has been cast. - AbsoluteCount { weight: u64, total_weight: u64 }, - - /// Declares a percentage of the total weight that must cast Yes votes, in order for - /// a proposal to pass. The passing weight is computed over the total weight minus the weight of the - /// abstained votes. - /// - /// This is useful for similar circumstances as `AbsoluteCount`, where we have a relatively - /// small set of voters, and participation is required. - /// It is understood that if the voting set (group) changes between different proposals that - /// refer to the same group, each proposal will work with a different set of voter weights - /// (the ones snapshotted at proposal creation), and the passing weight for each proposal - /// will be computed based on the absolute percentage, times the total weights of the members - /// at the time of each proposal creation. - /// - /// Example: we set `percentage` to 51%. Proposal 1 starts when there is a `total_weight` of 5. - /// This will require 3 weight of Yes votes in order to pass. Later, the Proposal 2 starts but the - /// `total_weight` of the group has increased to 9. That proposal will then automatically - /// require 5 Yes of 9 to pass, rather than 3 yes of 9 as would be the case with `AbsoluteCount`. - AbsolutePercentage { - percentage: Decimal, - total_weight: u64, - }, - - /// In addition to a `threshold`, declares a `quorum` of the total votes that must participate - /// in the election in order for the vote to be considered at all. Within the votes that - /// were cast, it requires `threshold` votes in favor. That is calculated by ignoring - /// the Abstain votes (they count towards `quorum`, but do not influence `threshold`). - /// That is, we calculate `Yes / (Yes + No + Veto)` and compare it with `threshold` to consider - /// if the proposal was passed. - /// - /// It is rather difficult for a proposal of this type to pass early. That can only happen if - /// the required quorum has been already met, and there are already enough Yes votes for the - /// proposal to pass. - /// - /// 30% Yes votes, 10% No votes, and 20% Abstain would pass early if quorum <= 60% - /// (who has cast votes) and if the threshold is <= 37.5% (the remaining 40% voting - /// no => 30% yes + 50% no). Once the voting period has passed with no additional votes, - /// that same proposal would be considered successful if quorum <= 60% and threshold <= 75% - /// (percent in favor if we ignore abstain votes). - /// - /// This type is more common in general elections, where participation is often expected to - /// be low, and `AbsolutePercentage` would either be too high to pass anything, - /// or allow low percentages to pass, independently of if there was high participation in the - /// election or not. - ThresholdQuorum { - threshold: Decimal, - quorum: Decimal, - total_weight: u64, - }, -} - /// Note, if you are storing custom messages in the proposal, /// the querier needs to know what possible custom message types /// those are in order to parse the response diff --git a/packages/utils/src/lib.rs b/packages/utils/src/lib.rs index 939599c00..c39b1005e 100644 --- a/packages/utils/src/lib.rs +++ b/packages/utils/src/lib.rs @@ -4,6 +4,7 @@ mod expiration; mod pagination; mod parse_reply; mod payment; +mod threshold; pub use pagination::{ calc_range_end, calc_range_start, calc_range_start_string, maybe_addr, maybe_canonical, @@ -14,6 +15,7 @@ pub use parse_reply::{ ParseReplyError, }; pub use payment::{may_pay, must_pay, nonpayable, one_coin, PaymentError}; +pub use threshold::{Threshold, ThresholdError, ThresholdResponse}; pub use crate::balance::NativeBalance; pub use crate::event::Event; diff --git a/packages/utils/src/threshold.rs b/packages/utils/src/threshold.rs new file mode 100644 index 000000000..b919f7a02 --- /dev/null +++ b/packages/utils/src/threshold.rs @@ -0,0 +1,341 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use cosmwasm_std::{Decimal, StdError}; +use thiserror::Error; + +/// This defines the different ways tallies can happen. +/// +/// The total_weight used for calculating success as well as the weights of each +/// individual voter used in tallying should be snapshotted at the beginning of +/// the block at which the proposal starts (this is likely the responsibility of a +/// correct cw4 implementation). +/// See also `ThresholdResponse` in the cw3 spec. +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[serde(rename_all = "snake_case")] +pub enum Threshold { + /// Declares that a fixed weight of Yes votes is needed to pass. + /// See `ThresholdResponse.AbsoluteCount` in the cw3 spec for details. + AbsoluteCount { weight: u64 }, + + /// Declares a percentage of the total weight that must cast Yes votes in order for + /// a proposal to pass. + /// See `ThresholdResponse.AbsolutePercentage` in the cw3 spec for details. + AbsolutePercentage { percentage: Decimal }, + + /// Declares a `quorum` of the total votes that must participate in the election in order + /// for the vote to be considered at all. + /// See `ThresholdResponse.ThresholdQuorum` in the cw3 spec for details. + ThresholdQuorum { threshold: Decimal, quorum: Decimal }, +} + +impl Threshold { + /// returns error if this is an unreachable value, + /// given a total weight of all members in the group + pub fn validate(&self, total_weight: u64) -> Result<(), ThresholdError> { + match self { + Threshold::AbsoluteCount { + weight: weight_needed, + } => { + if *weight_needed == 0 { + Err(ThresholdError::ZeroWeight {}) + } else if *weight_needed > total_weight { + Err(ThresholdError::UnreachableWeight {}) + } else { + Ok(()) + } + } + Threshold::AbsolutePercentage { + percentage: percentage_needed, + } => valid_threshold(percentage_needed), + Threshold::ThresholdQuorum { + threshold, + quorum: quroum, + } => { + valid_threshold(threshold)?; + valid_quorum(quroum) + } + } + } + + /// Creates a response from the saved data, just missing the total_weight info + pub fn to_response(&self, total_weight: u64) -> ThresholdResponse { + match self.clone() { + Threshold::AbsoluteCount { weight } => ThresholdResponse::AbsoluteCount { + weight, + total_weight, + }, + Threshold::AbsolutePercentage { percentage } => ThresholdResponse::AbsolutePercentage { + percentage, + total_weight, + }, + Threshold::ThresholdQuorum { threshold, quorum } => { + ThresholdResponse::ThresholdQuorum { + threshold, + quorum, + total_weight, + } + } + } + } +} + +/// Asserts that the 0.5 < percent <= 1.0 +fn valid_threshold(percent: &Decimal) -> Result<(), ThresholdError> { + if *percent > Decimal::percent(100) || *percent < Decimal::percent(50) { + Err(ThresholdError::InvalidThreshold {}) + } else { + Ok(()) + } +} + +/// Asserts that the 0.5 < percent <= 1.0 +fn valid_quorum(percent: &Decimal) -> Result<(), ThresholdError> { + if percent.is_zero() { + Err(ThresholdError::ZeroQuorumThreshold {}) + } else if *percent > Decimal::one() { + Err(ThresholdError::UnreachableQuorumThreshold {}) + } else { + Ok(()) + } +} + +/// This defines the different ways tallies can happen. +/// Every contract should support a subset of these, ideally all. +/// +/// The total_weight used for calculating success as well as the weights of each +/// individual voter used in tallying should be snapshotted at the beginning of +/// the block at which the proposal starts (this is likely the responsibility of a +/// correct cw4 implementation). +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +#[serde(rename_all = "snake_case")] +pub enum ThresholdResponse { + /// Declares that a fixed weight of yes votes is needed to pass. + /// It does not matter how many no votes are cast, or how many do not vote, + /// as long as `weight` yes votes are cast. + /// + /// This is the simplest format and usually suitable for small multisigs of trusted parties, + /// like 3 of 5. (weight: 3, total_weight: 5) + /// + /// A proposal of this type can pass early as soon as the needed weight of yes votes has been cast. + AbsoluteCount { weight: u64, total_weight: u64 }, + + /// Declares a percentage of the total weight that must cast Yes votes, in order for + /// a proposal to pass. The passing weight is computed over the total weight minus the weight of the + /// abstained votes. + /// + /// This is useful for similar circumstances as `AbsoluteCount`, where we have a relatively + /// small set of voters, and participation is required. + /// It is understood that if the voting set (group) changes between different proposals that + /// refer to the same group, each proposal will work with a different set of voter weights + /// (the ones snapshotted at proposal creation), and the passing weight for each proposal + /// will be computed based on the absolute percentage, times the total weights of the members + /// at the time of each proposal creation. + /// + /// Example: we set `percentage` to 51%. Proposal 1 starts when there is a `total_weight` of 5. + /// This will require 3 weight of Yes votes in order to pass. Later, the Proposal 2 starts but the + /// `total_weight` of the group has increased to 9. That proposal will then automatically + /// require 5 Yes of 9 to pass, rather than 3 yes of 9 as would be the case with `AbsoluteCount`. + AbsolutePercentage { + percentage: Decimal, + total_weight: u64, + }, + + /// In addition to a `threshold`, declares a `quorum` of the total votes that must participate + /// in the election in order for the vote to be considered at all. Within the votes that + /// were cast, it requires `threshold` votes in favor. That is calculated by ignoring + /// the Abstain votes (they count towards `quorum`, but do not influence `threshold`). + /// That is, we calculate `Yes / (Yes + No + Veto)` and compare it with `threshold` to consider + /// if the proposal was passed. + /// + /// It is rather difficult for a proposal of this type to pass early. That can only happen if + /// the required quorum has been already met, and there are already enough Yes votes for the + /// proposal to pass. + /// + /// 30% Yes votes, 10% No votes, and 20% Abstain would pass early if quorum <= 60% + /// (who has cast votes) and if the threshold is <= 37.5% (the remaining 40% voting + /// no => 30% yes + 50% no). Once the voting period has passed with no additional votes, + /// that same proposal would be considered successful if quorum <= 60% and threshold <= 75% + /// (percent in favor if we ignore abstain votes). + /// + /// This type is more common in general elections, where participation is often expected to + /// be low, and `AbsolutePercentage` would either be too high to pass anything, + /// or allow low percentages to pass, independently of if there was high participation in the + /// election or not. + ThresholdQuorum { + threshold: Decimal, + quorum: Decimal, + total_weight: u64, + }, +} + +#[derive(Error, Debug, PartialEq)] +pub enum ThresholdError { + #[error("{0}")] + Std(#[from] StdError), + + #[error("Invalid voting threshold percentage, must be in the 0.5-1.0 range")] + InvalidThreshold {}, + + #[error("Required quorum threshold cannot be zero")] + ZeroQuorumThreshold {}, + + #[error("Not possible to reach required quorum threshold")] + UnreachableQuorumThreshold {}, + + #[error("Required weight cannot be zero")] + ZeroWeight {}, + + #[error("Not possible to reach required (passing) weight")] + UnreachableWeight {}, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validate_quorum_percentage() { + // TODO: test the error messages + + // 0 is never a valid percentage + let err = valid_quorum(&Decimal::zero()).unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::ZeroQuorumThreshold {}.to_string() + ); + + // 100% is + valid_quorum(&Decimal::one()).unwrap(); + + // 101% is not + let err = valid_quorum(&Decimal::percent(101)).unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::UnreachableQuorumThreshold {}.to_string() + ); + // not 100.1% + let err = valid_quorum(&Decimal::permille(1001)).unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::UnreachableQuorumThreshold {}.to_string() + ); + } + + #[test] + fn validate_threshold_percentage() { + // other values in between 0.5 and 1 are valid + valid_threshold(&Decimal::percent(51)).unwrap(); + valid_threshold(&Decimal::percent(67)).unwrap(); + valid_threshold(&Decimal::percent(99)).unwrap(); + let err = valid_threshold(&Decimal::percent(101)).unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::InvalidThreshold {}.to_string() + ); + } + + #[test] + fn validate_threshold() { + // absolute count ensures 0 < required <= total_weight + let err = Threshold::AbsoluteCount { weight: 0 } + .validate(5) + .unwrap_err(); + // TODO: remove to_string() when PartialEq implemented + assert_eq!(err.to_string(), ThresholdError::ZeroWeight {}.to_string()); + let err = Threshold::AbsoluteCount { weight: 6 } + .validate(5) + .unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::UnreachableWeight {}.to_string() + ); + + Threshold::AbsoluteCount { weight: 1 }.validate(5).unwrap(); + Threshold::AbsoluteCount { weight: 5 }.validate(5).unwrap(); + + // AbsolutePercentage just enforces valid_percentage (tested above) + let err = Threshold::AbsolutePercentage { + percentage: Decimal::zero(), + } + .validate(5) + .unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::InvalidThreshold {}.to_string() + ); + Threshold::AbsolutePercentage { + percentage: Decimal::percent(51), + } + .validate(5) + .unwrap(); + + // Quorum enforces both valid just enforces valid_percentage (tested above) + Threshold::ThresholdQuorum { + threshold: Decimal::percent(51), + quorum: Decimal::percent(40), + } + .validate(5) + .unwrap(); + let err = Threshold::ThresholdQuorum { + threshold: Decimal::percent(101), + quorum: Decimal::percent(40), + } + .validate(5) + .unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::InvalidThreshold {}.to_string() + ); + let err = Threshold::ThresholdQuorum { + threshold: Decimal::percent(51), + quorum: Decimal::percent(0), + } + .validate(5) + .unwrap_err(); + assert_eq!( + err.to_string(), + ThresholdError::ZeroQuorumThreshold {}.to_string() + ); + } + + #[test] + fn threshold_response() { + let total_weight: u64 = 100; + + let res = Threshold::AbsoluteCount { weight: 42 }.to_response(total_weight); + assert_eq!( + res, + ThresholdResponse::AbsoluteCount { + weight: 42, + total_weight + } + ); + + let res = Threshold::AbsolutePercentage { + percentage: Decimal::percent(51), + } + .to_response(total_weight); + assert_eq!( + res, + ThresholdResponse::AbsolutePercentage { + percentage: Decimal::percent(51), + total_weight + } + ); + + let res = Threshold::ThresholdQuorum { + threshold: Decimal::percent(66), + quorum: Decimal::percent(50), + } + .to_response(total_weight); + assert_eq!( + res, + ThresholdResponse::ThresholdQuorum { + threshold: Decimal::percent(66), + quorum: Decimal::percent(50), + total_weight + } + ); + } +}