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
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use crate::traits::{
    Apply, Approved, ConsistentThresholdStructure, DeriveThresholdRequirement, Revert,
    UpdateOutcome, VoteVector,
};
use codec::{Decode, Encode};
use frame_support::Parameter;
use sp_runtime::PerThing;
use sp_std::prelude::*;

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
/// The types of vote weightings supported by default in `vote-yesno`
pub enum SupportedVoteTypes {
    /// 1 account 1 vote
    OneAccountOneVote,
    /// Defaults to share weights
    ShareWeighted,
    /// Special signal minting policy?
    Custom,
}

impl Default for SupportedVoteTypes {
    fn default() -> SupportedVoteTypes {
        SupportedVoteTypes::ShareWeighted
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
/// The vote-yesno voter options (direction)
pub enum VoterYesNoView {
    /// Voted in favor
    InFavor,
    /// Voted against
    Against,
    /// Acknowledged but abstained
    Abstain,
}

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
/// Binary vote to express for/against with magnitude
/// ~ vectors have direction and magnitude, not to be confused with `Vec`
pub struct YesNoVote<Signal, Hash> {
    magnitude: Signal,
    direction: VoterYesNoView,
    justification: Option<Hash>,
}

impl<Signal, Hash: Clone> YesNoVote<Signal, Hash> {
    pub fn new(magnitude: Signal, direction: VoterYesNoView, justification: Option<Hash>) -> Self {
        YesNoVote {
            magnitude,
            direction,
            justification,
        }
    }

    pub fn justification(&self) -> Option<Hash> {
        self.justification.clone()
    }
}

impl<Signal: Copy, Hash: Clone> VoteVector<Signal, VoterYesNoView> for YesNoVote<Signal, Hash> {
    fn magnitude(&self) -> Signal {
        self.magnitude
    }

    fn direction(&self) -> VoterYesNoView {
        self.direction
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
/// The type for the threshold
pub enum ThresholdType<Signal, FineArithmetic>
where
    FineArithmetic: PerThing,
{
    Count(Signal),
    Percentage(FineArithmetic),
}

impl<Signal: From<u32>, FineArithmetic: PerThing> Default
    for ThresholdType<Signal, FineArithmetic>
{
    fn default() -> ThresholdType<Signal, FineArithmetic> {
        ThresholdType::Count(0u32.into())
    }
}

#[derive(Clone, Copy, Default, PartialEq, Eq, Encode, Decode, sp_runtime::RuntimeDebug)]
/// This is the threshold configuration
/// - evaluates passage of vote state
pub struct ThresholdConfig<Signal, FineArithmetic>
where
    Signal: From<u32>,
    FineArithmetic: PerThing,
{
    /// Support threshold
    support_required: ThresholdType<Signal, FineArithmetic>,
    /// Required turnout
    turnout_required: ThresholdType<Signal, FineArithmetic>,
}
impl<Signal: From<u32>, FineArithmetic: PerThing> From<(u32, u32)>
    for ThresholdConfig<Signal, FineArithmetic>
{
    fn from(other: (u32, u32)) -> ThresholdConfig<Signal, FineArithmetic> {
        ThresholdConfig {
            support_required: ThresholdType::Count(other.0.into()),
            turnout_required: ThresholdType::Count(other.1.into()),
        }
    }
}

use crate::schedule::{ThresholdConfigBuilder, ThresholdTypeBuilder};
// local extension
impl<Signal: From<u32>, FineArithmetic: PerThing> From<ThresholdTypeBuilder<FineArithmetic>>
    for ThresholdType<Signal, FineArithmetic>
{
    fn from(
        threshold_type_builder: ThresholdTypeBuilder<FineArithmetic>,
    ) -> ThresholdType<Signal, FineArithmetic> {
        match threshold_type_builder {
            ThresholdTypeBuilder::Count(count) => ThresholdType::Count(count.into()), // From<u32>
            ThresholdTypeBuilder::Percentage(percent) => ThresholdType::Percentage(percent),
        }
    }
}
// local extension
impl<Signal: From<u32>, FineArithmetic: PerThing> From<ThresholdConfigBuilder<FineArithmetic>>
    for ThresholdConfig<Signal, FineArithmetic>
{
    fn from(
        threshold_config_builder: ThresholdConfigBuilder<FineArithmetic>,
    ) -> ThresholdConfig<Signal, FineArithmetic> {
        ThresholdConfig {
            support_required: threshold_config_builder.support_required.into(),
            turnout_required: threshold_config_builder.turnout_required.into(),
        }
    }
}

impl<Signal: From<u32>, FineArithmetic: PerThing> ThresholdConfig<Signal, FineArithmetic> {
    pub fn new_signal_count_threshold(support_required: Signal, turnout_required: Signal) -> Self {
        ThresholdConfig {
            support_required: ThresholdType::Count(support_required),
            turnout_required: ThresholdType::Count(turnout_required),
        }
    }
    pub fn new_percentage_threshold(
        support_required: FineArithmetic,
        turnout_required: FineArithmetic,
    ) -> Self {
        ThresholdConfig {
            support_required: ThresholdType::Percentage(support_required),
            turnout_required: ThresholdType::Percentage(turnout_required),
        }
    }
}

impl<Signal: From<u32> + Copy, FineArithmetic: PerThing + Copy> ConsistentThresholdStructure
    for ThresholdConfig<Signal, FineArithmetic>
{
    fn is_percentage_threshold(&self) -> bool {
        match (self.support_required, self.turnout_required) {
            (ThresholdType::Percentage(_), ThresholdType::Percentage(_)) => true,
            _ => false,
        }
    }
    fn is_count_threshold(&self) -> bool {
        match (self.support_required, self.turnout_required) {
            (ThresholdType::Count(_), ThresholdType::Count(_)) => true,
            _ => false,
        }
    }
    fn has_consistent_structure(&self) -> bool {
        Self::is_percentage_threshold(self) || Self::is_count_threshold(self)
    }
}

impl<
        Signal: From<u32> + Copy,
        FineArithmetic: PerThing + sp_std::ops::Mul<Signal, Output = Signal>,
    > DeriveThresholdRequirement<Signal> for ThresholdConfig<Signal, FineArithmetic>
{
    fn derive_support_requirement(&self, turnout: Signal) -> Signal {
        match self.support_required {
            ThresholdType::Count(signal) => signal,
            ThresholdType::Percentage(signal) => signal * turnout,
        }
    }
    fn derive_turnout_requirement(&self, turnout: Signal) -> Signal {
        match self.turnout_required {
            ThresholdType::Count(signal) => signal,
            ThresholdType::Percentage(signal) => signal * turnout,
        }
    }
}

#[derive(PartialEq, Eq, Default, Clone, Encode, Decode, sp_runtime::RuntimeDebug)]
/// The state of an ongoing vote
pub struct VoteState<Signal, FineArithmetic, BlockNumber>
where
    Signal: From<u32>,
    FineArithmetic: PerThing,
{
    /// u32 in favor
    in_favor: Signal,
    /// u32 against
    against: Signal,
    /// All signal that votes
    turnout: Signal,
    /// All signal that could vote
    all_possible_turnout: Signal,
    /// The threshold configuration for passage
    threshold: ThresholdConfig<Signal, FineArithmetic>,
    /// The time at which this is initialized
    initialized: BlockNumber,
    /// The time at which this vote state expired, now an Option
    expires: Option<BlockNumber>,
    /// The vote outcome
    outcome: VoteOutcome,
}

impl<
        Signal: Copy
            + From<u32>
            + Default
            + sp_std::ops::Add<Output = Signal>
            + sp_std::ops::Sub<Output = Signal>,
        FineArithmetic: PerThing + Default,
        BlockNumber: Parameter + Copy + Default,
    > VoteState<Signal, FineArithmetic, BlockNumber>
{
    pub fn new(
        all_possible_turnout: Signal,
        threshold: ThresholdConfig<Signal, FineArithmetic>,
        initialized: BlockNumber,
        expires: Option<BlockNumber>,
    ) -> VoteState<Signal, FineArithmetic, BlockNumber> {
        VoteState {
            all_possible_turnout,
            threshold,
            initialized,
            expires,
            outcome: VoteOutcome::Voting,
            ..Default::default()
        }
    }
    pub fn in_favor(&self) -> Signal {
        self.in_favor
    }
    pub fn against(&self) -> Signal {
        self.against
    }
    pub fn turnout(&self) -> Signal {
        self.turnout
    }
    pub fn all_possible_turnout(&self) -> Signal {
        self.all_possible_turnout
    }
    pub fn expires(&self) -> Option<BlockNumber> {
        self.expires
    }
    pub fn threshold(&self) -> ThresholdConfig<Signal, FineArithmetic> {
        self.threshold
    }
    pub fn outcome(&self) -> VoteOutcome {
        self.outcome
    }

    pub fn add_in_favor_vote(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() + magnitude;
        let new_in_favor = self.in_favor() + magnitude;
        VoteState {
            in_favor: new_in_favor,
            turnout: new_turnout,
            ..self.clone()
        }
    }
    pub fn add_against_vote(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() + magnitude;
        let new_against = self.against() + magnitude;
        VoteState {
            against: new_against,
            turnout: new_turnout,
            ..self.clone()
        }
    }
    pub fn add_abstention(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() + magnitude;
        VoteState {
            turnout: new_turnout,
            ..self.clone()
        }
    }
    pub fn remove_in_favor_vote(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() - magnitude;
        let new_in_favor = self.in_favor() - magnitude;
        VoteState {
            in_favor: new_in_favor,
            turnout: new_turnout,
            ..self.clone()
        }
    }
    pub fn remove_against_vote(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() - magnitude;
        let new_against = self.against() - magnitude;
        VoteState {
            against: new_against,
            turnout: new_turnout,
            ..self.clone()
        }
    }
    pub fn remove_abstention(&self, magnitude: Signal) -> Self {
        let new_turnout = self.turnout() - magnitude;
        VoteState {
            turnout: new_turnout,
            ..self.clone()
        }
    }
}

impl<
        Signal: Parameter
            + Copy
            + From<u32>
            + Default
            + PartialOrd
            + sp_std::ops::Add<Output = Signal>
            + sp_std::ops::Sub<Output = Signal>,
        FineArithmetic: PerThing + Default + sp_std::ops::Mul<Signal, Output = Signal>,
        BlockNumber: Parameter + Copy + Default,
    > Approved for VoteState<Signal, FineArithmetic, BlockNumber>
{
    fn approved(&self) -> bool {
        self.in_favor()
            > self
                .threshold
                .derive_support_requirement(self.all_possible_turnout())
            && self.turnout()
                > self
                    .threshold
                    .derive_turnout_requirement(self.all_possible_turnout())
    }
}

impl<
        Signal: Parameter
            + Copy
            + From<u32>
            + Default
            + sp_std::ops::Add<Output = Signal>
            + sp_std::ops::Sub<Output = Signal>,
        Hash: Clone,
        FineArithmetic: PerThing + Default,
        BlockNumber: Parameter + Copy + Default,
    > Apply<YesNoVote<Signal, Hash>> for VoteState<Signal, FineArithmetic, BlockNumber>
{
    fn apply(
        &self,
        vote: YesNoVote<Signal, Hash>,
    ) -> VoteState<Signal, FineArithmetic, BlockNumber> {
        match vote.direction() {
            VoterYesNoView::InFavor => self.add_in_favor_vote(vote.magnitude()),
            VoterYesNoView::Against => self.add_against_vote(vote.magnitude()),
            VoterYesNoView::Abstain => self.add_abstention(vote.magnitude()),
        }
    }
}

impl<
        Signal: Parameter
            + Copy
            + From<u32>
            + Default
            + sp_std::ops::Add<Output = Signal>
            + sp_std::ops::Sub<Output = Signal>,
        Hash: Clone,
        FineArithmetic: PerThing + Default,
        BlockNumber: Parameter + Copy + Default,
    > Revert<YesNoVote<Signal, Hash>> for VoteState<Signal, FineArithmetic, BlockNumber>
{
    fn revert(
        &self,
        vote: YesNoVote<Signal, Hash>,
    ) -> VoteState<Signal, FineArithmetic, BlockNumber> {
        match vote.direction() {
            VoterYesNoView::InFavor => self.remove_in_favor_vote(vote.magnitude()),
            VoterYesNoView::Against => self.remove_against_vote(vote.magnitude()),
            VoterYesNoView::Abstain => self.remove_abstention(vote.magnitude()),
        }
    }
}

impl<
        Signal: Parameter
            + Copy
            + From<u32>
            + Default
            + PartialOrd
            + sp_std::ops::Add<Output = Signal>
            + sp_std::ops::Sub<Output = Signal>,
        FineArithmetic: PerThing + Default + sp_std::ops::Mul<Signal, Output = Signal>,
        BlockNumber: Parameter + Copy + Default,
    > UpdateOutcome for VoteState<Signal, FineArithmetic, BlockNumber>
{
    fn update_outcome(&self) -> Option<VoteState<Signal, FineArithmetic, BlockNumber>> {
        let current_outcome = self.outcome();
        match current_outcome {
            VoteOutcome::Voting => {
                if self.approved() {
                    Some(VoteState {
                        outcome: VoteOutcome::Approved,
                        ..self.clone()
                    })
                } else {
                    None
                }
            }
            _ => None,
        }
    }
}

#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, sp_runtime::RuntimeDebug)]
#[non_exhaustive]
/// The vote's state and outcome
pub enum VoteOutcome {
    /// The VoteId in question has been reserved but is not yet open for voting (context is schedule)
    NotStarted,
    /// The VoteState associated with the VoteId is open to voting by the given `ShareId`
    Voting,
    /// The VoteState is approved, thereby unlocking the next `VoteId` if it wraps Some(VoteId)
    Approved,
    /// The VoteState is rejected and all dependent `VoteId`s are not opened
    Rejected,
}

impl Default for VoteOutcome {
    fn default() -> Self {
        VoteOutcome::NotStarted
    }
}

impl Approved for VoteOutcome {
    fn approved(&self) -> bool {
        match self {
            VoteOutcome::Approved => true,
            _ => false,
        }
    }
}