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
//! Voting Mechanism.
//!
//! ## Overview
//!
//! This module provides a weighted voting [`Tally`] implementation used for managing the multisig's proposals.
//! Members each have a balance in voting tokens and this balance differentiate their voting power
//! as every vote utilizes the entire `power` of the said member.
//! This empowers decision-making where certain members possess greater influence.

use crate::{origin::INV4Origin, BalanceOf, Config, CoreStorage, Error, Multisig, Pallet};
use codec::{Decode, Encode, HasCompact, MaxEncodedLen};
use core::marker::PhantomData;
use frame_support::{
    pallet_prelude::{Member, RuntimeDebug},
    traits::{fungibles::Inspect, PollStatus, VoteTally},
    BoundedBTreeMap, CloneNoBound, EqNoBound, Parameter, PartialEqNoBound, RuntimeDebugNoBound,
};
use frame_system::pallet_prelude::BlockNumberFor;
use scale_info::TypeInfo;
use sp_runtime::{
    traits::{One, Zero},
    DispatchError, Perbill,
};
use sp_std::vec::Vec;

pub type Votes<T> = BalanceOf<T>;
pub type Core<T> = <T as Config>::CoreId;

/// Aggregated votes for an ongoing poll by members of a core.
#[derive(
    CloneNoBound,
    PartialEqNoBound,
    EqNoBound,
    RuntimeDebugNoBound,
    TypeInfo,
    Encode,
    Decode,
    MaxEncodedLen,
)]
#[scale_info(skip_type_params(T))]
#[codec(mel_bound())]
pub struct Tally<T: Config> {
    pub ayes: Votes<T>,
    pub nays: Votes<T>,
    pub records: BoundedBTreeMap<T::AccountId, Vote<Votes<T>>, T::MaxCallers>,
    dummy: PhantomData<T>,
}

impl<T: Config> Tally<T> {
    /// Allows for building a `Tally` manually.
    pub fn from_parts(
        ayes: Votes<T>,
        nays: Votes<T>,
        records: BoundedBTreeMap<T::AccountId, Vote<Votes<T>>, T::MaxCallers>,
    ) -> Self {
        Tally {
            ayes,
            nays,
            records,
            dummy: PhantomData,
        }
    }

    /// Check if a vote is valid and add the member's total voting token balance to the tally.
    pub fn process_vote(
        &mut self,
        account: T::AccountId,
        maybe_vote: Option<Vote<Votes<T>>>,
    ) -> Result<Vote<Votes<T>>, DispatchError> {
        let votes = if let Some(vote) = maybe_vote {
            self.records
                .try_insert(account, vote)
                .map_err(|_| Error::<T>::MaxCallersExceeded)?;
            vote
        } else {
            self.records.remove(&account).ok_or(Error::<T>::NotAVoter)?
        };

        let (ayes, nays) = self.records.values().fold(
            (Zero::zero(), Zero::zero()),
            |(mut ayes, mut nays): (Votes<T>, Votes<T>), vote| {
                match vote {
                    Vote::Aye(v) => ayes += *v,
                    Vote::Nay(v) => nays += *v,
                };
                (ayes, nays)
            },
        );

        self.ayes = ayes;
        self.nays = nays;

        Ok(votes)
    }
}

impl<T: Config> VoteTally<Votes<T>, Core<T>> for Tally<T> {
    fn new(_: Core<T>) -> Self {
        Self {
            ayes: Zero::zero(),
            nays: Zero::zero(),
            records: BoundedBTreeMap::default(),
            dummy: PhantomData,
        }
    }

    fn ayes(&self, _: Core<T>) -> Votes<T> {
        self.ayes
    }

    fn support(&self, class: Core<T>) -> Perbill {
        Perbill::from_rational(self.ayes, T::AssetsProvider::total_issuance(class))
    }

    fn approval(&self, _: Core<T>) -> Perbill {
        Perbill::from_rational(
            self.ayes,
            <Votes<T> as One>::one().max(self.ayes + self.nays),
        )
    }

    #[cfg(feature = "runtime-benchmarks")]
    fn unanimity(_: Core<T>) -> Self {
        todo!()
    }

    #[cfg(feature = "runtime-benchmarks")]
    fn rejection(_: Core<T>) -> Self {
        todo!()
    }

    #[cfg(feature = "runtime-benchmarks")]
    fn from_requirements(_: Perbill, _: Perbill, _: Core<T>) -> Self {
        todo!()
    }

    #[cfg(feature = "runtime-benchmarks")]
    fn setup(_: Core<T>, _: Perbill) {
        todo!()
    }
}

pub trait CustomPolling<Tally> {
    type Index: Ord + PartialOrd + Copy + MaxEncodedLen;
    type Votes: Parameter + Ord + PartialOrd + Copy + HasCompact + MaxEncodedLen;
    type Class: Parameter + Member + Ord + PartialOrd + MaxEncodedLen;
    type Moment;

    // Provides a vec of values that `T` may take.
    fn classes() -> Vec<Self::Class>;

    /// `Some` if the referendum `index` can be voted on, along with the tally and class of
    /// referendum.
    ///
    /// Don't use this if you might mutate - use `try_access_poll` instead.
    fn as_ongoing(class: Self::Class, index: Self::Index) -> Option<(Tally, Self::Class)>;

    fn access_poll<R>(
        class: Self::Class,
        index: Self::Index,
        f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> R,
    ) -> R;

    fn try_access_poll<R>(
        class: Self::Class,
        index: Self::Index,
        f: impl FnOnce(PollStatus<&mut Tally, Self::Moment, Self::Class>) -> Result<R, DispatchError>,
    ) -> Result<R, DispatchError>;
}

impl<T: Config> CustomPolling<Tally<T>> for Pallet<T> {
    type Index = T::Hash;
    type Votes = Votes<T>;
    type Moment = BlockNumberFor<T>;
    type Class = T::CoreId;

    fn classes() -> Vec<Self::Class> {
        CoreStorage::<T>::iter_keys().collect()
    }

    fn access_poll<R>(
        class: Self::Class,
        index: Self::Index,
        f: impl FnOnce(PollStatus<&mut Tally<T>, BlockNumberFor<T>, T::CoreId>) -> R,
    ) -> R {
        match Multisig::<T>::get(class, index) {
            Some(mut m) => {
                let result = f(PollStatus::Ongoing(&mut m.tally, class));
                Multisig::<T>::insert(class, index, m);
                result
            }
            _ => f(PollStatus::None),
        }
    }

    fn try_access_poll<R>(
        class: Self::Class,
        index: Self::Index,
        f: impl FnOnce(
            PollStatus<&mut Tally<T>, BlockNumberFor<T>, T::CoreId>,
        ) -> Result<R, DispatchError>,
    ) -> Result<R, DispatchError> {
        match Multisig::<T>::get(class, index) {
            Some(mut m) => {
                let result = f(PollStatus::Ongoing(&mut m.tally, class))?;
                Multisig::<T>::insert(class, index, m);
                Ok(result)
            }
            _ => f(PollStatus::None),
        }
    }

    fn as_ongoing(class: Self::Class, index: Self::Index) -> Option<(Tally<T>, T::CoreId)> {
        Multisig::<T>::get(class, index).map(|m| (m.tally, class))
    }
}

/// Represents a proposal vote within a multisig context.
///
/// This is both the vote and how many voting tokens it carries.
#[derive(PartialEq, Eq, Clone, Copy, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
pub enum Vote<Votes> {
    Aye(Votes),
    Nay(Votes),
}

/// Type alias for [`Vote`] with [`BalanceOf`].
pub type VoteRecord<T> = Vote<Votes<T>>;

impl<T: Config> Pallet<T>
where
    Result<INV4Origin<T>, <T as frame_system::Config>::RuntimeOrigin>:
        From<<T as frame_system::Config>::RuntimeOrigin>,
{
    /// Returns the minimum support and required approval thresholds of a core.
    pub fn minimum_support_and_required_approval(core_id: T::CoreId) -> Option<(Perbill, Perbill)> {
        CoreStorage::<T>::get(core_id).map(|core| (core.minimum_support, core.required_approval))
    }
}