Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixes SERPTreasusy conversions #442

Merged
merged 1 commit into from
Aug 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion lib-serml/serp/serp-staking/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ decl_module! {
#[weight = 0]
pub fn reward_myself(origin) -> dispatch::DispatchResult {
let reported = ensure_signed(origin)?;
<staking::Module<T>>::reward_by_ids(vec![(reported, 10)]);
<staking::<Pallet<T>>::reward_by_ids(vec![(reported, 10)]);
Ok(())
}
}
Expand Down
112 changes: 59 additions & 53 deletions lib-serml/serp/serp-treasury/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,7 @@ use frame_system::pallet_prelude::*;
use orml_traits::{GetByKey, MultiCurrency, MultiCurrencyExtended};
use primitives::{Balance, CurrencyId};
use sp_runtime::{
traits::{
AccountIdConversion, Convert,
UniqueSaturatedInto, Zero,
},
traits::{AccountIdConversion, Convert, Zero},
DispatchError, DispatchResult,
};
use sp_std::{
Expand All @@ -46,12 +43,14 @@ use support::{
DEXManager, Price, PriceProvider, Ratio, SerpTreasury, SerpTreasuryExtended
};

mod price_to_balance_convertor;
mod market_price_to_balance_convertor;
mod peg_price_to_balance_convertor;
mod mock;
mod tests;
pub mod weights;

pub use price_to_balance_convertor::PriceToBalanceConvertor;
pub use market_price_to_balance_convertor::MarketPriceToBalanceConvertor;
pub use peg_price_to_balance_convertor::PegPriceToBalanceConvertor;
pub use module::*;
Expand Down Expand Up @@ -182,10 +181,12 @@ pub mod module {
// SERP TES (Token Elasticity of Supply).
// Triggers Serping for all system stablecoins to stabilize stablecoin prices.
let mut count: u32 = 0;
Self::setter_on_tes();
count += 1;
Self::usdj_on_tes();
count += 1;
if Self::setter_on_tes().is_ok() {
count += 1;
};
if Self::usdj_on_tes().is_ok() {
count += 1;
}

T::WeightInfo::on_initialize(count)
} else {
Expand Down Expand Up @@ -217,10 +218,10 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
currency_id,
serping_amount,
None,
);
)?;

// Burn Native Reserve asset (Dinar (DNAR))
Self::burn_dinar(&Self::account_id(), serping_amount);
Self::burn_dinar(&Self::account_id(), serping_amount)?;

<Pallet<T>>::deposit_event(Event::SerpUpDelivery(amount, currency_id));
Ok(())
Expand All @@ -234,7 +235,7 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
let six: Balance = 6;
let serping_amount: Balance = six.saturating_mul(amount / 10);
// Issue the SerpUp propper to the SettPayVault
Self::issue_propper(currency_id, &settpay_account, serping_amount);
Self::issue_propper(currency_id, &settpay_account, serping_amount)?;

<Pallet<T>>::deposit_event(Event::SerpUpDelivery(amount, currency_id));
Ok(())
Expand All @@ -246,7 +247,7 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
// Charity Fund SerpUp Pool - 10%
let serping_amount: Balance = amount / 10;
// Issue the SerpUp propper to the SettPayVault
Self::issue_propper(currency_id, &charity_fund_account, serping_amount);
Self::issue_propper(currency_id, &charity_fund_account, serping_amount)?;

<Pallet<T>>::deposit_event(Event::SerpUpDelivery(amount, currency_id));
Ok(())
Expand All @@ -260,6 +261,10 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
T::PriceSource::get_market_price(currency_id).unwrap_or_else(T::DefaultPriceRate::get)
}

fn get_price_balance(currency_id: Self::CurrencyId) -> Price {
T::PriceSource::get_price(currency_id).unwrap_or_else(T::DefaultPriceRate::get)
}

fn get_peg_price_balance_value(currency_id: Self::CurrencyId, balance: Self::Balance) -> Self::Balance {
crate::PegPriceToBalanceConvertor::<T>::convert((currency_id, balance))
}
Expand All @@ -268,6 +273,10 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
crate::MarketPriceToBalanceConvertor::<T>::convert((currency_id, balance))
}

fn get_price_balance_value(currency_id: Self::CurrencyId, balance: Self::Balance) -> Self::Balance {
crate::PriceToBalanceConvertor::<T>::convert((currency_id, balance))
}

fn setter_on_tes() -> DispatchResult {
let currency_id = T::SetterCurrencyId::get();
let one: Balance = 1;
Expand Down Expand Up @@ -330,9 +339,9 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
!amount.is_zero(),
Error::<T>::InvalidAmount,
);
Self::get_buyback_serpup(amount, currency_id);
Self::get_settpay_serpup(amount, currency_id);
Self::get_charity_fund_serpup(amount, currency_id);
Self::get_buyback_serpup(amount, currency_id)?;
Self::get_settpay_serpup(amount, currency_id)?;
Self::get_charity_fund_serpup(amount, currency_id)?;

<Pallet<T>>::deposit_event(Event::SerpUp(amount, currency_id));
Ok(())
Expand Down Expand Up @@ -365,13 +374,13 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
<Self as SerpTreasuryExtended<T::AccountId>>::swap_dinar_to_exact_setter(
amount,
None,
);
)?;
} else {
<Self as SerpTreasuryExtended<T::AccountId>>::swap_setter_to_exact_settcurrency(
currency_id,
amount,
None,
);
)?;
}

<Pallet<T>>::deposit_event(Event::SerpDown(amount, currency_id));
Expand Down Expand Up @@ -444,39 +453,6 @@ impl<T: Config> SerpTreasury<T::AccountId> for Pallet<T> {
}

impl<T: Config> SerpTreasuryExtended<T::AccountId> for Pallet<T> {
/// Swap exact amount of Dinar to Setter,
/// return actual target Setter amount
fn swap_exact_dinar_to_setter(
supply_amount: Balance,
maybe_path: Option<&[CurrencyId]>,
) -> sp_std::result::Result<Balance, DispatchError> {
let dinar_currency_id = T::GetNativeCurrencyId::get();

let setter_currency_id = T::SetterCurrencyId::get();
let default_swap_path = &[dinar_currency_id, setter_currency_id];
let swap_path = match maybe_path {
None => default_swap_path,
Some(path) => {
let path_length = path.len();
ensure!(
path_length >= 2 && path[0] == dinar_currency_id && path[path_length - 1] == setter_currency_id,
Error::<T>::InvalidSwapPath
);
path
}
};
let price_impact_limit = Some(T::MaxSlippageSwapWithDEX::get());
let Some(min_target_amount) = T::Dex::get_swap_target_amount(&swap_path, supply_amount, price_impact_limit).unwrap_or_else(T::Currency::minimum_balance(setter_currency_id));
T::Currency::deposit(T::GetNativeCurrencyId::get(), &Self::account_id(), supply_amount)?;
T::Dex::swap_with_exact_supply(
&Self::account_id(),
swap_path,
supply_amount,
min_target_amount,
price_impact_limit,
)
}

/// swap Dinar to get exact Setter,
/// return actual supply Dinar amount
fn swap_dinar_to_exact_setter(
Expand All @@ -498,8 +474,18 @@ impl<T: Config> SerpTreasuryExtended<T::AccountId> for Pallet<T> {
path
}
};
let one: Balance = 1;
let price_impact_limit = Some(T::MaxSlippageSwapWithDEX::get());
let Some(max_supply_amount) = T::Dex::get_swap_supply_amount(&swap_path, target_amount, price_impact_limit);
let dinar_price_into = Self::get_price_balance_value(dinar_currency_id, one);
let setter_price_into = Self::get_price_balance_value(setter_currency_id, one);

// get a max_supply_amount of 105% of market value, marking the 5% slippage of `price_impact_limit`.
let relative_price = dinar_price_into / setter_price_into;
let max_supply_amount_full = target_amount / relative_price;
let max_supply_amount_fives = max_supply_amount_full / 20;
let max_supply_amount = max_supply_amount_fives * 21;

// let Some(max_supply_amount) = T::Dex::get_swap_supply_amount(&swap_path, target_amount, price_impact_limit);
T::Currency::deposit(dinar_currency_id, &Self::account_id(), max_supply_amount)?;
T::Dex::swap_with_exact_target(
&Self::account_id(),
Expand Down Expand Up @@ -534,8 +520,18 @@ impl<T: Config> SerpTreasuryExtended<T::AccountId> for Pallet<T> {
path
}
};
let one: Balance = 1;
let price_impact_limit = Some(T::MaxSlippageSwapWithDEX::get());
let Some(max_supply_amount) = T::Dex::get_swap_supply_amount(&swap_path, target_amount, price_impact_limit);
let setter_price_into = Self::get_price_balance_value(setter_currency_id, one);
let settcurrency_price_into = Self::get_price_balance_value(currency_id, one);

// get a max_supply_amount of 105% of market value, marking the 5% slippage of `price_impact_limit`.
let relative_price = setter_price_into / settcurrency_price_into;
let max_supply_amount_full = target_amount / relative_price;
let max_supply_amount_fives = max_supply_amount_full / 20;
let max_supply_amount = max_supply_amount_fives * 21;

// let Some(max_supply_amount) = T::Dex::get_swap_supply_amount(&swap_path, target_amount, price_impact_limit);

T::Currency::deposit(setter_currency_id, &Self::account_id(), max_supply_amount)?;
T::Dex::swap_with_exact_target(
Expand Down Expand Up @@ -572,8 +568,18 @@ impl<T: Config> SerpTreasuryExtended<T::AccountId> for Pallet<T> {
path
}
};
let one: Balance = 1;
let price_impact_limit = Some(T::MaxSlippageSwapWithDEX::get());
let Some(min_target_amount) = T::Dex::get_swap_target_amount(&swap_path, supply_amount, price_impact_limit).unwrap_or_else(T::Currency::minimum_balance(dinar_currency_id));
let stablecurrency_price_into = Self::get_price_balance_value(currency_id, one);
let dinar_price_into = Self::get_price_balance_value(dinar_currency_id, one);

// get a min_target_amount of 95% of market value, marking the 5% slippage of `price_impact_limit`.
let relative_price = dinar_price_into / stablecurrency_price_into;
let min_target_amount_full = supply_amount / relative_price;
let min_target_amount_fives = min_target_amount_full / 20;
let min_target_amount = min_target_amount_fives * 19;

// let Some(min_target_amount) = T::Dex::get_swap_target_amount(&swap_path, supply_amount, price_impact_limit);
T::Dex::swap_with_exact_supply(
&Self::account_id(),
swap_path,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

use super::*;
use primitives::{Balance, CurrencyId};
use support::Price;
use sp_runtime::traits::Convert;
use sp_runtime::FixedPointNumber;

Expand All @@ -29,6 +28,6 @@ where
T: Config,
{
fn convert((currency_id, balance): (CurrencyId, Balance)) -> Balance {
<Module<T>>::get_market_price_balance(currency_id).saturating_mul_int(balance)
<<Pallet<T>>::get_market_price_balance(currency_id).saturating_mul_int(balance)
}
}
1 change: 0 additions & 1 deletion lib-serml/serp/serp-treasury/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ use orml_traits::parameter_type_with_key;
use primitives::{Amount, ReserveIdentifier, TokenSymbol, TradingPair};
use sp_core::H256;
use sp_runtime::{
Permill,
testing::Header,
traits::{IdentityLookup, One as OneT, Zero},
DispatchError, FixedPointNumber,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

use super::*;
use primitives::{Balance, CurrencyId};
use support::Price;
use sp_runtime::traits::Convert;
use sp_runtime::FixedPointNumber;

Expand All @@ -29,6 +28,6 @@ where
T: Config,
{
fn convert((currency_id, balance): (CurrencyId, Balance)) -> Balance {
<Module<T>>::get_peg_price_balance(currency_id).saturating_mul_int(balance)
<<Pallet<T>>::get_peg_price_balance(currency_id).saturating_mul_int(balance)
}
}
33 changes: 33 additions & 0 deletions lib-serml/serp/serp-treasury/src/price_to_balance_convertor.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// This file is part of Setheum.

// Copyright (C) 2019-2021 Setheum Labs.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

use super::*;
use primitives::{Balance, CurrencyId};
use sp_runtime::traits::Convert;
use sp_runtime::FixedPointNumber;

pub struct PriceToBalanceConvertor<T>(sp_std::marker::PhantomData<T>);

impl<T> Convert<(CurrencyId, Balance), Balance> for PriceToBalanceConvertor<T>
where
T: Config,
{
fn convert((currency_id, balance): (CurrencyId, Balance)) -> Balance {
<<Pallet<T>>::get_price_balance(currency_id).saturating_mul_int(balance)
}
}
2 changes: 1 addition & 1 deletion lib-serml/settmint/settmint-engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ mod tests;

pub use module::*;

pub type SettmintManagerOf<T> = settmint_manager::Module<T>;
pub type SettmintManagerOf<T> = settmint_manager::<Pallet<T>;

// typedef to help polkadot.js disambiguate Change with different generic
// parameters
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,6 @@ where
T: Config,
{
fn convert((currency_id, balance): (CurrencyId, Balance)) -> Balance {
<Module<T>>::get_standard_exchange_rate(currency_id).saturating_mul_int(balance)
<<Pallet<T>>::get_standard_exchange_rate(currency_id).saturating_mul_int(balance)
}
}
4 changes: 2 additions & 2 deletions lib-serml/settmint/settmint-gateway/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ pub mod module {
standard_adjustment: Amount,
) -> DispatchResultWithPostInfo {
let who = ensure_signed(origin)?;
<settmint_engine::Module<T>>::adjust_position(&who, currency_id, reserve_adjustment, standard_adjustment)?;
<settmint_engine::<Pallet<T>>::adjust_position(&who, currency_id, reserve_adjustment, standard_adjustment)?;
Ok(().into())
}

Expand All @@ -150,7 +150,7 @@ pub mod module {
let to = ensure_signed(origin)?;
let from = T::Lookup::lookup(from)?;
Self::check_authorization(&from, &to, currency_id)?;
<settmint_manager::Module<T>>::transfer_reserve(&from, &to, currency_id)?;
<settmint_manager::<Pallet<T>>::transfer_reserve(&from, &to, currency_id)?;
Ok(().into())
}

Expand Down
Loading