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
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(test)]
mod tests;

use frame_support::{
    decl_error,
    decl_event,
    decl_module,
    traits::{
        Currency,
        ExistenceRequirement,
        Get,
    },
};
use frame_system::{
    self as system,
    ensure_signed,
};
use sp_runtime::{
    traits::{
        AccountIdConversion,
        CheckedSub,
    },
    DispatchError,
    DispatchResult,
    ModuleId,
    Permill,
};
use util::traits::GetGroup;

type BalanceOf<T> = <<T as Trait>::Currency as Currency<
    <T as system::Trait>::AccountId,
>>::Balance;

pub trait Trait: system::Trait + org::Trait {
    /// The overarching event type
    type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
    /// The currency type
    type Currency: Currency<Self::AccountId>;
    //// Taxes for some transfers
    type TransactionFee: Get<BalanceOf<Self>>;
    /// Where the conditional taxes go
    type Treasury: Get<ModuleId>;
}

decl_event!(
    pub enum Event<T> where
        <T as system::Trait>::AccountId,
        <T as org::Trait>::OrgId,
        Balance = BalanceOf<T>,
    {
        DonationExecuted(AccountId, OrgId, Balance, bool),
    }
);

decl_error! {
    pub enum Error for Module<T: Trait> {
        AccountHasNoOwnershipInOrg,
        NotEnoughFundsInFreeToMakeTransfer,
        CannotDonateToOrgThatDNE,
    }
}

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        fn deposit_event() = default;

        #[weight = 0]
        fn make_prop_donation_with_fee(
            origin,
            org: T::OrgId,
            amt: BalanceOf<T>
        ) -> DispatchResult {
            let sender = ensure_signed(origin)?;
            Self::donate(&sender, org, amt, true)?;
            Self::deposit_event(RawEvent::DonationExecuted(sender, org, amt, true));
            Ok(())
        }
        #[weight = 0]
        fn make_prop_donation_without_fee(
            origin,
            org: T::OrgId,
            amt: BalanceOf<T>
        ) -> DispatchResult {
            let sender = ensure_signed(origin)?;
            Self::donate(&sender, org, amt, false)?;
            Self::deposit_event(RawEvent::DonationExecuted(sender, org, amt, false));
            Ok(())
        }
    }
}

impl<T: Trait> Module<T> {
    /// The account ID of this module's treasury
    ///
    /// This actually does computation. If you need to keep using it, then make sure you cache the
    /// value and only call this once.
    pub fn account_id() -> T::AccountId {
        T::Treasury::get().into_account()
    }
    pub fn donate(
        sender: &T::AccountId,
        recipient: T::OrgId,
        amt: BalanceOf<T>,
        transaction_fee: bool,
    ) -> DispatchResult {
        let free = T::Currency::free_balance(sender);
        let total_transfer = if transaction_fee {
            amt + T::TransactionFee::get()
        } else {
            amt
        };
        let _ = free
            .checked_sub(&total_transfer)
            .ok_or(Error::<T>::NotEnoughFundsInFreeToMakeTransfer)?;
        // Get the membership set of the Org
        let group = <org::Module<T>>::get_group(recipient)
            .ok_or(Error::<T>::CannotDonateToOrgThatDNE)?;
        // iterate through and pay the transfer out
        group
            .0
            .into_iter()
            .map(|acc: T::AccountId| -> DispatchResult {
                let amt_due = Self::calculate_proportional_amount_for_account(
                    amt,
                    acc.clone(),
                    recipient,
                )?;
                T::Currency::transfer(
                    sender,
                    &acc,
                    amt_due,
                    ExistenceRequirement::KeepAlive,
                )?;
                Ok(())
            })
            .collect::<DispatchResult>()?;
        if transaction_fee {
            // pay the transaction fee last
            T::Currency::transfer(
                &sender,
                &Self::account_id(),
                T::TransactionFee::get(),
                ExistenceRequirement::KeepAlive,
            )
        } else {
            Ok(())
        }
    }
    fn calculate_proportional_amount_for_account(
        amount: BalanceOf<T>,
        account: T::AccountId,
        group: T::OrgId,
    ) -> Result<BalanceOf<T>, DispatchError> {
        let issuance = <org::Module<T>>::total_issuance(group);
        let acc_ownership = <org::Module<T>>::members(group, &account)
            .ok_or(Error::<T>::AccountHasNoOwnershipInOrg)?;
        let ownership = Permill::from_rational_approximation(
            acc_ownership.total(),
            issuance,
        );
        Ok(ownership * amount)
    }
}