1pub mod multiple_choice;
17
18use crate::balances::credits::Credits;
19use crate::consensus::basic::decision_proposal::InvalidDecisionProposalRuleError;
20use crate::prelude::TimestampMillis;
21use crate::validation::ConsensusValidationResult;
22use crate::voting::vote_polls::yes_no_vote_poll::{
23 VotingPowerRounding, YesNoMinimumVotingPower, YesNoVotePoll, YesNoVotePollPurpose,
24};
25use crate::ProtocolError;
26use platform_value::btreemap_extensions::BTreeValueMapPathHelper;
27use platform_value::{Identifier, IdentifierBytes32, Value};
28use platform_version::version::PlatformVersion;
29use std::collections::BTreeMap;
30
31pub const DECISION_PROPOSALS_CONTRACT_ID: Identifier = Identifier(IdentifierBytes32([
36 40, 81, 10, 2, 166, 107, 62, 218, 6, 184, 111, 202, 230, 218, 170, 157, 181, 119, 102, 211,
37 195, 114, 92, 200, 90, 88, 205, 30, 174, 49, 203, 200,
38]));
39
40pub const PROPOSAL_DOCUMENT_TYPE_NAME: &str = "proposal";
42
43pub const DECISION_PROPOSAL_FUND_NAME: &str = PROPOSAL_DOCUMENT_TYPE_NAME;
46
47pub const MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME: &str = "multipleChoiceProposal";
50
51pub mod properties {
53 pub const TITLE: &str = "title";
55 pub const DESCRIPTION: &str = "description";
57 pub const URL: &str = "url";
60 pub const PASS_PERCENT: &str = "passPercent";
62 pub const MINIMUM_TURNOUT_PERCENT: &str = "minimumTurnoutPercent";
65 pub const END_DATE: &str = "endDate";
68}
69
70pub fn is_decision_proposal(contract_id: &Identifier, document_type_name: &str) -> bool {
74 *contract_id == DECISION_PROPOSALS_CONTRACT_ID
75 && document_type_name == PROPOSAL_DOCUMENT_TYPE_NAME
76}
77
78pub fn decision_proposal_required_fund(platform_version: &PlatformVersion) -> Credits {
82 platform_version
83 .fee_version
84 .vote_resolution_fund_fees
85 .decision_proposal_fund_required_amount
86}
87
88pub fn is_multiple_choice_proposal(contract_id: &Identifier, document_type_name: &str) -> bool {
92 *contract_id == DECISION_PROPOSALS_CONTRACT_ID
93 && document_type_name == MULTIPLE_CHOICE_PROPOSAL_DOCUMENT_TYPE_NAME
94}
95
96pub fn multiple_choice_proposal_processing_fee(platform_version: &PlatformVersion) -> Credits {
101 platform_version
102 .fee_version
103 .vote_resolution_fund_fees
104 .multiple_choice_proposal_processing_fee
105}
106
107pub fn decision_proposal_vote_poll_id(
118 document_id: Identifier,
119 platform_version: &PlatformVersion,
120) -> Result<Identifier, ProtocolError> {
121 YesNoVotePollPurpose::DecisionProposal { document_id }.unique_id(platform_version)
122}
123
124#[derive(Debug, Clone, PartialEq, Eq)]
126pub struct DecisionProposalVotePoll {
127 pub vote_poll: YesNoVotePoll,
129 pub end_date: TimestampMillis,
131}
132
133impl DecisionProposalVotePoll {
134 pub fn from_proposal(
150 document_id: Identifier,
151 properties: &BTreeMap<String, Value>,
152 platform_version: &PlatformVersion,
153 ) -> Result<ConsensusValidationResult<Self>, ProtocolError> {
154 match platform_version
155 .dpp
156 .voting_versions
157 .decision_proposal_vote_poll
158 {
159 Some(0) => Ok(Self::from_proposal_v0(
160 document_id,
161 properties,
162 platform_version,
163 )),
164 Some(version) => Err(ProtocolError::UnknownVersionMismatch {
165 method: "DecisionProposalVotePoll::from_proposal".to_string(),
166 known_versions: vec![0],
167 received: version,
168 }),
169 None => Err(ProtocolError::UnknownVersionError(
170 "DecisionProposalVotePoll::from_proposal is not active before protocol version 15"
171 .to_string(),
172 )),
173 }
174 }
175
176 fn from_proposal_v0(
182 document_id: Identifier,
183 properties: &BTreeMap<String, Value>,
184 platform_version: &PlatformVersion,
185 ) -> ConsensusValidationResult<Self> {
186 let read = || -> Result<Self, String> {
187 let percent = |path: &str| -> Result<u8, String> {
188 let value = properties
189 .get_optional_integer_at_path::<u64>(path)
190 .map_err(|error| format!("`{path}` is not a whole number: {error}"))?
191 .ok_or_else(|| format!("`{path}` is required"))?;
192 u8::try_from(value).map_err(|_| format!("`{path}` is at most 255, got {value}"))
193 };
194 let pass_percent = percent(properties::PASS_PERCENT)?;
195 let minimum_turnout_percent = percent(properties::MINIMUM_TURNOUT_PERCENT)?;
196 let end_date = properties
197 .get_optional_integer_at_path::<u64>(properties::END_DATE)
198 .map_err(|error| {
199 format!("`{}` is not a whole number: {error}", properties::END_DATE)
200 })?
201 .ok_or_else(|| format!("`{}` is required", properties::END_DATE))?;
202 let vote_poll = YesNoVotePoll {
203 purpose: YesNoVotePollPurpose::DecisionProposal { document_id },
204 supermajority_numerator: pass_percent,
205 supermajority_denominator: 100,
206 minimum_voting_power: YesNoMinimumVotingPower::FractionOfTotal {
207 numerator: minimum_turnout_percent,
208 denominator: 100,
209 rounding: VotingPowerRounding::Up,
210 },
211 };
212 vote_poll
213 .validate_parameters(platform_version)
214 .map_err(|error| match error {
215 ProtocolError::VoteError(reason) => reason,
216 other => other.to_string(),
217 })?;
218 Ok(Self {
219 vote_poll,
220 end_date,
221 })
222 };
223 match read() {
224 Ok(decision_proposal_vote_poll) => {
225 ConsensusValidationResult::new_with_data(decision_proposal_vote_poll)
226 }
227 Err(reason) => ConsensusValidationResult::new_with_error(
228 InvalidDecisionProposalRuleError::new(document_id, reason).into(),
229 ),
230 }
231 }
232}
233
234#[cfg(test)]
235mod tests {
236 use super::*;
237 use crate::consensus::basic::BasicError;
238 use crate::consensus::ConsensusError;
239
240 fn proposal(pass_percent: u8, minimum_turnout_percent: u8) -> BTreeMap<String, Value> {
241 BTreeMap::from([
242 (
243 "title".to_string(),
244 Value::Text("Raise the limit?".to_string()),
245 ),
246 (
247 properties::PASS_PERCENT.to_string(),
248 Value::U8(pass_percent),
249 ),
250 (
251 properties::MINIMUM_TURNOUT_PERCENT.to_string(),
252 Value::U8(minimum_turnout_percent),
253 ),
254 (properties::END_DATE.to_string(), Value::U64(5_000)),
255 ])
256 }
257
258 fn refusal(result: ConsensusValidationResult<DecisionProposalVotePoll>) -> String {
259 match result.errors.as_slice() {
260 [ConsensusError::BasicError(BasicError::InvalidDecisionProposalRuleError(error))] => {
261 error.reason().to_string()
262 }
263 other => panic!("expected one invalid rule error, got {other:?}"),
264 }
265 }
266
267 #[test]
268 fn should_read_the_poll_a_proposal_opens() {
269 let platform_version = PlatformVersion::latest();
270 let document_id = Identifier::new([7; 32]);
271 let result = DecisionProposalVotePoll::from_proposal(
272 document_id,
273 &proposal(60, 10),
274 platform_version,
275 )
276 .expect("active at 15");
277 assert_eq!(
278 result.into_data().expect("a valid rule"),
279 DecisionProposalVotePoll {
280 vote_poll: YesNoVotePoll {
281 purpose: YesNoVotePollPurpose::DecisionProposal { document_id },
282 supermajority_numerator: 60,
283 supermajority_denominator: 100,
284 minimum_voting_power: YesNoMinimumVotingPower::FractionOfTotal {
285 numerator: 10,
286 denominator: 100,
287 rounding: VotingPowerRounding::Up,
288 },
289 },
290 end_date: 5_000,
291 }
292 );
293 }
294
295 #[test]
297 fn should_pass_only_strictly_above_the_pass_percent() {
298 let platform_version = PlatformVersion::latest();
299 let vote_poll = DecisionProposalVotePoll::from_proposal(
300 Identifier::new([7; 32]),
301 &proposal(50, 0),
302 platform_version,
303 )
304 .expect("active at 15")
305 .into_data()
306 .expect("a valid rule")
307 .vote_poll;
308 let passes = |yes, no| {
309 vote_poll
310 .passes(yes, no, 1_000, platform_version)
311 .expect("15")
312 };
313 assert!(!passes(5, 5));
314 assert!(passes(6, 5));
315 let vote_poll = DecisionProposalVotePoll::from_proposal(
317 Identifier::new([7; 32]),
318 &proposal(50, 10),
319 platform_version,
320 )
321 .expect("active at 15")
322 .into_data()
323 .expect("a valid rule")
324 .vote_poll;
325 assert_eq!(
326 vote_poll
327 .required_voting_power(95, platform_version)
328 .expect("15"),
329 10
330 );
331 }
332
333 #[test]
334 fn should_refuse_a_rule_outside_the_limits() {
335 let platform_version = PlatformVersion::latest();
336 let document_id = Identifier::new([7; 32]);
337 let read = |properties: BTreeMap<String, Value>| {
338 DecisionProposalVotePoll::from_proposal(document_id, &properties, platform_version)
339 .expect("active at 15")
340 };
341 assert!(refusal(read(proposal(49, 0))).contains("at least 50%"));
344 assert!(refusal(read(proposal(100, 0))).contains("below its denominator"));
345 assert!(refusal(read(proposal(60, 51))).contains("at most 50%"));
346 assert!(read(proposal(50, 50)).is_valid());
347 let mut no_turnout = proposal(60, 0);
348 no_turnout.remove(properties::MINIMUM_TURNOUT_PERCENT);
349 assert!(refusal(read(no_turnout)).contains("is required"));
350 }
351
352 #[test]
354 fn should_name_the_poll_of_a_proposal_by_its_id_alone() {
355 let platform_version = PlatformVersion::latest();
356 let document_id = Identifier::new([7; 32]);
357 let opened = DecisionProposalVotePoll::from_proposal(
358 document_id,
359 &proposal(60, 10),
360 platform_version,
361 )
362 .expect("active at 15")
363 .into_data()
364 .expect("a valid rule")
365 .vote_poll;
366 assert_eq!(
367 decision_proposal_vote_poll_id(document_id, platform_version).expect("active at 15"),
368 opened.unique_id(platform_version).expect("active at 15")
369 );
370 assert_ne!(
371 decision_proposal_vote_poll_id(Identifier::new([8; 32]), platform_version)
372 .expect("active at 15"),
373 opened.unique_id(platform_version).expect("active at 15")
374 );
375 assert!(matches!(
376 decision_proposal_vote_poll_id(
377 document_id,
378 PlatformVersion::get(14).expect("expected protocol version 14")
379 ),
380 Err(ProtocolError::UnknownVersionError(_))
381 ));
382 }
383
384 #[test]
385 fn should_not_be_active_before_protocol_version_15() {
386 let platform_version = PlatformVersion::get(14).expect("expected protocol version 14");
387 assert!(matches!(
388 DecisionProposalVotePoll::from_proposal(
389 Identifier::new([7; 32]),
390 &proposal(60, 10),
391 platform_version,
392 ),
393 Err(ProtocolError::UnknownVersionError(_))
394 ));
395 }
396
397 #[test]
398 fn should_recognize_only_the_proposal_of_the_decision_proposals_contract() {
399 assert!(is_decision_proposal(
400 &DECISION_PROPOSALS_CONTRACT_ID,
401 PROPOSAL_DOCUMENT_TYPE_NAME
402 ));
403 assert!(!is_decision_proposal(
404 &DECISION_PROPOSALS_CONTRACT_ID,
405 "other"
406 ));
407 assert!(!is_decision_proposal(
408 &Identifier::new([1; 32]),
409 PROPOSAL_DOCUMENT_TYPE_NAME
410 ));
411 }
412
413 #[cfg(feature = "decision-proposals-contract")]
414 #[test]
415 fn should_name_the_contract_as_its_crate_does() {
416 use data_contracts::decision_proposals_contract;
417 use decision_proposals_contract::v1::document_types::proposal;
418
419 assert_eq!(
420 DECISION_PROPOSALS_CONTRACT_ID,
421 decision_proposals_contract::ID
422 );
423 assert_eq!(PROPOSAL_DOCUMENT_TYPE_NAME, proposal::NAME);
424 assert_eq!(properties::TITLE, proposal::properties::TITLE);
425 assert_eq!(properties::DESCRIPTION, proposal::properties::DESCRIPTION);
426 assert_eq!(properties::URL, proposal::properties::URL);
427 assert_eq!(properties::PASS_PERCENT, proposal::properties::PASS_PERCENT);
428 assert_eq!(
429 properties::MINIMUM_TURNOUT_PERCENT,
430 proposal::properties::MINIMUM_TURNOUT_PERCENT
431 );
432 assert_eq!(properties::END_DATE, proposal::properties::END_DATE);
433 }
434
435 #[cfg(feature = "decision-proposals-contract")]
439 #[test]
440 fn should_freeze_the_text_of_a_proposal_after_a_day_or_a_fifth_of_its_run() {
441 use crate::data_contract::accessors::v0::DataContractV0Getters;
442 use crate::data_contract::document_type::accessors::{
443 DocumentTypeV0Getters, DocumentTypeV2Getters,
444 };
445 use crate::data_contract::document_type::property_constraints::DocumentSystemValues;
446 use crate::system_data_contracts::{load_system_data_contract, SystemDataContract};
447
448 const DAY_MS: u64 = 86_400_000;
449 let platform_version = PlatformVersion::latest();
450 let contract =
451 load_system_data_contract(SystemDataContract::DecisionProposals, platform_version)
452 .expect("the contract loads at 15");
453 let document_type = contract
454 .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME)
455 .expect("the proposal type");
456 let created_at = 1_000;
457 let frozen = |property: &str, run: u64, edited_after: u64| {
458 document_type.immutable_field_conditions()[property]
459 .holds(
460 &Value::Map(vec![(
461 Value::Text(properties::END_DATE.to_string()),
462 Value::U64(created_at + run),
463 )]),
464 &DocumentSystemValues {
465 created_at: Some(created_at),
466 updated_at: Some(created_at + edited_after),
467 ..Default::default()
468 },
469 )
470 .expect("the condition evaluates")
471 };
472 for property in ["title", "description", "url"] {
473 assert!(
475 !frozen(property, 14 * DAY_MS, DAY_MS),
476 "{property} at a day"
477 );
478 assert!(
479 frozen(property, 14 * DAY_MS, DAY_MS + 1),
480 "{property} after a day"
481 );
482 let fifth = 2 * DAY_MS / 5;
484 assert!(
485 !frozen(property, 2 * DAY_MS, fifth),
486 "{property} at a fifth"
487 );
488 assert!(
489 frozen(property, 2 * DAY_MS, fifth + 1),
490 "{property} after a fifth"
491 );
492 }
493 for property in [
494 properties::PASS_PERCENT,
495 properties::MINIMUM_TURNOUT_PERCENT,
496 properties::END_DATE,
497 ] {
498 assert!(
499 document_type.immutable_fields().contains(property)
500 && !document_type
501 .immutable_field_conditions()
502 .contains_key(property),
503 "{property} never changes"
504 );
505 }
506 assert!(document_type.documents_mutable());
507 assert!(document_type.documents_keep_history());
508 }
509
510 #[cfg(feature = "decision-proposals-contract")]
513 #[test]
514 fn should_state_the_decision_proposal_fund_on_a_proposal_create() {
515 use crate::data_contract::accessors::v0::DataContractV0Getters;
516 use crate::data_contract::document_type::methods::DocumentTypeV0Methods;
517 use crate::document::{Document, DocumentV0};
518 use crate::system_data_contracts::{load_system_data_contract, SystemDataContract};
519
520 let platform_version = PlatformVersion::latest();
521 let contract =
522 load_system_data_contract(SystemDataContract::DecisionProposals, platform_version)
523 .expect("the contract loads at 15");
524 let document_type = contract
525 .document_type_for_name(PROPOSAL_DOCUMENT_TYPE_NAME)
526 .expect("the proposal type");
527 let document: Document = DocumentV0 {
528 properties: proposal(60, 10),
529 ..Default::default()
530 }
531 .into();
532 assert_eq!(
533 document_type
534 .prefunded_voting_balance_for_document(&document, platform_version)
535 .expect("active"),
536 Some((DECISION_PROPOSAL_FUND_NAME.to_string(), 50_000_000_000))
537 );
538 }
539}