diff --git a/Cargo.lock b/Cargo.lock index 7497ae4eda..058fddfe48 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4976,7 +4976,7 @@ dependencies = [ [[package]] name = "node-cli" -version = "0.9.8" +version = "0.9.10" dependencies = [ "cumulus-client-cli", "cumulus-client-service", @@ -11765,7 +11765,7 @@ dependencies = [ [[package]] name = "zenlink-protocol" version = "0.4.4" -source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=0a96d66fba0b8173381ff5d03a33bb7943b4f457#0a96d66fba0b8173381ff5d03a33bb7943b4f457" +source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703#f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703" dependencies = [ "cumulus-primitives-core", "frame-support", @@ -11788,7 +11788,7 @@ dependencies = [ [[package]] name = "zenlink-protocol-rpc" version = "0.4.4" -source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=0a96d66fba0b8173381ff5d03a33bb7943b4f457#0a96d66fba0b8173381ff5d03a33bb7943b4f457" +source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703#f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703" dependencies = [ "jsonrpc-core", "jsonrpc-core-client", @@ -11805,7 +11805,7 @@ dependencies = [ [[package]] name = "zenlink-protocol-runtime-api" version = "0.4.4" -source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=0a96d66fba0b8173381ff5d03a33bb7943b4f457#0a96d66fba0b8173381ff5d03a33bb7943b4f457" +source = "git+https://github.com/zenlinkpro/Zenlink-DEX-Module?rev=f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703#f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703" dependencies = [ "parity-scale-codec", "sp-api", diff --git a/Cargo.toml b/Cargo.toml index 002a406e2c..277e0a56f2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -193,9 +193,9 @@ substrate-frame-rpc-system = { git = "https://github.com/paritytech/substrate", substrate-prometheus-endpoint = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.12" } substrate-wasm-builder = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.12" } -zenlink-protocol = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "0a96d66fba0b8173381ff5d03a33bb7943b4f457"} -zenlink-protocol-rpc = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "0a96d66fba0b8173381ff5d03a33bb7943b4f457" } -zenlink-protocol-runtime-api = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "0a96d66fba0b8173381ff5d03a33bb7943b4f457" } +zenlink-protocol = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703"} +zenlink-protocol-rpc = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703" } +zenlink-protocol-runtime-api = { git = "https://github.com/zenlinkpro/Zenlink-DEX-Module", rev = "f6ca2a8e0babb19e1a6e9309ce3e9b5b53f7a703" } orml-traits = { git = "https://github.com/open-web3-stack/open-runtime-module-library", rev = "5ba42f532b72d71a28aaa18421855de003b9ca71" } orml-currencies = {git = "https://github.com/open-web3-stack/open-runtime-module-library", rev = "5ba42f532b72d71a28aaa18421855de003b9ca71" } diff --git a/node/cli/Cargo.toml b/node/cli/Cargo.toml index ee85ec4751..74dbdbd964 100644 --- a/node/cli/Cargo.toml +++ b/node/cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "node-cli" -version = "0.9.8" +version = "0.9.10" authors = ["Liebi Technologies "] description = "Bifrost Parachain Node" build = "build.rs" diff --git a/pallets/flexible-fee/src/lib.rs b/pallets/flexible-fee/src/lib.rs index 3954c27106..32d27a7beb 100644 --- a/pallets/flexible-fee/src/lib.rs +++ b/pallets/flexible-fee/src/lib.rs @@ -286,9 +286,6 @@ where // Calculate how much refund we should return let refund_amount = paid.peek().saturating_sub(corrected_fee); - #[cfg(feature = "std")] - println!("refund_amount: {:?}", refund_amount); - // refund to the the account that paid the fees. If this fails, the // account might have dropped below the existential balance. In // that case we don't refund anything. diff --git a/pallets/liquidity-mining/rpc/runtime-api/src/lib.rs b/pallets/liquidity-mining/rpc/runtime-api/src/lib.rs index 80ec625f9e..63058cd547 100644 --- a/pallets/liquidity-mining/rpc/runtime-api/src/lib.rs +++ b/pallets/liquidity-mining/rpc/runtime-api/src/lib.rs @@ -31,6 +31,7 @@ decl_runtime_apis! { fn get_rewards( who: AccountId, pid: PoolId, + pallet_instance: u32, ) -> Vec<(CurrencyId, Balance)>; } } diff --git a/pallets/liquidity-mining/rpc/src/lib.rs b/pallets/liquidity-mining/rpc/src/lib.rs index 4767c59cf3..630dbaf097 100644 --- a/pallets/liquidity-mining/rpc/src/lib.rs +++ b/pallets/liquidity-mining/rpc/src/lib.rs @@ -38,6 +38,7 @@ pub trait LiquidityMiningRpcApi { &self, who: AccountId, pid: PoolId, + pallet_instance: u32, at: Option, ) -> JsonRpcResult>; } @@ -67,12 +68,14 @@ where &self, who: AccountId, pid: PoolId, + pallet_instance: u32, at: Option<::Hash>, ) -> JsonRpcResult> { let lm_rpc_api = self.client.runtime_api(); let at = BlockId::::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - let rs: Result, _> = lm_rpc_api.get_rewards(&at, who, pid); + let rs: Result, _> = + lm_rpc_api.get_rewards(&at, who, pid, pallet_instance); match rs { Ok(rewards) => Ok(rewards diff --git a/pallets/liquidity-mining/src/lib.rs b/pallets/liquidity-mining/src/lib.rs index 2da0af8695..9f7f390d8c 100644 --- a/pallets/liquidity-mining/src/lib.rs +++ b/pallets/liquidity-mining/src/lib.rs @@ -22,7 +22,9 @@ use frame_support::{ pallet_prelude::*, sp_runtime::{ - traits::{AccountIdConversion, SaturatedConversion, Saturating, Zero}, + traits::{ + AccountIdConversion, AtLeast32BitUnsigned, SaturatedConversion, Saturating, Zero, + }, FixedPointNumber, FixedU128, }, sp_std::{ @@ -51,17 +53,22 @@ pub mod weights; pub use weights::*; #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] -pub struct PoolInfo { +pub struct PoolInfo +where + AccountIdOf: Clone, + BalanceOf: AtLeast32BitUnsigned + Copy, + BlockNumberOf: AtLeast32BitUnsigned + Copy, +{ /// Id of the liquidity-pool pool_id: PoolId, /// The keeper of the liquidity-pool - keeper: AccountIdOf, + keeper: AccountIdOf, /// The man who charges the rewards to the pool - investor: Option>, + investor: Option, /// The trading-pair supported by the liquidity-pool trading_pair: (CurrencyId, CurrencyId), /// The length of time the liquidity-pool releases rewards - duration: BlockNumberFor, + duration: BlockNumberOf, /// The liquidity-pool type r#type: PoolType, @@ -69,30 +76,38 @@ pub struct PoolInfo { /// /// When starts the liquidity-pool, the amount deposited in the liquidity-pool /// should be greater than the value. - min_deposit_to_start: BalanceOf, + min_deposit_to_start: BalanceOf, /// The Second Condition /// /// When starts the liquidity-pool, the current block should be greater than the value. - after_block_to_start: BlockNumberFor, + after_block_to_start: BlockNumberOf, /// The total amount deposited in the liquidity-pool - deposit: BalanceOf, + deposit: BalanceOf, /// The reward infos about the liquidity-pool - rewards: BTreeMap>, + rewards: BTreeMap>, /// The block of the last update of the rewards - update_b: BlockNumberFor, + update_b: BlockNumberOf, /// The liquidity-pool state state: PoolState, /// The block number when the liquidity-pool startup - block_startup: Option>, + block_startup: Option, /// The block number when the liquidity-pool retired - block_retired: Option>, + block_retired: Option, } -impl PoolInfo { +impl PoolInfo +where + AccountIdOf: Clone, + BalanceOf: AtLeast32BitUnsigned + Copy, + BlockNumberOf: AtLeast32BitUnsigned + Copy, +{ /// Trying to update the rewards - pub(crate) fn try_update(mut self) -> Self { + pub(crate) fn try_update, I: 'static>(mut self) -> Self + where + T: frame_system::Config, + { // When pool in `PoolState::Ongoing` or `PoolState::Retired` if let Some(block_startup) = self.block_startup { let block_retired = match self.block_retired { @@ -114,13 +129,13 @@ impl PoolInfo { /// Trying to change the state from `PoolState::Charged` to `PoolState::Ongoing` /// /// __NOTE__: Only called in the `Hook` - pub(crate) fn try_startup(mut self, n: BlockNumberFor) -> Self { + pub(crate) fn try_startup, I: 'static>(mut self, n: BlockNumberOf) -> Self { if self.state == PoolState::Charged { if n >= self.after_block_to_start && self.deposit >= self.min_deposit_to_start { self.block_startup = Some(n); self.state = PoolState::Ongoing; - Pallet::::deposit_event(Event::PoolStarted( + Pallet::::deposit_event(Event::PoolStarted( self.pool_id, self.r#type, self.trading_pair, @@ -132,7 +147,10 @@ impl PoolInfo { } /// Trying to change the state from `PoolState::Ongoing` to `PoolState::Retired` - pub(crate) fn try_retire(mut self) -> Self { + pub(crate) fn try_retire, I: 'static>(mut self) -> Self + where + T: frame_system::Config, + { if self.state == PoolState::Ongoing { let n = frame_system::Pallet::::block_number(); @@ -149,12 +167,16 @@ impl PoolInfo { } /// Trying account & transfer the rewards to user - pub(crate) fn try_settle_and_transfer( + pub(crate) fn try_settle_and_transfer, I: 'static>( &mut self, - deposit_data: &mut DepositData, - user: AccountIdOf, - ) -> Result<(), DispatchError> { - let mut to_rewards = Vec::<(CurrencyId, BalanceOf)>::new(); + deposit_data: &mut DepositData, + user: AccountIdOf, + ) -> Result<(), DispatchError> + where + T: frame_system::Config, + T::MultiCurrency: MultiCurrency, + { + let mut to_rewards = Vec::<(CurrencyId, BalanceOf)>::new(); // The pool was startup before. if let Some(_block_startup) = self.block_startup { @@ -164,7 +186,7 @@ impl PoolInfo { let v_old = *gain_avg; let user_deposit: u128 = deposit_data.deposit.saturated_into(); - let amount = BalanceOf::::saturated_from( + let amount = BalanceOf::saturated_from( v_new.saturating_sub(v_old).saturating_mul_int(user_deposit), ); @@ -193,7 +215,7 @@ impl PoolInfo { T::MultiCurrency::transfer(*rtoken, &self.keeper, &user, *amount)?; } - Pallet::::deposit_event(Event::UserClaimed( + Pallet::::deposit_event(Event::UserClaimed( self.pool_id, self.r#type, self.trading_pair, @@ -205,8 +227,11 @@ impl PoolInfo { } /// Try to return back the remain of reward from keeper to investor - pub(crate) fn try_withdraw_remain(&self) -> DispatchResult { - let investor = self.investor.clone().ok_or(Error::::Unexpected)?; + pub(crate) fn try_withdraw_remain, I: 'static>(&self) -> DispatchResult + where + T::MultiCurrency: MultiCurrency, + { + let investor = self.investor.clone().ok_or(Error::::Unexpected)?; for (rtoken, reward) in self.rewards.iter() { let remain = reward.total.saturating_sub(reward.claimed); @@ -246,20 +271,30 @@ pub enum PoolState { } #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] -pub struct DepositData { +pub struct DepositData +where + BalanceOf: AtLeast32BitUnsigned + Copy, + BlockNumberOf: AtLeast32BitUnsigned + Copy, +{ /// The amount of trading-pair deposited in the liquidity-pool - deposit: BalanceOf, + deposit: BalanceOf, /// The average gain in pico by 1 pico deposited from the startup of the liquidity-pool, /// updated when the `DepositData`'s owner deposits/redeems/claims from the liquidity-pool. /// /// - Arg0: The average gain in pico by 1 pico deposited from the startup of the liquidity-pool /// - Arg1: The block number updated lastest gain_avgs: BTreeMap, - update_b: BlockNumberFor, + update_b: BlockNumberOf, } -impl DepositData { - pub(crate) fn from_pool(pool: &PoolInfo) -> Self { +impl DepositData +where + BalanceOf: AtLeast32BitUnsigned + Copy, + BlockNumberOf: AtLeast32BitUnsigned + Copy, +{ + pub(crate) fn from_pool( + pool: &PoolInfo, + ) -> Self { let mut gain_avgs = BTreeMap::::new(); for (rtoken, reward) in pool.rewards.iter() { @@ -271,21 +306,34 @@ impl DepositData { } #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] -pub struct RewardData { +pub struct RewardData +where + BalanceOf: AtLeast32BitUnsigned + Copy, +{ /// The total amount of token to reward - total: BalanceOf, + total: BalanceOf, /// The amount of token to reward per block - per_block: BalanceOf, + per_block: BalanceOf, /// The amount of token was already rewarded - claimed: BalanceOf, + claimed: BalanceOf, /// The average gain in pico by 1 pico deposited from the startup of the liquidity-pool, /// updated when anyone deposits to / redeems from / claims from the liquidity-pool. gain_avg: FixedU128, } -impl RewardData { - fn new(total: BalanceOf, duration: BlockNumberFor) -> Result { +impl RewardData +where + BalanceOf: AtLeast32BitUnsigned + Copy, +{ + fn new, I: 'static, BlockNumberOf>( + total: BalanceOf, + duration: BlockNumberOf, + ) -> Result + where + BlockNumberOf: AtLeast32BitUnsigned + Copy, + T::MinimumRewardPerBlock: Get, + { let total: u128 = total.saturated_into(); let (per_block, total) = { let duration: u128 = duration.saturated_into(); @@ -293,15 +341,15 @@ impl RewardData { let per_block = total / duration; let total = per_block.saturating_mul(duration); - (BalanceOf::::saturated_from(per_block), BalanceOf::::saturated_from(total)) + (BalanceOf::saturated_from(per_block), BalanceOf::saturated_from(total)) }; - ensure!(per_block > T::MinimumRewardPerBlock::get(), Error::::InvalidRewardPerBlock); + ensure!(per_block > T::MinimumRewardPerBlock::get(), Error::::InvalidRewardPerBlock); Ok(RewardData { total, per_block, claimed: Zero::zero(), gain_avg: 0.into() }) } - pub(crate) fn per_block_per_deposited(&self, deposited: BalanceOf) -> FixedU128 { + pub(crate) fn per_block_per_deposited(&self, deposited: BalanceOf) -> FixedU128 { let per_block: u128 = self.per_block.saturated_into(); let deposit: u128 = deposited.saturated_into(); @@ -312,13 +360,15 @@ impl RewardData { } /// Trying to update the gain_avg - pub(crate) fn update( + pub(crate) fn update( &mut self, - deposit: BalanceOf, - block_startup: BlockNumberFor, - block_last_updated: BlockNumberFor, - n: BlockNumberFor, - ) { + deposit: BalanceOf, + block_startup: BlockNumberOf, + block_last_updated: BlockNumberOf, + n: BlockNumberOf, + ) where + BlockNumberOf: AtLeast32BitUnsigned + Copy, + { let pbpd = self.per_block_per_deposited(deposit); let b_prev = max(block_last_updated, block_startup); @@ -330,13 +380,16 @@ impl RewardData { } } -impl core::fmt::Debug for RewardData { +impl core::fmt::Debug for RewardData +where + BalanceOf: AtLeast32BitUnsigned + Copy, +{ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("") - .field(&self.total) - .field(&self.per_block) - .field(&self.claimed) - .field(&self.gain_avg) + // .field(&self.total) + // .field(&self.per_block) + // .field(&self.claimed) + // .field(&self.gain_avg) .finish() } } @@ -345,8 +398,8 @@ impl core::fmt::Debug for RewardData { type AccountIdOf = ::AccountId; #[allow(type_alias_bounds)] -type BalanceOf = - <::MultiCurrency as MultiCurrency>>::Balance; +type BalanceOf, I: 'static = ()> = + <>::MultiCurrency as MultiCurrency>>::Balance; type PoolId = u32; @@ -355,8 +408,8 @@ pub mod pallet { use super::*; #[pallet::config] - pub trait Config: frame_system::Config + TypeInfo { - type Event: From> + IsType<::Event>; + pub trait Config: frame_system::Config { + type Event: From> + IsType<::Event>; /// Origin for anyone able to create/kill/force_retire the liquidity-pool. type ControlOrigin: EnsureOrigin; @@ -371,15 +424,15 @@ pub mod pallet { /// The deposit of a liquidity-pool should be less than the value #[pallet::constant] - type MaximumDepositInPool: Get>; + type MaximumDepositInPool: Get>; /// The amount which be deposited to a liquidity-pool should be greater than the value #[pallet::constant] - type MinimumDepositOfUser: Get>; + type MinimumDepositOfUser: Get>; /// The amount of reward which will be released per block should be greater than the value #[pallet::constant] - type MinimumRewardPerBlock: Get>; + type MinimumRewardPerBlock: Get>; /// The duration of a liquidity-pool should be greater than the value #[pallet::constant] @@ -401,7 +454,7 @@ pub mod pallet { } #[pallet::error] - pub enum Error { + pub enum Error { InvalidTradingPair, InvalidDuration, InvalidRewardPerBlock, @@ -435,7 +488,7 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub (crate) fn deposit_event)] - pub enum Event { + pub enum Event, I: 'static = ()> { /// The liquidity-pool was created /// /// [pool_id, pool_type, trading_pair, keeper] @@ -459,11 +512,11 @@ pub mod pallet { /// User deposited tokens to a liquidity-pool /// /// [pool_id, pool_type, trading_pair, amount_deposited, user] - UserDeposited(PoolId, PoolType, (CurrencyId, CurrencyId), BalanceOf, AccountIdOf), + UserDeposited(PoolId, PoolType, (CurrencyId, CurrencyId), BalanceOf, AccountIdOf), /// User redeemed tokens from a liquidity-mining /// /// [pool_id, pool_type, trading_pair, amount_redeemed, user] - UserRedeemed(PoolId, PoolType, (CurrencyId, CurrencyId), BalanceOf, AccountIdOf), + UserRedeemed(PoolId, PoolType, (CurrencyId, CurrencyId), BalanceOf, AccountIdOf), /// User withdrew the rewards whose deserved from a liquidity-pool /// /// [pool_id, pool_type, trading_pair, rewards, user] @@ -471,14 +524,14 @@ pub mod pallet { PoolId, PoolType, (CurrencyId, CurrencyId), - Vec<(CurrencyId, BalanceOf)>, + Vec<(CurrencyId, BalanceOf)>, AccountIdOf, ), } #[pallet::storage] #[pallet::getter(fn pool_id)] - pub(crate) type NextPoolId = StorageValue<_, PoolId, ValueQuery>; + pub(crate) type NextPoolId, I: 'static = ()> = StorageValue<_, PoolId, ValueQuery>; /// The storage is used to store pool-ids which point to the Pools at `PoolState::Charged`. /// @@ -487,28 +540,34 @@ pub mod pallet { /// after the conditions that are set at the pool-creation stage are met. #[pallet::storage] #[pallet::getter(fn charged_pids)] - pub(crate) type ChargedPoolIds = StorageValue<_, BTreeSet, ValueQuery>; + pub(crate) type ChargedPoolIds, I: 'static = ()> = + StorageValue<_, BTreeSet, ValueQuery>; #[pallet::storage] #[pallet::getter(fn pool)] - pub(crate) type TotalPoolInfos = StorageMap<_, Twox64Concat, PoolId, PoolInfo>; + pub(crate) type TotalPoolInfos, I: 'static = ()> = StorageMap< + _, + Twox64Concat, + PoolId, + PoolInfo, BalanceOf, BlockNumberFor>, + >; #[pallet::storage] #[pallet::getter(fn user_deposit_data)] - pub(crate) type TotalDepositData = StorageDoubleMap< + pub(crate) type TotalDepositData, I: 'static = ()> = StorageDoubleMap< _, Blake2_128Concat, PoolId, Blake2_128Concat, AccountIdOf, - DepositData, + DepositData, BlockNumberFor>, >; #[pallet::pallet] - pub struct Pallet(PhantomData); + pub struct Pallet(PhantomData<(T, I)>); #[pallet::call] - impl Pallet { + impl, I: 'static> Pallet { /// Create a liquidity-pool which type is `PoolType::Mining`, Only accepts `lpToken` as /// deposit. #[pallet::weight(( @@ -519,10 +578,10 @@ pub mod pallet { pub fn create_mining_pool( origin: OriginFor, trading_pair: (CurrencyId, CurrencyId), - main_reward: (CurrencyId, BalanceOf), - option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, + main_reward: (CurrencyId, BalanceOf), + option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, #[pallet::compact] duration: BlockNumberFor, - #[pallet::compact] min_deposit_to_start: BalanceOf, + #[pallet::compact] min_deposit_to_start: BalanceOf, #[pallet::compact] after_block_to_start: BlockNumberFor, ) -> DispatchResultWithPostInfo { let _ = T::ControlOrigin::ensure_origin(origin)?; @@ -530,8 +589,8 @@ pub mod pallet { // Order the trading_pair let (token1, token2) = trading_pair; - ensure!(!token1.is_vsbond() && !token1.is_lptoken(), Error::::InvalidTradingPair); - ensure!(!token2.is_vsbond() && !token2.is_lptoken(), Error::::InvalidTradingPair); + ensure!(!token1.is_vsbond() && !token1.is_lptoken(), Error::::InvalidTradingPair); + ensure!(!token2.is_vsbond() && !token2.is_lptoken(), Error::::InvalidTradingPair); let (id1, id2) = (token1.currency_id(), token2.currency_id()); let trading_pair = if id1 <= id2 { (token1, token2) } else { (token2, token1) }; @@ -559,10 +618,10 @@ pub mod pallet { index: ParaId, first_slot: LeasePeriod, last_slot: LeasePeriod, - main_reward: (CurrencyId, BalanceOf), - option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, + main_reward: (CurrencyId, BalanceOf), + option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, #[pallet::compact] duration: BlockNumberFor, - #[pallet::compact] min_deposit_to_start: BalanceOf, + #[pallet::compact] min_deposit_to_start: BalanceOf, #[pallet::compact] after_block_to_start: BlockNumberFor, ) -> DispatchResultWithPostInfo { let _ = T::ControlOrigin::ensure_origin(origin)?; @@ -594,10 +653,10 @@ pub mod pallet { index: ParaId, first_slot: LeasePeriod, last_slot: LeasePeriod, - main_reward: (CurrencyId, BalanceOf), - option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, + main_reward: (CurrencyId, BalanceOf), + option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, #[pallet::compact] duration: BlockNumberFor, - #[pallet::compact] min_deposit_to_start: BalanceOf, + #[pallet::compact] min_deposit_to_start: BalanceOf, #[pallet::compact] after_block_to_start: BlockNumberFor, ) -> DispatchResultWithPostInfo { let _ = T::ControlOrigin::ensure_origin(origin)?; @@ -627,12 +686,12 @@ pub mod pallet { let investor = ensure_signed(origin)?; let num = Self::charged_pids().len() as u32; - ensure!(num < T::MaximumCharged::get(), Error::::ExceedMaximumCharged); + ensure!(num < T::MaximumCharged::get(), Error::::ExceedMaximumCharged); - let pool: PoolInfo = Self::pool(pid).ok_or(Error::::InvalidPoolId)?; + let pool = Self::pool(pid).ok_or(Error::::InvalidPoolId)?; - ensure!(pool.state == PoolState::UnCharged, Error::::InvalidPoolState); - ensure!(pool.investor.is_none(), Error::::PoolChargedAlready); + ensure!(pool.state == PoolState::UnCharged, Error::::InvalidPoolState); + ensure!(pool.investor.is_none(), Error::::PoolChargedAlready); for (token, reward) in pool.rewards.iter() { T::MultiCurrency::ensure_can_withdraw(*token, &investor, reward.total)?; @@ -642,14 +701,14 @@ pub mod pallet { T::MultiCurrency::transfer(*token, &investor, &pool.keeper, reward.total)?; } - ChargedPoolIds::::mutate(|pids| pids.insert(pid)); + ChargedPoolIds::::mutate(|pids| pids.insert(pid)); let r#type = pool.r#type; let trading_pair = pool.trading_pair; let pool_charged = PoolInfo { state: PoolState::Charged, investor: Some(investor.clone()), ..pool }; - TotalPoolInfos::::insert(pid, pool_charged); + TotalPoolInfos::::insert(pid, pool_charged); Self::deposit_event(Event::PoolCharged(pid, r#type, trading_pair, investor)); @@ -665,12 +724,12 @@ pub mod pallet { pub fn kill_pool(origin: OriginFor, pid: PoolId) -> DispatchResultWithPostInfo { let _ = T::ControlOrigin::ensure_origin(origin)?; - let pool: PoolInfo = Self::pool(pid).ok_or(Error::::InvalidPoolId)?; + let pool = Self::pool(pid).ok_or(Error::::InvalidPoolId)?; - ensure!(pool.state == PoolState::UnCharged, Error::::InvalidPoolState); + ensure!(pool.state == PoolState::UnCharged, Error::::InvalidPoolState); let pool_killed = PoolInfo { state: PoolState::Dead, ..pool }; - TotalPoolInfos::::remove(pid); + TotalPoolInfos::::remove(pid); Self::deposit_event(Event::PoolKilled( pid, @@ -697,24 +756,24 @@ pub mod pallet { pub fn force_retire_pool(origin: OriginFor, pid: PoolId) -> DispatchResultWithPostInfo { let _ = T::ControlOrigin::ensure_origin(origin)?; - let pool: PoolInfo = Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire(); + let pool = Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire::(); ensure!( pool.state == PoolState::Charged || pool.state == PoolState::Ongoing, - Error::::InvalidPoolState + Error::::InvalidPoolState ); let r#type = pool.r#type; let trading_pair = pool.trading_pair; if pool.state == PoolState::Charged { - ChargedPoolIds::::mutate(|pids| pids.remove(&pid)); + ChargedPoolIds::::mutate(|pids| pids.remove(&pid)); } match pool.state { PoolState::Charged if pool.deposit == Zero::zero() => { - pool.try_withdraw_remain()?; - TotalPoolInfos::::remove(pid); + pool.try_withdraw_remain::()?; + TotalPoolInfos::::remove(pid); }, PoolState::Charged | PoolState::Ongoing => { let pool_retired = PoolInfo { @@ -722,7 +781,7 @@ pub mod pallet { block_retired: Some(frame_system::Pallet::::block_number()), ..pool }; - TotalPoolInfos::::insert(pid, pool_retired); + TotalPoolInfos::::insert(pid, pool_retired); }, _ => {}, } @@ -745,32 +804,34 @@ pub mod pallet { pub fn deposit( origin: OriginFor, pid: PoolId, - value: BalanceOf, + value: BalanceOf, ) -> DispatchResultWithPostInfo { let user = ensure_signed(origin)?; - let mut pool: PoolInfo = - Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire().try_update(); + let mut pool = Self::pool(pid) + .ok_or(Error::::InvalidPoolId)? + .try_retire::() + .try_update::(); ensure!( pool.state == PoolState::Charged || pool.state == PoolState::Ongoing, - Error::::InvalidPoolState + Error::::InvalidPoolState ); - ensure!(value >= T::MinimumDepositOfUser::get(), Error::::TooLowToDeposit); + ensure!(value >= T::MinimumDepositOfUser::get(), Error::::TooLowToDeposit); - let mut deposit_data: DepositData = Self::user_deposit_data(pid, user.clone()) - .unwrap_or(DepositData::::from_pool(&pool)); + let mut deposit_data = Self::user_deposit_data(pid, user.clone()) + .unwrap_or(DepositData::, BlockNumberFor>::from_pool(&pool)); if pool.state == PoolState::Ongoing && pool.update_b != deposit_data.update_b { - pool.try_settle_and_transfer(&mut deposit_data, user.clone())?; + pool.try_settle_and_transfer::(&mut deposit_data, user.clone())?; } deposit_data.deposit = deposit_data.deposit.saturating_add(value); pool.deposit = pool.deposit.saturating_add(value); ensure!( pool.deposit <= T::MaximumDepositInPool::get(), - Error::::ExceedMaximumDeposit + Error::::ExceedMaximumDeposit ); // To "lock" the deposit @@ -779,26 +840,26 @@ pub mod pallet { let lpt = Self::convert_to_lptoken(pool.trading_pair)?; T::MultiCurrency::transfer(lpt, &user, &pool.keeper, value) - .map_err(|_e| Error::::NotEnoughToDeposit)?; + .map_err(|_e| Error::::NotEnoughToDeposit)?; }, PoolType::Farming => { let (token_a, token_b) = pool.trading_pair; T::MultiCurrency::transfer(token_a, &user, &pool.keeper, value) - .map_err(|_e| Error::::NotEnoughToDeposit)?; + .map_err(|_e| Error::::NotEnoughToDeposit)?; T::MultiCurrency::transfer(token_b, &user, &pool.keeper, value) - .map_err(|_e| Error::::NotEnoughToDeposit)?; + .map_err(|_e| Error::::NotEnoughToDeposit)?; }, PoolType::EBFarming => { let (token_a, token_b) = pool.trading_pair; ensure!( T::MultiCurrency::reserved_balance(token_a, &user) >= deposit_data.deposit, - Error::::NotEnoughToDeposit + Error::::NotEnoughToDeposit ); ensure!( T::MultiCurrency::reserved_balance(token_b, &user) >= deposit_data.deposit, - Error::::NotEnoughToDeposit + Error::::NotEnoughToDeposit ); }, } @@ -806,8 +867,8 @@ pub mod pallet { let r#type = pool.r#type; let trading_pair = pool.trading_pair; - TotalPoolInfos::::insert(pid, pool); - TotalDepositData::::insert(pid, user.clone(), deposit_data); + TotalPoolInfos::::insert(pid, pool); + TotalDepositData::::insert(pid, user.clone(), deposit_data); Self::deposit_event(Event::UserDeposited(pid, r#type, trading_pair, value, user)); @@ -838,7 +899,7 @@ pub mod pallet { pub fn redeem( origin: OriginFor, pid: PoolId, - value: BalanceOf, + value: BalanceOf, ) -> DispatchResultWithPostInfo { if value == Zero::zero() { return Ok(().into()); @@ -891,16 +952,16 @@ pub mod pallet { pid: PoolId, account: Option>, ) -> DispatchResultWithPostInfo { - let pool: PoolInfo = Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire(); + let pool = Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire::(); - ensure!(pool.state == PoolState::Retired, Error::::InvalidPoolState); + ensure!(pool.state == PoolState::Retired, Error::::InvalidPoolState); let user = match account { Some(account) => account, None => { - let (account, _) = TotalDepositData::::iter_prefix(pid) + let (account, _) = TotalDepositData::::iter_prefix(pid) .next() - .ok_or(Error::::NoDepositOfUser)?; + .ok_or(Error::::NoDepositOfUser)?; account }, @@ -921,58 +982,60 @@ pub mod pallet { pub fn claim(origin: OriginFor, pid: PoolId) -> DispatchResultWithPostInfo { let user = ensure_signed(origin)?; - let mut pool: PoolInfo = - Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire().try_update(); + let mut pool = Self::pool(pid) + .ok_or(Error::::InvalidPoolId)? + .try_retire::() + .try_update::(); - ensure!(pool.state == PoolState::Ongoing, Error::::InvalidPoolState); + ensure!(pool.state == PoolState::Ongoing, Error::::InvalidPoolState); - let mut deposit_data: DepositData = - Self::user_deposit_data(pid, user.clone()).ok_or(Error::::NoDepositOfUser)?; + let mut deposit_data = + Self::user_deposit_data(pid, user.clone()).ok_or(Error::::NoDepositOfUser)?; - ensure!(pool.update_b != deposit_data.update_b, Error::::TooShortBetweenTwoClaim); - pool.try_settle_and_transfer(&mut deposit_data, user.clone())?; + ensure!(pool.update_b != deposit_data.update_b, Error::::TooShortBetweenTwoClaim); + pool.try_settle_and_transfer::(&mut deposit_data, user.clone())?; - TotalPoolInfos::::insert(pid, pool); - TotalDepositData::::insert(pid, user, deposit_data); + TotalPoolInfos::::insert(pid, pool); + TotalDepositData::::insert(pid, user, deposit_data); Ok(().into()) } } - impl Pallet { + impl, I: 'static> Pallet { pub(crate) fn create_pool( trading_pair: (CurrencyId, CurrencyId), - main_reward: (CurrencyId, BalanceOf), - option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, + main_reward: (CurrencyId, BalanceOf), + option_rewards: BoundedVec<(CurrencyId, BalanceOf), T::MaximumOptionRewards>, r#type: PoolType, duration: BlockNumberFor, - min_deposit_to_start: BalanceOf, + min_deposit_to_start: BalanceOf, after_block_to_start: BlockNumberFor, ) -> DispatchResultWithPostInfo { // Check the trading-pair - ensure!(trading_pair.0 != trading_pair.1, Error::::InvalidTradingPair); + ensure!(trading_pair.0 != trading_pair.1, Error::::InvalidTradingPair); // Check the duration - ensure!(duration > T::MinimumDuration::get(), Error::::InvalidDuration); + ensure!(duration > T::MinimumDuration::get(), Error::::InvalidDuration); // Check the condition ensure!( min_deposit_to_start >= T::MinimumDepositOfUser::get(), - Error::::InvalidDepositLimit + Error::::InvalidDepositLimit ); ensure!( min_deposit_to_start <= T::MaximumDepositInPool::get(), - Error::::InvalidDepositLimit + Error::::InvalidDepositLimit ); // Check & Construct the rewards - let raw_rewards: Vec<(CurrencyId, BalanceOf)> = + let raw_rewards: Vec<(CurrencyId, BalanceOf)> = option_rewards.into_iter().chain(Some(main_reward).into_iter()).collect(); - let mut rewards: BTreeMap> = BTreeMap::new(); + let mut rewards: BTreeMap>> = BTreeMap::new(); for (token, total) in raw_rewards.into_iter() { - ensure!(!rewards.contains_key(&token), Error::::DuplicateReward); + ensure!(!rewards.contains_key(&token), Error::::DuplicateReward); - let reward = RewardData::new(total, duration)?; + let reward = RewardData::new::>(total, duration)?; rewards.insert(token, reward); } @@ -1000,7 +1063,7 @@ pub mod pallet { block_retired: None, }; - TotalPoolInfos::::insert(pool_id, mining_pool); + TotalPoolInfos::::insert(pool_id, mining_pool); Self::deposit_event(Event::PoolCreated(pool_id, r#type, trading_pair, keeper)); @@ -1010,28 +1073,30 @@ pub mod pallet { pub(crate) fn redeem_inner( user: AccountIdOf, pid: PoolId, - value: Option>, + value: Option>, ) -> DispatchResultWithPostInfo { - let mut pool: PoolInfo = - Self::pool(pid).ok_or(Error::::InvalidPoolId)?.try_retire().try_update(); + let mut pool = Self::pool(pid) + .ok_or(Error::::InvalidPoolId)? + .try_retire::() + .try_update::(); ensure!( pool.state == PoolState::Ongoing || pool.state == PoolState::Retired, - Error::::InvalidPoolState + Error::::InvalidPoolState ); - let mut deposit_data: DepositData = - Self::user_deposit_data(pid, user.clone()).ok_or(Error::::NoDepositOfUser)?; + let mut deposit_data = + Self::user_deposit_data(pid, user.clone()).ok_or(Error::::NoDepositOfUser)?; if pool.update_b != deposit_data.update_b { - pool.try_settle_and_transfer(&mut deposit_data, user.clone())?; + pool.try_settle_and_transfer::(&mut deposit_data, user.clone())?; } // Keep minimum deposit in pool when the pool is ongoing. let minimum_in_pool = match pool.state { PoolState::Ongoing => T::MinimumDepositOfUser::get(), PoolState::Retired => Zero::zero(), - _ => return Err(Error::::Unexpected.into()), + _ => return Err(Error::::Unexpected.into()), }; let pool_can_redeem = pool.deposit.saturating_sub(minimum_in_pool); @@ -1041,12 +1106,12 @@ pub mod pallet { Some(value) if pool.state == PoolState::Ongoing => value, Some(_) if pool.state == PoolState::Retired => user_can_redeem, None => user_can_redeem, - _ => return Err(Error::::Unexpected.into()), + _ => return Err(Error::::Unexpected.into()), }; ensure!( user_can_redeem >= try_redeem && user_can_redeem != Zero::zero(), - Error::::TooLowToRedeem + Error::::TooLowToRedeem ); pool.deposit = pool.deposit.saturating_sub(try_redeem); @@ -1057,21 +1122,21 @@ pub mod pallet { PoolType::Mining => { let lpt = Self::convert_to_lptoken(pool.trading_pair)?; T::MultiCurrency::transfer(lpt, &pool.keeper, &user, try_redeem) - .map_err(|_e| Error::::NotEnoughToRedeem)?; + .map_err(|_e| Error::::NotEnoughToRedeem)?; }, PoolType::Farming => { let (token_a, token_b) = pool.trading_pair; T::MultiCurrency::transfer(token_a, &pool.keeper, &user, try_redeem) - .map_err(|_e| Error::::NotEnoughToRedeem)?; + .map_err(|_e| Error::::NotEnoughToRedeem)?; T::MultiCurrency::transfer(token_b, &pool.keeper, &user, try_redeem) - .map_err(|_e| Error::::NotEnoughToRedeem)?; + .map_err(|_e| Error::::NotEnoughToRedeem)?; }, PoolType::EBFarming => {}, }; if pool.state == PoolState::Retired && pool.deposit == Zero::zero() { - pool.try_withdraw_remain()?; + pool.try_withdraw_remain::()?; pool.state = PoolState::Dead; } @@ -1079,13 +1144,13 @@ pub mod pallet { let trading_pair = pool.trading_pair; match pool.deposit.saturated_into() { - 0u128 => TotalPoolInfos::::remove(pid), - _ => TotalPoolInfos::::insert(pid, pool), + 0u128 => TotalPoolInfos::::remove(pid), + _ => TotalPoolInfos::::insert(pid, pool), } match deposit_data.deposit.saturated_into() { - 0u128 => TotalDepositData::::remove(pid, user.clone()), - _ => TotalDepositData::::insert(pid, user.clone(), deposit_data), + 0u128 => TotalDepositData::::remove(pid, user.clone()), + _ => TotalDepositData::::insert(pid, user.clone(), deposit_data), } Self::deposit_event(Event::UserRedeemed(pid, r#type, trading_pair, try_redeem, user)); @@ -1095,7 +1160,7 @@ pub mod pallet { pub(crate) fn next_pool_id() -> PoolId { let next_pool_id = Self::pool_id(); - NextPoolId::::mutate(|current| *current = current.saturating_add(1)); + NextPoolId::::mutate(|current| *current = current.saturating_add(1)); next_pool_id } @@ -1109,8 +1174,8 @@ pub mod pallet { (token2.currency_id() & 0x0000_0000_0000_00ff) as u8, ); let (sym1, sym2) = ( - TokenSymbol::try_from(sid1).map_err(|_| Error::::InvalidTradingPair)?, - TokenSymbol::try_from(sid2).map_err(|_| Error::::InvalidTradingPair)?, + TokenSymbol::try_from(sid1).map_err(|_| Error::::InvalidTradingPair)?, + TokenSymbol::try_from(sid2).map_err(|_| Error::::InvalidTradingPair)?, ); Ok(CurrencyId::LPToken(sym1, discr1, sym2, discr2)) @@ -1119,12 +1184,11 @@ pub mod pallet { pub fn rewards( who: AccountIdOf, pid: PoolId, - ) -> Result)>, ()> { - let pool: PoolInfo = Self::pool(pid).ok_or(())?.try_retire().try_update(); - let deposit_data: DepositData = - Self::user_deposit_data(pid, who.clone()).ok_or(())?; + ) -> Result)>, ()> { + let pool = Self::pool(pid).ok_or(())?.try_retire::().try_update::(); + let deposit_data = Self::user_deposit_data(pid, who.clone()).ok_or(())?; - let mut to_rewards = Vec::<(CurrencyId, BalanceOf)>::new(); + let mut to_rewards = Vec::<(CurrencyId, BalanceOf)>::new(); if let Some(_block_startup) = pool.block_startup { for (rtoken, reward) in pool.rewards.iter() { @@ -1133,7 +1197,7 @@ pub mod pallet { let v_old = *gain_avg; let user_deposit: u128 = deposit_data.deposit.saturated_into(); - let amount = BalanceOf::::saturated_from( + let amount = BalanceOf::::saturated_from( v_new.saturating_sub(v_old).saturating_mul_int(user_deposit), ); @@ -1147,16 +1211,16 @@ pub mod pallet { } #[pallet::hooks] - impl Hooks> for Pallet { + impl, I: 'static> Hooks> for Pallet { fn on_finalize(n: BlockNumberFor) { // Check whether pool-activated is meet the startup condition for pid in Self::charged_pids() { if let Some(mut pool) = Self::pool(pid) { - pool = pool.try_startup(n); + pool = pool.try_startup::(n); if pool.state == PoolState::Ongoing { - ChargedPoolIds::::mutate(|pids| pids.remove(&pid)); - TotalPoolInfos::::insert(pid, pool); + ChargedPoolIds::::mutate(|pids| pids.remove(&pid)); + TotalPoolInfos::::insert(pid, pool); } } } diff --git a/pallets/liquidity-mining/src/tests.rs b/pallets/liquidity-mining/src/tests.rs index 9ffd9b8dda..1d4c30b50c 100644 --- a/pallets/liquidity-mining/src/tests.rs +++ b/pallets/liquidity-mining/src/tests.rs @@ -30,7 +30,7 @@ use orml_traits::MultiReservableCurrency; use crate::{ mock::{Test as T, *}, - Error, PoolId, PoolInfo, PoolState, PoolType, TotalPoolInfos, + Error, PoolId, PoolState, PoolType, TotalPoolInfos, }; fn run_to_block(n: BlockNumber) { @@ -708,7 +708,7 @@ fn deposit_to_pool_ongoing_with_init_deposit_should_work() { assert_eq!(Tokens::accounts(USER_1, REWARD_2).frozen, 0); assert_eq!(Tokens::accounts(USER_1, REWARD_2).reserved, 0); - let pool: PoolInfo = LM::pool(0).unwrap(); + let pool = LM::pool(0).unwrap(); assert_eq!(pool.deposit, 3_000_000); for (_rtoken, reward) in pool.rewards.iter() { @@ -762,7 +762,7 @@ fn double_deposit_to_pool_ongoing_in_diff_block_should_work() { assert_eq!(Tokens::accounts(USER_2, REWARD_2).frozen, 0); assert_eq!(Tokens::accounts(USER_2, REWARD_2).reserved, 0); - let pool: PoolInfo = LM::pool(0).unwrap(); + let pool = LM::pool(0).unwrap(); assert_eq!(pool.deposit, 3_000_000); for (_rtoken, reward) in pool.rewards.iter() { @@ -808,7 +808,7 @@ fn double_deposit_to_pool_ongoing_in_same_block_should_work() { assert_eq!(Tokens::accounts(USER_2, REWARD_2).frozen, 0); assert_eq!(Tokens::accounts(USER_2, REWARD_2).reserved, 0); - let pool: PoolInfo = LM::pool(0).unwrap(); + let pool = LM::pool(0).unwrap(); assert_eq!(pool.deposit, 3_000_000); for (_rtoken, reward) in pool.rewards.iter() { @@ -1554,7 +1554,7 @@ fn claim_from_pool_ongoing_should_work() { assert_eq!(Tokens::accounts(USER_1, REWARD_2).frozen, 0); assert_eq!(Tokens::accounts(USER_1, REWARD_2).reserved, 0); - let pool: PoolInfo = LM::pool(0).unwrap(); + let pool = LM::pool(0).unwrap(); assert_eq!(Tokens::accounts(pool.keeper.clone(), REWARD_1).free, kept - rewarded); assert_eq!(Tokens::accounts(pool.keeper.clone(), REWARD_1).frozen, 0); @@ -1563,7 +1563,7 @@ fn claim_from_pool_ongoing_should_work() { assert_eq!(Tokens::accounts(pool.keeper.clone(), REWARD_2).frozen, 0); assert_eq!(Tokens::accounts(pool.keeper.clone(), REWARD_2).reserved, 0); - let pool: PoolInfo = LM::pool(0).unwrap(); + let pool = LM::pool(0).unwrap(); assert_eq!(pool.rewards.get(&REWARD_1).unwrap().claimed, rewarded); assert_eq!(pool.rewards.get(&REWARD_2).unwrap().claimed, rewarded); }); diff --git a/pallets/salp-lite/src/lib.rs b/pallets/salp-lite/src/lib.rs index eb90da5d4d..7576653e2a 100644 --- a/pallets/salp-lite/src/lib.rs +++ b/pallets/salp-lite/src/lib.rs @@ -504,11 +504,7 @@ pub mod pallet { let raised = fund.raised.checked_add(&value).ok_or(Error::::Overflow)?; ensure!(raised <= fund.cap, Error::::CapExceeded); - let (contributed, status) = Self::contribution(fund.trie_index, &who); - ensure!( - status == ContributionStatus::Idle || status == ContributionStatus::MigrateToIdle, - Error::::InvalidContributionStatus - ); + let (contributed, _) = Self::contribution(fund.trie_index, &who); let (vs_token, vs_bond) = Self::vsAssets(index, fund.first_slot, fund.last_slot); diff --git a/pallets/salp/src/lib.rs b/pallets/salp/src/lib.rs index 04883061e9..8e45a60600 100644 --- a/pallets/salp/src/lib.rs +++ b/pallets/salp/src/lib.rs @@ -592,7 +592,8 @@ pub mod pallet { ensure!( status == ContributionStatus::Idle || status == ContributionStatus::Refunded || - status == ContributionStatus::Redeemed, + status == ContributionStatus::Redeemed || + status == ContributionStatus::Unlocked, Error::::InvalidContributionStatus ); diff --git a/runtime/asgard/src/lib.rs b/runtime/asgard/src/lib.rs index 9e76efe41e..369b46ec34 100644 --- a/runtime/asgard/src/lib.rs +++ b/runtime/asgard/src/lib.rs @@ -125,8 +125,6 @@ use zenlink_protocol::{ mod benchmarking; mod weights; -pub type SessionHandlers = (); - impl_opaque_keys! { pub struct SessionKeys { pub aura: Aura, @@ -280,6 +278,7 @@ parameter_types! { pub const TreasuryPalletId: PalletId = PalletId(*b"bf/trsry"); pub const BifrostCrowdloanId: PalletId = PalletId(*b"bf/salp#"); pub const LiquidityMiningPalletId: PalletId = PalletId(*b"bf/lm###"); + pub const LiquidityMiningDOTPalletId: PalletId = PalletId(*b"bf/lmdot"); pub const LighteningRedeemPalletId: PalletId = PalletId(*b"bf/ltnrd"); } @@ -1135,7 +1134,8 @@ pub struct DustRemovalWhitelist; impl Contains for DustRemovalWhitelist { fn contains(a: &AccountId) -> bool { get_all_pallet_accounts().contains(a) || - LiquidityMiningPalletId::get().check_sub_account::(a) + LiquidityMiningPalletId::get().check_sub_account::(a) || + LiquidityMiningDOTPalletId::get().check_sub_account::(a) } } @@ -1411,6 +1411,7 @@ impl bifrost_vsbond_auction::Config for Runtime { parameter_types! { pub const RelayChainTokenSymbol: TokenSymbol = TokenSymbol::KSM; + pub const RelayChainTokenSymbolDOT: TokenSymbol = TokenSymbol::DOT; pub const MaximumDepositInPool: Balance = 1_000_000_000 * DOLLARS; pub const MinimumDepositOfUser: Balance = 1_000_000; pub const MinimumRewardPerBlock: Balance = 1_000; @@ -1419,7 +1420,7 @@ parameter_types! { pub const MaximumCharged: u32 = 32; } -impl bifrost_liquidity_mining::Config for Runtime { +impl bifrost_liquidity_mining::Config for Runtime { type Event = Event; type ControlOrigin = MoreThanHalfCouncil; type MultiCurrency = Currencies; @@ -1434,6 +1435,21 @@ impl bifrost_liquidity_mining::Config for Runtime { type WeightInfo = (); } +impl bifrost_liquidity_mining::Config for Runtime { + type Event = Event; + type ControlOrigin = MoreThanHalfCouncil; + type MultiCurrency = Currencies; + type RelayChainTokenSymbol = RelayChainTokenSymbolDOT; + type MaximumDepositInPool = MaximumDepositInPool; + type MinimumDepositOfUser = MinimumDepositOfUser; + type MinimumRewardPerBlock = MinimumRewardPerBlock; + type MinimumDuration = MinimumDuration; + type MaximumCharged = MaximumCharged; + type MaximumOptionRewards = MaximumOptionRewards; + type PalletId = LiquidityMiningDOTPalletId; + type WeightInfo = (); +} + impl bifrost_token_issuer::Config for Runtime { type Event = Event; type MultiCurrency = Currencies; @@ -1635,12 +1651,13 @@ construct_runtime! { MinterReward: bifrost_minter_reward::{Pallet, Call, Storage, Event, Config} = 102, Salp: bifrost_salp::{Pallet, Call, Storage, Event} = 105, Bancor: bifrost_bancor::{Pallet, Call, Storage, Event, Config} = 106, - VSBondAuction: bifrost_vsbond_auction::{Pallet, Call, Storage, Event} = 107, - LiquidityMining: bifrost_liquidity_mining::{Pallet, Call, Storage, Event} = 108, + LiquidityMiningDOT: bifrost_liquidity_mining::::{Pallet, Call, Storage, Event} = 107, + LiquidityMining: bifrost_liquidity_mining::::{Pallet, Call, Storage, Event} = 108, TokenIssuer: bifrost_token_issuer::{Pallet, Call, Storage, Event} = 109, LighteningRedeem: bifrost_lightening_redeem::{Pallet, Call, Storage, Event} = 110, SalpLite: bifrost_salp_lite::{Pallet, Call, Storage, Event} = 111, CallSwitchgear: bifrost_call_switchgear::{Pallet, Storage, Call, Event} = 112, + VSBondAuction: bifrost_vsbond_auction::{Pallet, Call, Storage, Event} = 113, } } @@ -1914,8 +1931,12 @@ impl_runtime_apis! { } impl bifrost_liquidity_mining_rpc_runtime_api::LiquidityMiningRuntimeApi for Runtime { - fn get_rewards(who: AccountId, pid: PoolId) -> Vec<(CurrencyId, Balance)> { - LiquidityMining::rewards(who, pid).unwrap_or(Vec::new()) + fn get_rewards(who: AccountId, pid: PoolId, pallet_instance: u32) -> Vec<(CurrencyId, Balance)> { + match pallet_instance { + 1 => LiquidityMining::rewards(who, pid).unwrap_or(Vec::new()), + 2 => LiquidityMiningDOT::rewards(who, pid).unwrap_or(Vec::new()), + _ => Vec::new() + } } } @@ -2013,18 +2034,13 @@ impl OnRuntimeUpgrade for CustomOnRuntimeUpgrade { fn pre_upgrade() -> Result<(), &'static str> { #[allow(unused_imports)] use frame_support::{migration, Identity}; - log::info!("Asgard `pre_upgrade`..."); - - bifrost_salp::migration::migrate(); - Ok(()) } #[cfg(feature = "try-runtime")] fn on_runtime_upgrade() -> Weight { log::info!("Asgard `on_runtime_upgrade`..."); - let _ = PolkadotXcm::force_default_xcm_version(Origin::root(), Some(2)); log::info!("Asgard `on_runtime_upgrade finished`"); RocksDbWeight::get().writes(1) } diff --git a/runtime/bifrost/src/lib.rs b/runtime/bifrost/src/lib.rs index ba70a856bf..a94f97320d 100644 --- a/runtime/bifrost/src/lib.rs +++ b/runtime/bifrost/src/lib.rs @@ -120,8 +120,6 @@ use zenlink_protocol::{ // Weights used in the runtime. mod weights; -pub type SessionHandlers = (); - impl_opaque_keys! { pub struct SessionKeys { pub aura: Aura, @@ -134,7 +132,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bifrost"), impl_name: create_runtime_str!("bifrost"), authoring_version: 1, - spec_version: 909, + spec_version: 910, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -283,6 +281,7 @@ parameter_types! { pub const BifrostCrowdloanId: PalletId = PalletId(*b"bf/salp#"); pub const BifrostSalpLiteCrowdloanId: PalletId = PalletId(*b"bf/salpl"); pub const LiquidityMiningPalletId: PalletId = PalletId(*b"bf/lm###"); + pub const LiquidityMiningDOTPalletId: PalletId = PalletId(*b"bf/lmdot"); pub const LighteningRedeemPalletId: PalletId = PalletId(*b"bf/ltnrd"); } @@ -1071,7 +1070,7 @@ impl pallet_collator_selection::Config for Runtime { type MaxInvulnerables = MaxInvulnerables; type MinCandidates = MinCandidates; type PotId = PotId; - type UpdateOrigin = EnsureRoot; + type UpdateOrigin = MoreThanHalfCouncil; type ValidatorId = ::AccountId; type ValidatorIdOf = pallet_collator_selection::IdentityCollator; type ValidatorRegistration = Session; @@ -1125,7 +1124,8 @@ impl Contains for DustRemovalWhitelist { AccountIdConversion::::into_account(&BifrostCrowdloanId::get()).eq(a) || AccountIdConversion::::into_account(&BifrostSalpLiteCrowdloanId::get()) .eq(a) || AccountIdConversion::::into_account(&LighteningRedeemPalletId::get()) - .eq(a) || LiquidityMiningPalletId::get().check_sub_account::(a) + .eq(a) || LiquidityMiningPalletId::get().check_sub_account::(a) || + LiquidityMiningDOTPalletId::get().check_sub_account::(a) } } @@ -1367,7 +1367,8 @@ impl bifrost_salp_lite::Config for Runtime { } parameter_types! { - pub const RelayChainTokenSymbol: TokenSymbol = TokenSymbol::KSM; + pub const RelayChainTokenSymbolKSM: TokenSymbol = TokenSymbol::KSM; + pub const RelayChainTokenSymbolDOT: TokenSymbol = TokenSymbol::DOT; pub const MaximumDepositInPool: Balance = 1_000_000_000 * DOLLARS; pub const MinimumDepositOfUser: Balance = 1_000_000; pub const MinimumRewardPerBlock: Balance = 1_000; @@ -1376,11 +1377,11 @@ parameter_types! { pub const MaximumCharged: u32 = 32; } -impl bifrost_liquidity_mining::Config for Runtime { +impl bifrost_liquidity_mining::Config for Runtime { type Event = Event; type ControlOrigin = MoreThanHalfCouncil; type MultiCurrency = Currencies; - type RelayChainTokenSymbol = RelayChainTokenSymbol; + type RelayChainTokenSymbol = RelayChainTokenSymbolKSM; type MaximumDepositInPool = MaximumDepositInPool; type MinimumDepositOfUser = MinimumDepositOfUser; type MinimumRewardPerBlock = MinimumRewardPerBlock; @@ -1391,6 +1392,21 @@ impl bifrost_liquidity_mining::Config for Runtime { type WeightInfo = (); } +impl bifrost_liquidity_mining::Config for Runtime { + type Event = Event; + type ControlOrigin = MoreThanHalfCouncil; + type MultiCurrency = Currencies; + type RelayChainTokenSymbol = RelayChainTokenSymbolDOT; + type MaximumDepositInPool = MaximumDepositInPool; + type MinimumDepositOfUser = MinimumDepositOfUser; + type MinimumRewardPerBlock = MinimumRewardPerBlock; + type MinimumDuration = MinimumDuration; + type MaximumCharged = MaximumCharged; + type MaximumOptionRewards = MaximumOptionRewards; + type PalletId = LiquidityMiningDOTPalletId; + type WeightInfo = (); +} + impl bifrost_token_issuer::Config for Runtime { type Event = Event; type MultiCurrency = Currencies; @@ -1556,7 +1572,7 @@ construct_runtime! { // XCM helpers. XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event} = 40, - PolkadotXcm: pallet_xcm::{Pallet, Call, Event, Origin, Config} = 41, + PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event, Origin, Config} = 41, CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event, Origin} = 42, DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event} = 43, @@ -1586,7 +1602,8 @@ construct_runtime! { // Bifrost modules FlexibleFee: bifrost_flexible_fee::{Pallet, Call, Storage, Event} = 100, Salp: bifrost_salp::{Pallet, Call, Storage, Event} = 105, - LiquidityMining: bifrost_liquidity_mining::{Pallet, Call, Storage, Event} = 108, + LiquidityMiningDOT: bifrost_liquidity_mining::::{Pallet, Call, Storage, Event} = 107, + LiquidityMining: bifrost_liquidity_mining::::{Pallet, Call, Storage, Event} = 108, TokenIssuer: bifrost_token_issuer::{Pallet, Call, Storage, Event} = 109, LighteningRedeem: bifrost_lightening_redeem::{Pallet, Call, Storage, Event} = 110, SalpLite: bifrost_salp_lite::{Pallet, Call, Storage, Event} = 111, @@ -1830,8 +1847,12 @@ impl_runtime_apis! { } impl bifrost_liquidity_mining_rpc_runtime_api::LiquidityMiningRuntimeApi for Runtime { - fn get_rewards(who: AccountId, pid: PoolId) -> Vec<(CurrencyId, Balance)> { - LiquidityMining::rewards(who, pid).unwrap_or(Vec::new()) + fn get_rewards(who: AccountId, pid: PoolId, pallet_instance: u32) -> Vec<(CurrencyId, Balance)> { + match pallet_instance { + 1 => LiquidityMining::rewards(who, pid).unwrap_or(Vec::new()), + 2 => LiquidityMiningDOT::rewards(who, pid).unwrap_or(Vec::new()), + _ => Vec::new() + } } } @@ -1916,16 +1937,13 @@ impl OnRuntimeUpgrade for CustomOnRuntimeUpgrade { fn pre_upgrade() -> Result<(), &'static str> { #[allow(unused_imports)] use frame_support::{migration, Identity}; - log::info!("Bifrost `pre_upgrade`..."); - Ok(()) } #[cfg(feature = "try-runtime")] fn on_runtime_upgrade() -> Weight { log::info!("Bifrost `on_runtime_upgrade`..."); - let _ = PolkadotXcm::force_default_xcm_version(Origin::root(), Some(2)); log::info!("Bifrost `on_runtime_upgrade finished`"); RocksDbWeight::get().writes(1) }