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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! # Equilibrium Treasury Pallet
//!
//! Equilibrium's Treasury Pallet is a Substrate module that manages and stores
//! user transaction fees, charges treasury fee - small fee on active debt and
//! exchanges non-Eq currencies for Eq when account should pay fees but have
//! insufficient Eq

#![cfg_attr(not(feature = "std"), no_std)]

mod mock;
mod tests;

use codec::Codec;
use eq_balances::{BalanceGetter, EqCurrency};
use eq_oracle::PriceGetter;
use eq_primitives::{currency::Currency, FeeManager, InterestRateError};
use eq_utils::{balance_from_fixedi64, eq_ensure, eq_log, fixedi64_from_balance, ok_or_error};
#[allow(unused_imports)]
use frame_support::debug; // Required by eq_log! macro, compiler sees it as unused
use frame_support::{
    decl_error, decl_event, decl_module, decl_storage,
    dispatch::DispatchResult,
    traits::{ExistenceRequirement, Get, UnixTime, WithdrawReasons},
    Parameter,
};
use sp_arithmetic::{traits::Saturating, FixedI64, FixedPointNumber};
use sp_runtime::traits::{
    AccountIdConversion, AtLeast32BitUnsigned, CheckedSub, MaybeSerializeDeserialize, Member, Zero,
};
use sp_runtime::{sp_std::prelude::*, FixedI128, ModuleId, Permill};
use system as frame_system;
use system::ensure_signed;

/// Substrate pallet configuration trait
pub trait Trait: authorship::Trait {
    // type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
    type ModuleId: Get<ModuleId>;

    /// Numerical representation of stored balances
    type Balance: Member
        + AtLeast32BitUnsigned
        + MaybeSerializeDeserialize
        + Codec
        + Copy
        + Parameter
        + Default
        + From<u64>
        + Into<u64>;
    /// Gets users balances to calculate fees and check margin calls
    type BalanceGetter: BalanceGetter<Self::AccountId, Self::Balance>;
    /// Used for currency-related operations and calculations
    type EqCurrency: EqCurrency<Self::AccountId, Self::Balance>;
    /// Gets currency prices from oracle
    type PriceGetter: PriceGetter;
    /// Timestamp provider
    type UnixTime: UnixTime;
    /// Fee fro collateral buyouts (any currency that is not Eq)
    type BuyFee: Get<Permill>;
    /// Fee fro Eq buyouts
    type SellFee: Get<Permill>;
    /// Treasury pallet fee
    type Fee: Get<Permill>;
    /// Fee part that stays in Treasury pallet
    type WeightFeeTreasury: Get<u32>;
    /// Fee part that goes to validator
    type WeightFeeValidator: Get<u32>;
}

decl_storage! {
    trait Store for Module<T: Trait> as EqTreasury {}
}

// decl_event!(
//     pub enum Event<T> where <T as system::Trait>::AccountId{
//         // /// TODO - empty events list
//         // AEvent(AccountId),
//     }
// );

decl_error! {
    /// Pallet errors
    pub enum Error for Module<T: Trait> {
        /// Amount to sell is less than or equal to zero
        NothingToSell,
        /// Eq tokens cannot be used for collateral buyout
        BuyEqTokensRestricted,
        /// One of transacted currencies is missing a price information or price
        /// is outdated
        NoPrice,
        /// The price is higher than max possible price
        BadPrice,
        /// Treasury balance is too low for the operation
        InsufficientTreasuryBalance,
        /// Account balance is too low for the operation
        InsufficientAccountBalance,
    }
}

decl_module! {
    pub struct Module<T: Trait> for enum Call where origin: T::Origin {
        type Error = Error<T>;

        // todel
        // fn deposit_event() = default;

        /// Account can buy collateral tokens from treasury paying with it's Eq.
        /// Collateral is any [`Currency`](../eq_primitives/currency/enum.Currency.html)
        /// except Eq
        #[weight = 10_000]
        pub fn colaterall_buyout(
            origin,
            currency: Currency,
            amount: T::Balance,
            max_price: FixedI64)
        {
            let who = ensure_signed(origin)?;
            Self::colaterall_buyout_inner(&who, currency, amount, max_price)?
        }
    }
}

impl<T: Trait> Module<T> {
    /// Returns module account id
    pub fn account_id() -> T::AccountId {
        T::ModuleId::get().into_account()
    }

    fn colaterall_buyout_inner(
        who: &T::AccountId,
        currency: Currency,
        amount: T::Balance,
        max_price: FixedI64,
    ) -> DispatchResult {
        eq_ensure!(
            currency != Currency::Eq,
            Error::<T>::BuyEqTokensRestricted,
            "{}:{}. Eq currency not allowed for operation. Currency: {:?}.",
            file!(),
            line!(),
            currency
        );
        // TODO is client_eq_balance needed? Remove&
        let _client_eq_balance = if let eq_balances::SignedBalance::Positive(value) =
            T::BalanceGetter::get_balance(who, &Currency::Eq)
        {
            value
        } else {
            T::Balance::zero()
        };
        let self_account_id = Self::account_id();
        let self_currency_balance = if let eq_balances::SignedBalance::Positive(value) =
            T::BalanceGetter::get_balance(&self_account_id, &currency)
        {
            value
        } else {
            T::Balance::zero()
        };

        let amount_to_sell = if self_currency_balance < amount {
            self_currency_balance
        } else {
            amount
        };

        eq_ensure!(
            amount_to_sell > T::Balance::zero(),
            Error::<T>::NothingToSell,
            "{}:{}. Amount to sell less than or equal to zero. Amount: {:?}, currency: {:?}.",
            file!(),
            line!(),
            amount_to_sell,
            currency
        );

        let currency_price = T::PriceGetter::get_price(&currency).map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::NoPrice
        })?;
        let eq_price = T::PriceGetter::get_price(&Currency::Eq).map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::NoPrice
        })?;

        let amount_to_sell_fixed = FixedI64::from_inner(Into::into(amount_to_sell) as i64);

        let fact_fixed: FixedI64 = amount_to_sell_fixed * currency_price / eq_price
            * (FixedI64::from(T::BuyFee::get()) + FixedI64::one());
        let fact: T::Balance = From::<u64>::from(fact_fixed.into_inner() as u64);

        let actual_price = fact_fixed / amount_to_sell_fixed;

        eq_ensure!(
            max_price >= actual_price,
            Error::<T>::BadPrice,
            "{}:{}. Max price is less than actual price. Currency: {:?}, max price: {:?}, 
            actual_price: {:?} = fact_fixed ({:?}) / amount_to_sell_fixed ({:?}).",
            file!(),
            line!(),
            currency,
            max_price,
            actual_price,
            fact_fixed,
            amount_to_sell_fixed
        );

        let amount_to_sell = From::<u64>::from(amount_to_sell_fixed.into_inner() as u64);
        let option_balance = self_currency_balance.checked_sub(&amount_to_sell);
        let new_balance =
            ok_or_error!(option_balance, Error::<T>::InsufficientTreasuryBalance,
        "{}:{}. Couldn't sub balance. Who: {:?}, balance: {:?}, amount: {:?}, currency: {:?}.", 
        file!(), line!(), self_account_id, self_currency_balance, amount_to_sell, currency)?;
        // this should always be false, but...
        T::EqCurrency::ensure_can_withdraw(
            currency,
            &self_account_id,
            amount_to_sell,
            WithdrawReasons::all(),
            new_balance,
        )
        .map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::InsufficientTreasuryBalance
        })?;

        T::EqCurrency::currency_transfer(
            Currency::Eq,
            who,
            &self_account_id,
            fact,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::TreasuryBuyEq,
            true,
        )
        .map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::InsufficientAccountBalance
        })?;

        T::EqCurrency::currency_transfer(
            currency,
            &self_account_id,
            who,
            amount_to_sell,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::TreasuryBuyEq,
            true,
        )
        .map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::InsufficientTreasuryBalance
        })?;

        Ok(())
    }

    /// Function for calculations: splits `value` into 2 parts: `amount` and
    /// `value` minus `amount`. If `amount` > `value` will return value and zero
    fn split(value: T::Balance, amount: T::Balance) -> (T::Balance, T::Balance) {
        let first = value.min(amount);
        let second = value - first;
        (first, second)
    }

    /// Function for calculations: splits `value` into 2 parts in given
    /// proportions of `first` and `second`
    fn ration(value: T::Balance, first: u32, second: u32) -> (T::Balance, T::Balance) {
        let total = first.saturating_add(second);
        let amount1 = value.saturating_mul(first.into()) / total.into();
        Self::split(value, amount1)
    }
}

/// Gets priority value for a currency. Priority value determines which currency
/// will be used first to withdraw fees when account has insufficient Eq
fn get_currency_priority(acurrency: Currency) -> u8 {
    match acurrency {
        Currency::Btc => 1,
        Currency::Eth => 2,
        Currency::Eos => 3,
        _ => 4,
    }
}

/// Manager for treasury Eq exchanging transactions
pub trait EqBuyout<AccountId, Balance> {
    /// Buyout `amount` of Eq from Treasury. Account `who` pays for it with it's
    /// balances accordingly to exchange priority (see `get_currency_priority`)
    fn eq_buyout(who: &AccountId, amount: Balance) -> DispatchResult;
}

impl<T: Trait> EqBuyout<T::AccountId, T::Balance> for Module<T> {
    fn eq_buyout(who: &T::AccountId, amount: T::Balance) -> DispatchResult {
        let self_account_id = Self::account_id();

        // check eq module balance and issue if not enough
        let self_eq_balance = T::BalanceGetter::get_balance(&self_account_id, &Currency::Eq);
        if let eq_balances::SignedBalance::Positive(self_eq_balance_value) = self_eq_balance {
            #[allow(unused_must_use)]
            if self_eq_balance_value < amount {
                // we need to add some EQ tokens to system for paying fee
                // deposit should not return err
                T::EqCurrency::deposit_into_existing(
                    Currency::Eq,
                    &self_account_id,
                    amount - self_eq_balance_value,
                )
                .unwrap();
            }
        } else {
            panic!("Cant be negative balance in treasury acc!");
        }

        let mut account_balances = T::BalanceGetter::iterate_account_balances(who);
        account_balances
            .sort_by(|a, b| get_currency_priority(a.0).cmp(&get_currency_priority(b.0)));
        let mut eq_price = T::PriceGetter::get_price(&Currency::Eq).map_err(|_| {
            debug::error!("{}:{}.", file!(), line!());
            Error::<T>::NoPrice
        })?;
        eq_price = eq_price * (FixedI64::from(T::SellFee::get()) + FixedI64::one());

        let mut amount_left = Into::<u64>::into(amount);

        for account_balance in account_balances {
            //skip EQ token
            if account_balance.0 == Currency::Eq {
                continue;
            }

            match account_balance.1 {
                eq_balances::SignedBalance::Positive(balance) => {
                    let currency_price =
                        T::PriceGetter::get_price(&account_balance.0).map_err(|_| {
                            debug::error!("{}:{}.", file!(), line!());
                            Error::<T>::NoPrice
                        })?;
                    let balance_in_eq_fixed =
                        FixedI64::from_inner(Into::<u64>::into(balance) as i64) * currency_price
                            / eq_price;
                    let balance_in_eq = balance_in_eq_fixed.into_inner() as u64;

                    // we just moving assets, so no aggregates changed
                    // we are using "unsafe" changes because it can lead to margincall
                    #[allow(unused_must_use)]
                    if balance_in_eq < amount_left {
                        T::EqCurrency::currency_transfer(
                            account_balance.0,
                            who,
                            &self_account_id,
                            balance,
                            ExistenceRequirement::KeepAlive,
                            eq_primitives::TransferReason::TreasuryEqBuyout,
                            false,
                        );

                        amount_left = amount_left - balance_in_eq;
                    } else {
                        let balance_to_change = balance_from_fixedi64(
                            fixedi64_from_balance(amount_left) * eq_price / currency_price,
                        )
                        .unwrap();

                        #[allow(unused_must_use)]
                        T::EqCurrency::currency_transfer(
                            account_balance.0,
                            who,
                            &self_account_id,
                            balance_to_change,
                            ExistenceRequirement::KeepAlive,
                            eq_primitives::TransferReason::TreasuryEqBuyout,
                            false,
                        );

                        break;
                    }
                }
                _ => {
                    // nothing to do with debt
                }
            }
        }

        // here amount_left may be more than 0, should we deposit event in this case?
        T::EqCurrency::currency_transfer(
            Currency::Eq,
            &self_account_id,
            who,
            amount,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::TreasuryEqBuyout,
            false,
        )
        .unwrap();

        Ok(())
    }
}

/// `FeeManager` for Treasury pallet: used to calculate and withdraw
/// Treasury fee
impl<T: Trait> FeeManager<T::AccountId, T::Balance> for Module<T> {
    fn calc_fee(owner: &T::AccountId, last_update: &u64) -> Result<T::Balance, InterestRateError> {
        let balance = T::BalanceGetter::get_balance(owner, &Currency::Usd);

        match balance {
            eq_balances::SignedBalance::Positive(_) => Ok(T::Balance::zero()),
            eq_balances::SignedBalance::Negative(_) => {
                let accuracy = FixedI128::accuracy() / FixedI64::accuracy() as i128;
                let fee = FixedI128::from(T::Fee::get());
                let (debt, _) = T::BalanceGetter::get_debt_and_colaterall(owner);
                let current_time = T::UnixTime::now().as_secs();
                let elapsed = FixedI128::saturating_from_integer(current_time - *last_update);
                let debt_amount_usd = fee * debt * elapsed
                    / FixedI128::saturating_from_integer(365 as i128 * 24 * 60 * 60);
                let price = T::PriceGetter::get_price(&Currency::Eq).map_err(|_| {
                    debug::error!("{}:{}.", file!(), line!());
                    InterestRateError::ExternalError
                })?;
                let price = FixedI128::from_inner((price.into_inner() as i128) * accuracy);
                let debt_amount = debt_amount_usd / price;

                eq_log!(
                    "Treasury fee for owner {:?}:  fee = {:?}, elapsed = {:?}, fee in usd = {:?}, fee in eq = {:?}",
                    owner,
                    fee,
                    elapsed,
                    debt_amount_usd,
                    debt_amount
                );

                Ok(From::<u64>::from(
                    (debt_amount.into_inner() / accuracy) as u64,
                ))
            }
        }
    }

    #[allow(unused_must_use)]
    fn charge_fee_inner(owner: &T::AccountId, debt_amount: &T::Balance) {
        let account = Self::account_id();
        let author = authorship::Module::<T>::author();
        let (fee_for_account, fee_for_author) = Self::ration(
            *debt_amount,
            T::WeightFeeTreasury::get(),
            T::WeightFeeValidator::get(),
        );

        T::EqCurrency::currency_transfer(
            Currency::Eq,
            owner,
            &account,
            fee_for_account,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::InterestFee,
            false,
        );

        T::EqCurrency::currency_transfer(
            Currency::Eq,
            owner,
            &author,
            fee_for_author,
            ExistenceRequirement::KeepAlive,
            eq_primitives::TransferReason::InterestFee,
            false,
        );
    }
}