Skip to main content

dpp/decision_proposal/
multiple_choice.rs

1//! Multiple choice proposals (protocol version 15): what clients name them and their vote by.
2//!
3//! A multiple choice proposal is a `multipleChoiceProposal` document of the decision proposals
4//! contract; its answers are `choice` documents, which contend in a masternode vote among
5//! documents (`ContestedIndexResolution::MasternodeVoteOnDocuments`). The vote is keyed by the
6//! proposal's id ([`multiple_choice_proposal_vote_poll`]), and a choice is named in it by its
7//! own document id, wherever a contest among identities names a contender by an identity id
8//! ([`MultipleChoiceVoteChoice`]).
9
10use crate::decision_proposal::DECISION_PROPOSALS_CONTRACT_ID;
11use crate::voting::vote_choices::resource_vote_choice::ResourceVoteChoice;
12use crate::voting::vote_polls::contested_document_resource_vote_poll::ContestedDocumentResourceVotePoll;
13use crate::voting::vote_polls::VotePoll;
14use crate::voting::votes::resource_vote::v0::ResourceVoteV0;
15use crate::voting::votes::resource_vote::ResourceVote;
16use crate::voting::votes::Vote;
17use platform_value::{Identifier, Value};
18
19/// The name of the choice document type: an answer to a multiple choice proposal.
20pub const CHOICE_DOCUMENT_TYPE_NAME: &str = "choice";
21
22/// The contested index every choice falls under, on the proposal it answers. A choice's create
23/// states its contest fund under this name.
24pub const CHOICE_CONTEST_INDEX_NAME: &str = "byProposal";
25
26/// The properties of a multiple choice proposal.
27pub mod proposal_properties {
28    /// The question, in one line. Editable for two hours after the proposal is created.
29    pub const TITLE: &str = "title";
30    /// The document saying what is being decided; optional, given with the two properties
31    /// naming where it lives and only with them. Editable for two hours.
32    pub const DESCRIPTION_ID: &str = "descriptionId";
33    /// The contract the description document lives in.
34    pub const DESCRIPTION_CONTRACT_ID: &str = "descriptionContractId";
35    /// The document type of the description document.
36    pub const DESCRIPTION_DOCUMENT_TYPE: &str = "descriptionDocumentType";
37    /// Where what is being decided is described or discussed; optional, required of a proposal
38    /// that points at no description document. Editable for two hours.
39    pub const URL: &str = "url";
40    /// Whether anyone may enter choices; only the proposal's owner may when it is false.
41    /// Never changes.
42    pub const OPEN: &str = "open";
43}
44
45/// The properties of a choice.
46pub mod choice_properties {
47    /// The multiple choice proposal the choice answers.
48    pub const PROPOSAL_ID: &str = "proposalId";
49    /// The answer, in one line.
50    pub const TITLE: &str = "title";
51    /// What voting for the answer means; optional.
52    pub const DESCRIPTION: &str = "description";
53}
54
55/// Whether a document of `document_type_name` in the contract `contract_id` is a choice: a
56/// `choice` of the decision proposals contract. Its create joins the vote among the choices of
57/// the proposal it answers, or opens it.
58pub fn is_choice(contract_id: &Identifier, document_type_name: &str) -> bool {
59    *contract_id == DECISION_PROPOSALS_CONTRACT_ID
60        && document_type_name == CHOICE_DOCUMENT_TYPE_NAME
61}
62
63/// The vote among the choices of the multiple choice proposal `proposal_id`: the contest of
64/// the `choice` type's `byProposal` index at that proposal, as a choice's create derives it
65/// from its `proposalId`. The contested resource queries take it, and a masternode's vote
66/// names it. Known from the proposal's id alone, whether or not a choice has opened the vote.
67pub fn multiple_choice_proposal_vote_poll(
68    proposal_id: Identifier,
69) -> ContestedDocumentResourceVotePoll {
70    ContestedDocumentResourceVotePoll {
71        contract_id: DECISION_PROPOSALS_CONTRACT_ID,
72        document_type_name: CHOICE_DOCUMENT_TYPE_NAME.to_string(),
73        index_name: CHOICE_CONTEST_INDEX_NAME.to_string(),
74        index_values: vec![Value::Identifier(proposal_id.to_buffer())],
75    }
76}
77
78/// A masternode's answer in the vote among a multiple choice proposal's choices.
79#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80pub enum MultipleChoiceVoteChoice {
81    /// For the choice with this document id. The id of the identity that entered the choice
82    /// names no contender here, and a vote carrying it is refused.
83    Choice(Identifier),
84    /// For no choice and against none.
85    Abstain,
86    /// None of the choices: when these votes outnumber the leading choice, no choice is kept
87    /// and none can be entered for the proposal again.
88    NoneOfTheChoices,
89}
90
91impl From<MultipleChoiceVoteChoice> for ResourceVoteChoice {
92    /// The resource vote choice the contest takes: a choice's document id travels where a
93    /// contest among identities carries an identity id, and none of the choices is a lock.
94    fn from(vote_choice: MultipleChoiceVoteChoice) -> Self {
95        match vote_choice {
96            MultipleChoiceVoteChoice::Choice(choice_id) => {
97                ResourceVoteChoice::TowardsIdentity(choice_id)
98            }
99            MultipleChoiceVoteChoice::Abstain => ResourceVoteChoice::Abstain,
100            MultipleChoiceVoteChoice::NoneOfTheChoices => ResourceVoteChoice::Lock,
101        }
102    }
103}
104
105/// A masternode's vote `vote_choice` in the vote among the choices of the multiple choice
106/// proposal `proposal_id`, to sign as a masternode vote transition.
107pub fn multiple_choice_proposal_vote(
108    proposal_id: Identifier,
109    vote_choice: MultipleChoiceVoteChoice,
110) -> Vote {
111    Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 {
112        vote_poll: VotePoll::ContestedDocumentResourceVotePoll(multiple_choice_proposal_vote_poll(
113            proposal_id,
114        )),
115        resource_vote_choice: vote_choice.into(),
116    }))
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use crate::decision_proposal::{
123        is_multiple_choice_proposal, MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME,
124    };
125
126    #[test]
127    fn should_recognize_only_the_choice_of_the_decision_proposals_contract() {
128        assert!(is_choice(
129            &DECISION_PROPOSALS_CONTRACT_ID,
130            CHOICE_DOCUMENT_TYPE_NAME
131        ));
132        assert!(!is_choice(
133            &DECISION_PROPOSALS_CONTRACT_ID,
134            MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME
135        ));
136        assert!(!is_choice(
137            &Identifier::new([1; 32]),
138            CHOICE_DOCUMENT_TYPE_NAME
139        ));
140        assert!(!is_multiple_choice_proposal(
141            &DECISION_PROPOSALS_CONTRACT_ID,
142            CHOICE_DOCUMENT_TYPE_NAME
143        ));
144    }
145
146    #[test]
147    fn should_vote_towards_a_choice_by_its_document_id() {
148        let proposal_id = Identifier::new([7; 32]);
149        let choice_id = Identifier::new([9; 32]);
150        let answers = [
151            (
152                MultipleChoiceVoteChoice::Choice(choice_id),
153                ResourceVoteChoice::TowardsIdentity(choice_id),
154            ),
155            (
156                MultipleChoiceVoteChoice::Abstain,
157                ResourceVoteChoice::Abstain,
158            ),
159            (
160                MultipleChoiceVoteChoice::NoneOfTheChoices,
161                ResourceVoteChoice::Lock,
162            ),
163        ];
164        for (vote_choice, resource_vote_choice) in answers {
165            assert_eq!(
166                multiple_choice_proposal_vote(proposal_id, vote_choice),
167                Vote::ResourceVote(ResourceVote::V0(ResourceVoteV0 {
168                    vote_poll: VotePoll::ContestedDocumentResourceVotePoll(
169                        multiple_choice_proposal_vote_poll(proposal_id)
170                    ),
171                    resource_vote_choice,
172                })),
173                "{vote_choice:?}"
174            );
175        }
176    }
177
178    #[cfg(feature = "decision-proposals-contract")]
179    #[test]
180    fn should_name_the_types_and_properties_as_the_contract_crate_does() {
181        use data_contracts::decision_proposals_contract::v1::document_types::{
182            choice, multiple_choice_proposal,
183        };
184
185        assert_eq!(
186            MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME,
187            multiple_choice_proposal::NAME
188        );
189        assert_eq!(
190            proposal_properties::TITLE,
191            multiple_choice_proposal::properties::TITLE
192        );
193        assert_eq!(
194            proposal_properties::DESCRIPTION_ID,
195            multiple_choice_proposal::properties::DESCRIPTION_ID
196        );
197        assert_eq!(
198            proposal_properties::DESCRIPTION_CONTRACT_ID,
199            multiple_choice_proposal::properties::DESCRIPTION_CONTRACT_ID
200        );
201        assert_eq!(
202            proposal_properties::DESCRIPTION_DOCUMENT_TYPE,
203            multiple_choice_proposal::properties::DESCRIPTION_DOCUMENT_TYPE
204        );
205        assert_eq!(
206            proposal_properties::URL,
207            multiple_choice_proposal::properties::URL
208        );
209        assert_eq!(
210            proposal_properties::OPEN,
211            multiple_choice_proposal::properties::OPEN
212        );
213        assert_eq!(CHOICE_DOCUMENT_TYPE_NAME, choice::NAME);
214        assert_eq!(CHOICE_CONTEST_INDEX_NAME, choice::indexes::BY_PROPOSAL);
215        assert_eq!(
216            choice_properties::PROPOSAL_ID,
217            choice::properties::PROPOSAL_ID
218        );
219        assert_eq!(choice_properties::TITLE, choice::properties::TITLE);
220        assert_eq!(
221            choice_properties::DESCRIPTION,
222            choice::properties::DESCRIPTION
223        );
224    }
225
226    /// The poll named from the proposal's id alone is the one a choice's create derives from
227    /// its `proposalId`, in whichever form the create writes the id.
228    #[cfg(feature = "decision-proposals-contract")]
229    #[test]
230    fn should_name_the_vote_a_choice_joins_by_the_proposal_id_alone() {
231        use crate::data_contract::accessors::v0::DataContractV0Getters;
232        use crate::data_contract::document_type::methods::DocumentTypeV0Methods;
233        use crate::document::{Document, DocumentV0};
234        use crate::system_data_contracts::{load_system_data_contract, SystemDataContract};
235        use platform_version::version::PlatformVersion;
236        use std::collections::BTreeMap;
237
238        let platform_version = PlatformVersion::latest();
239        let contract =
240            load_system_data_contract(SystemDataContract::DecisionProposals, platform_version)
241                .expect("the contract loads at the latest version");
242        let document_type = contract
243            .document_type_for_name(CHOICE_DOCUMENT_TYPE_NAME)
244            .expect("the choice type");
245        let proposal_id = Identifier::new([7; 32]);
246        let forms = [
247            Value::Identifier(proposal_id.to_buffer()),
248            Value::Bytes32(proposal_id.to_buffer()),
249            Value::Bytes(proposal_id.to_vec()),
250        ];
251        for proposal_id_value in forms {
252            let choice: Document = DocumentV0 {
253                properties: BTreeMap::from([
254                    (
255                        choice_properties::PROPOSAL_ID.to_string(),
256                        proposal_id_value.clone(),
257                    ),
258                    (
259                        choice_properties::TITLE.to_string(),
260                        Value::Text("Double it".to_string()),
261                    ),
262                ]),
263                ..Default::default()
264            }
265            .into();
266            assert_eq!(
267                document_type
268                    .contested_vote_poll_for_document(&choice, platform_version)
269                    .expect("active"),
270                Some(multiple_choice_proposal_vote_poll(proposal_id)),
271                "{proposal_id_value:?}"
272            );
273        }
274    }
275}