pallet_democracy/
conviction.rs1use crate::types::Delegations;
21use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
22use core::result::Result;
23use scale_info::TypeInfo;
24use sp_runtime::{
25 traits::{Bounded, CheckedDiv, CheckedMul, Zero},
26 RuntimeDebug,
27};
28
29#[derive(
31 Encode,
32 MaxEncodedLen,
33 Decode,
34 DecodeWithMemTracking,
35 Copy,
36 Clone,
37 Eq,
38 PartialEq,
39 Ord,
40 PartialOrd,
41 RuntimeDebug,
42 TypeInfo,
43)]
44pub enum Conviction {
45 None,
47 Locked1x,
49 Locked2x,
51 Locked3x,
53 Locked4x,
55 Locked5x,
57 Locked6x,
59}
60
61impl Default for Conviction {
62 fn default() -> Self {
63 Conviction::None
64 }
65}
66
67impl From<Conviction> for u8 {
68 fn from(c: Conviction) -> u8 {
69 match c {
70 Conviction::None => 0,
71 Conviction::Locked1x => 1,
72 Conviction::Locked2x => 2,
73 Conviction::Locked3x => 3,
74 Conviction::Locked4x => 4,
75 Conviction::Locked5x => 5,
76 Conviction::Locked6x => 6,
77 }
78 }
79}
80
81impl TryFrom<u8> for Conviction {
82 type Error = ();
83 fn try_from(i: u8) -> Result<Conviction, ()> {
84 Ok(match i {
85 0 => Conviction::None,
86 1 => Conviction::Locked1x,
87 2 => Conviction::Locked2x,
88 3 => Conviction::Locked3x,
89 4 => Conviction::Locked4x,
90 5 => Conviction::Locked5x,
91 6 => Conviction::Locked6x,
92 _ => return Err(()),
93 })
94 }
95}
96
97impl Conviction {
98 pub fn lock_periods(self) -> u32 {
101 match self {
102 Conviction::None => 0,
103 Conviction::Locked1x => 1,
104 Conviction::Locked2x => 2,
105 Conviction::Locked3x => 4,
106 Conviction::Locked4x => 8,
107 Conviction::Locked5x => 16,
108 Conviction::Locked6x => 32,
109 }
110 }
111
112 pub fn votes<B: From<u8> + Zero + Copy + CheckedMul + CheckedDiv + Bounded>(
114 self,
115 capital: B,
116 ) -> Delegations<B> {
117 let votes = match self {
118 Conviction::None => capital.checked_div(&10u8.into()).unwrap_or_else(Zero::zero),
119 x => capital.checked_mul(&u8::from(x).into()).unwrap_or_else(B::max_value),
120 };
121 Delegations { votes, capital }
122 }
123}
124
125impl Bounded for Conviction {
126 fn min_value() -> Self {
127 Conviction::None
128 }
129 fn max_value() -> Self {
130 Conviction::Locked6x
131 }
132}