From aed1579f75f655391bea2d8eff1db5ed4e153d66 Mon Sep 17 00:00:00 2001 From: Index0011 Date: Sun, 14 May 2023 14:44:08 +0000 Subject: [PATCH 01/12] implment currency trait for wrapped_balance and replace balances for currency in election's config --- pallets/phala/src/compute/wrapped_balances.rs | 274 +++++++++++++++++- pallets/phala/src/lib.rs | 3 + standalone/runtime/src/lib.rs | 2 +- 3 files changed, 262 insertions(+), 17 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index 838fc57a94..8da411896d 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -8,24 +8,27 @@ pub mod pallet { use crate::pool_proxy::PoolProxy; use crate::registry; use crate::vault; - use crate::{BalanceOf, NegativeImbalanceOf, PhalaConfig}; + use crate::{BalanceOf, NegativeImbalanceOf, PhalaConfig, PositiveImbalanceOf}; + use frame_support::traits::tokens::{Fortitude, Precision}; use frame_support::{ pallet_prelude::*, traits::{ - tokens::fungibles::{Inspect, Mutate}, tokens::nonfungibles::InspectEnumerable, - Currency, - ExistenceRequirement::{AllowDeath, KeepAlive}, - OnUnbalanced, StorageVersion, + tokens::{ + fungibles::{Inspect, Mutate}, + BalanceStatus, + }, + Currency, ExistenceRequirement, Imbalance, LockIdentifier, LockableCurrency, + OnUnbalanced, ReservableCurrency, SignedImbalance, StorageVersion, WithdrawReasons, }, }; - use frame_support::traits::tokens::{Fortitude, Precision}; use frame_system::{pallet_prelude::*, RawOrigin}; use pallet_democracy::{AccountVote, ReferendumIndex, ReferendumInfo}; pub use rmrk_traits::primitives::{CollectionId, NftId}; use scale_info::TypeInfo; - use sp_runtime::traits::Zero; + use sp_runtime::traits::{CheckedSub, Zero}; use sp_std::{fmt::Display, prelude::*, result::Result}; + #[pallet::config] pub trait Config: frame_system::Config @@ -89,6 +92,14 @@ pub mod pallet { pub type StakerAccounts = StorageMap<_, Twox64Concat, T::AccountId, FinanceAccount>>; + #[pallet::storage] + #[pallet::getter(fn election_locks)] + pub type ElectionLocks = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf>; + + #[pallet::storage] + #[pallet::getter(fn election_reserves)] + pub type ElectionReserves = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf>; + #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { @@ -133,6 +144,226 @@ pub mod pallet { ReferendumOngoing, /// The Iteration exceed the max limitaion IterationsIsNotVaild, + + LockLargerThanTotalBalance, + + LiquidityRestrictions, + } + + impl Currency for Pallet + where + BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, + T: pallet_assets::Config>, + T: Config + pallet_balances::Config + vault::Config, + T: pallet_balances::Config>, + { + type Balance = BalanceOf; + type PositiveImbalance = PositiveImbalanceOf; + type NegativeImbalance = NegativeImbalanceOf; + fn total_balance(who: &T::AccountId) -> Self::Balance { + as Inspect>::total_balance( + T::WPhaAssetId::get(), + who, + ) + } + + fn free_balance(who: &T::AccountId) -> Self::Balance { + let total_balance = Self::total_balance(who); + let lock = StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); + let election_lock = ElectionLocks::::get(who).unwrap_or_default(); + let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); + total_balance + .checked_sub(&lock.max(election_lock).max(election_reserve)) + .unwrap_or_default() + } + + fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool { + if value.is_zero() { + return true; + } + Self::free_balance(who) >= value + } + + fn total_issuance() -> Self::Balance { + as Inspect>::total_issuance( + T::WPhaAssetId::get(), + ) + } + + fn active_issuance() -> Self::Balance { + as Inspect>::total_issuance( + T::WPhaAssetId::get(), + ) + } + + fn deactivate(_amount: Self::Balance) {} + + fn reactivate(_amount: Self::Balance) {} + + fn minimum_balance() -> Self::Balance { + as Inspect>::minimum_balance( + T::WPhaAssetId::get(), + ) + } + + fn burn(mut _amount: Self::Balance) -> Self::PositiveImbalance { + Self::PositiveImbalance::zero() + } + + fn issue(mut _amount: Self::Balance) -> Self::NegativeImbalance { + Self::NegativeImbalance::zero() + } + + fn ensure_can_withdraw( + who: &T::AccountId, + amount: Self::Balance, + _reasons: WithdrawReasons, + new_balance: Self::Balance, + ) -> DispatchResult { + if amount.is_zero() { + return Ok(()); + } + let mut lock = + StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); + let election_lock = ElectionLocks::::get(who).unwrap_or_default(); + let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); + lock = lock.max(election_lock).max(election_reserve); + ensure!(new_balance >= lock, Error::::LiquidityRestrictions); + Ok(()) + } + + fn transfer( + _transactor: &T::AccountId, + _dest: &T::AccountId, + _value: Self::Balance, + _existence_requirement: ExistenceRequirement, + ) -> DispatchResult { + Ok(()) + } + + fn slash( + who: &T::AccountId, + _value: Self::Balance, + ) -> (Self::NegativeImbalance, Self::Balance) { + (Self::NegativeImbalance::zero(), Self::total_balance(who)) + } + + fn deposit_into_existing( + _who: &T::AccountId, + _value: Self::Balance, + ) -> Result { + Ok(Self::PositiveImbalance::zero()) + } + + fn deposit_creating(_who: &T::AccountId, _value: Self::Balance) -> Self::PositiveImbalance { + Self::PositiveImbalance::zero() + } + + fn withdraw( + _who: &T::AccountId, + _value: Self::Balance, + _reasons: WithdrawReasons, + _liveness: ExistenceRequirement, + ) -> Result { + Ok(Self::NegativeImbalance::zero()) + } + + fn make_free_balance_be( + _who: &T::AccountId, + _value: Self::Balance, + ) -> SignedImbalance { + SignedImbalance::Positive(Self::PositiveImbalance::zero()) + } + } + + impl ReservableCurrency for Pallet + where + BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, + T: pallet_assets::Config>, + T: Config + pallet_balances::Config + vault::Config, + T: pallet_balances::Config>, + { + fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { + Self::free_balance(who) >= value + } + fn reserved_balance(who: &T::AccountId) -> Self::Balance { + ElectionReserves::::get(who).unwrap_or_default() + } + fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { + let actual = value.min(Self::free_balance(who)); + ElectionReserves::::mutate(who, |reserve| { + *reserve = Some(reserve.unwrap_or_default() + actual); + }); + Ok(()) + } + fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance { + let actual = value.min(ElectionReserves::::get(who).unwrap_or_default()); + ElectionReserves::::mutate(who, |reserve| { + *reserve = Some(reserve.unwrap_or_default() - actual); + }); + value - actual + } + fn slash_reserved( + who: &T::AccountId, + value: Self::Balance, + ) -> (Self::NegativeImbalance, Self::Balance) { + let actual = value.min(ElectionReserves::::get(who).unwrap_or_default()); + ElectionReserves::::mutate(who, |reserve| { + *reserve = Some(reserve.unwrap_or_default() - actual); + }); + Self::burn_from(who, actual) + .expect("burn nft when slash reserved should success; qed."); + let imbalance = ::Currency::withdraw( + &T::WrappedBalancesAccountId::get(), + actual, + WithdrawReasons::all(), + ExistenceRequirement::AllowDeath, + ) + .expect("slash imbalance should success; qed."); + (imbalance, value - actual) + } + fn repatriate_reserved( + _slashed: &T::AccountId, + _beneficiary: &T::AccountId, + _value: Self::Balance, + _status: BalanceStatus, + ) -> Result { + Ok(Zero::zero()) + } + } + impl LockableCurrency for Pallet + where + BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, + T: pallet_assets::Config>, + T: Config + pallet_balances::Config + vault::Config, + T: pallet_balances::Config>, + { + type Moment = T::BlockNumber; + type MaxLocks = T::MaxLocks; + fn set_lock( + _id: LockIdentifier, + who: &T::AccountId, + amount: Self::Balance, + _reasons: WithdrawReasons, + ) { + let actual = amount.min(Self::free_balance(who)); + ElectionLocks::::insert(who, actual); + } + fn extend_lock( + _id: LockIdentifier, + who: &T::AccountId, + amount: Self::Balance, + _reasons: WithdrawReasons, + ) { + let current_lock = ElectionLocks::::get(who).unwrap_or_default(); + let actual = (current_lock + amount).min(Self::free_balance(who)); + ElectionLocks::::mutate(who, |locks| { + *locks = Some(locks.unwrap_or_default() + actual); + }); + } + fn remove_lock(_id: LockIdentifier, who: &T::AccountId) { + ElectionLocks::::remove(who); + } } impl rmrk_traits::TransferHooks for Pallet @@ -196,7 +427,7 @@ pub mod pallet { &user, &T::WrappedBalancesAccountId::get(), amount, - KeepAlive, + ExistenceRequirement::KeepAlive, )?; Self::mint_into(&user, amount)?; if !StakerAccounts::::contains_key(&user) { @@ -224,14 +455,17 @@ pub mod pallet { let free_stakes: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), &user); - let locked = + let mut locked = StakerAccounts::::get(&user).map_or(Zero::zero(), |status| status.locked); + let election_lock = ElectionLocks::::get(&user).unwrap_or_default(); + let election_reserve = ElectionReserves::::get(&user).unwrap_or_default(); + locked = locked.max(election_lock).max(election_reserve); let withdraw_amount = (active_stakes - locked).min(free_stakes); ::Currency::transfer( &T::WrappedBalancesAccountId::get(), &user, withdraw_amount, - AllowDeath, + ExistenceRequirement::AllowDeath, )?; Self::burn_from(&user, withdraw_amount)?; Ok(()) @@ -253,8 +487,11 @@ pub mod pallet { Error::::UnwrapAmountExceedsAvaliableStake ); let active_stakes = Self::get_net_value(user.clone())?; - let locked = + let mut locked = StakerAccounts::::get(&user).map_or(Zero::zero(), |status| status.locked); + let election_lock = ElectionLocks::::get(&user).unwrap_or_default(); + let election_reserve = ElectionReserves::::get(&user).unwrap_or_default(); + locked = locked.max(election_lock).max(election_reserve); ensure!( amount + locked <= active_stakes, Error::::UnwrapAmountExceedsAvaliableStake, @@ -263,7 +500,7 @@ pub mod pallet { &T::WrappedBalancesAccountId::get(), &user, amount, - AllowDeath, + ExistenceRequirement::AllowDeath, )?; Self::burn_from(&user, amount)?; Self::deposit_event(Event::::Unwrapped { user, amount }); @@ -379,9 +616,14 @@ pub mod pallet { pub fn remove_dust(who: &T::AccountId, dust: BalanceOf) { debug_assert!(dust != Zero::zero()); if dust != Zero::zero() { - let actual_removed = - pallet_assets::Pallet::::burn_from(T::WPhaAssetId::get(), who, dust, Precision::BestEffort, Fortitude::Force) - .expect("slash should success with correct amount: qed."); + let actual_removed = pallet_assets::Pallet::::burn_from( + T::WPhaAssetId::get(), + who, + dust, + Precision::BestEffort, + Fortitude::Force, + ) + .expect("slash should success with correct amount: qed."); let (imbalance, _remaining) = ::Currency::slash( &>::account_id(), dust, @@ -407,7 +649,7 @@ pub mod pallet { target, amount, Precision::BestEffort, - Fortitude::Force + Fortitude::Force, )?; Ok(()) } diff --git a/pallets/phala/src/lib.rs b/pallets/phala/src/lib.rs index cff335a980..5d379ad6da 100644 --- a/pallets/phala/src/lib.rs +++ b/pallets/phala/src/lib.rs @@ -39,6 +39,9 @@ type NegativeImbalanceOf = <::Currency as frame_support::tr ::AccountId, >>::NegativeImbalance; +type PositiveImbalanceOf = <::Currency as frame_support::traits::Currency< + ::AccountId, +>>::PositiveImbalance; // Alias pub use compute::base_pool as pallet_base_pool; pub use compute::computation as pallet_computation; diff --git a/standalone/runtime/src/lib.rs b/standalone/runtime/src/lib.rs index 3e9c33530a..f049dc94dc 100644 --- a/standalone/runtime/src/lib.rs +++ b/standalone/runtime/src/lib.rs @@ -931,7 +931,7 @@ const_assert!(DesiredMembers::get() <= CouncilMaxMembers::get()); impl pallet_elections_phragmen::Config for Runtime { type RuntimeEvent = RuntimeEvent; type PalletId = ElectionsPhragmenPalletId; - type Currency = Balances; + type Currency = PhalaWrappedBalances; type ChangeMembers = Council; // NOTE: this implies that council's genesis members cannot be set directly and must come from // this module. From 16bb96b8ef55d4a5b1029430adbe02603cbaa0d6 Mon Sep 17 00:00:00 2001 From: Index0011 Date: Thu, 18 May 2023 08:22:14 +0000 Subject: [PATCH 02/12] correct total_balance --- pallets/phala/src/compute/wrapped_balances.rs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index 8da411896d..ebc5493bb4 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -161,10 +161,7 @@ pub mod pallet { type PositiveImbalance = PositiveImbalanceOf; type NegativeImbalance = NegativeImbalanceOf; fn total_balance(who: &T::AccountId) -> Self::Balance { - as Inspect>::total_balance( - T::WPhaAssetId::get(), - who, - ) + Self::get_net_value(who.clone()).expect("Get net value should success; qed.") } fn free_balance(who: &T::AccountId) -> Self::Balance { @@ -284,13 +281,13 @@ pub mod pallet { T: pallet_balances::Config>, { fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { - Self::free_balance(who) >= value + Self::total_balance(who) >= value } fn reserved_balance(who: &T::AccountId) -> Self::Balance { ElectionReserves::::get(who).unwrap_or_default() } fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { - let actual = value.min(Self::free_balance(who)); + let actual = value.min(Self::total_balance(who)); ElectionReserves::::mutate(who, |reserve| { *reserve = Some(reserve.unwrap_or_default() + actual); }); @@ -346,7 +343,7 @@ pub mod pallet { amount: Self::Balance, _reasons: WithdrawReasons, ) { - let actual = amount.min(Self::free_balance(who)); + let actual = amount.min(Self::total_balance(who)); ElectionLocks::::insert(who, actual); } fn extend_lock( @@ -356,7 +353,7 @@ pub mod pallet { _reasons: WithdrawReasons, ) { let current_lock = ElectionLocks::::get(who).unwrap_or_default(); - let actual = (current_lock + amount).min(Self::free_balance(who)); + let actual = (current_lock + amount).min(Self::total_balance(who)); ElectionLocks::::mutate(who, |locks| { *locks = Some(locks.unwrap_or_default() + actual); }); From 3da22f536cfa18787113bfd9f94eccac7888004d Mon Sep 17 00:00:00 2001 From: Index0011 Date: Fri, 19 May 2023 01:29:58 +0000 Subject: [PATCH 03/12] fix free balance --- pallets/phala/src/compute/wrapped_balances.rs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index ebc5493bb4..d97aebdfec 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -165,13 +165,7 @@ pub mod pallet { } fn free_balance(who: &T::AccountId) -> Self::Balance { - let total_balance = Self::total_balance(who); - let lock = StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); - let election_lock = ElectionLocks::::get(who).unwrap_or_default(); - let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); - total_balance - .checked_sub(&lock.max(election_lock).max(election_reserve)) - .unwrap_or_default() + Self::total_balance(who) } fn can_slash(who: &T::AccountId, value: Self::Balance) -> bool { From bc5738bb76ff6e97aaf2fabef8c3951a097d38a1 Mon Sep 17 00:00:00 2001 From: Index0011 Date: Fri, 19 May 2023 09:41:06 +0000 Subject: [PATCH 04/12] response for review --- Cargo.lock | 1 + pallets/phala/Cargo.toml | 5 +- pallets/phala/src/compute/wrapped_balances.rs | 71 ++++++++++--------- 3 files changed, 44 insertions(+), 33 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 644d2f7b76..7902c65179 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -8018,6 +8018,7 @@ dependencies = [ "pallet-balances", "pallet-collective", "pallet-democracy", + "pallet-elections-phragmen", "pallet-insecure-randomness-collective-flip", "pallet-preimage", "pallet-rmrk-core", diff --git a/pallets/phala/Cargo.toml b/pallets/phala/Cargo.toml index 81ec383e98..2191fee742 100644 --- a/pallets/phala/Cargo.toml +++ b/pallets/phala/Cargo.toml @@ -27,6 +27,7 @@ rmrk-traits = { git = "https://github.com/Phala-Network/rmrk-substrate", branch frame-support = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } frame-system = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } pallet-insecure-randomness-collective-flip = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } +pallet-elections-phragmen = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } sp-runtime = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } sp-std = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } sp-io = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.42", default-features = false } @@ -73,6 +74,7 @@ std = [ "frame-system/std", "pallet-assets/std", "pallet-democracy/std", + "pallet-elections-phragmen/std", "sp-io/std", "sp-std/std", "sp-core/std", @@ -91,7 +93,8 @@ std = [ "pallet-preimage/std", ] runtime-benchmarks = [ - "frame-benchmarking/runtime-benchmarks" + "frame-benchmarking/runtime-benchmarks", + "pallet-elections-phragmen/runtime-benchmarks", ] try-runtime = ["frame-support/try-runtime"] native = [ diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index d97aebdfec..d12ee9bbd5 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -26,7 +26,7 @@ pub mod pallet { use pallet_democracy::{AccountVote, ReferendumIndex, ReferendumInfo}; pub use rmrk_traits::primitives::{CollectionId, NftId}; use scale_info::TypeInfo; - use sp_runtime::traits::{CheckedSub, Zero}; + use sp_runtime::traits::Zero; use sp_std::{fmt::Display, prelude::*, result::Result}; #[pallet::config] @@ -154,7 +154,7 @@ pub mod pallet { where BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_assets::Config>, - T: Config + pallet_balances::Config + vault::Config, + T: Config + pallet_balances::Config + vault::Config + pallet_elections_phragmen::Config, T: pallet_balances::Config>, { type Balance = BalanceOf; @@ -187,9 +187,13 @@ pub mod pallet { ) } - fn deactivate(_amount: Self::Balance) {} + fn deactivate(_amount: Self::Balance) { + unimplemented!() + } - fn reactivate(_amount: Self::Balance) {} + fn reactivate(_amount: Self::Balance) { + unimplemented!() + } fn minimum_balance() -> Self::Balance { as Inspect>::minimum_balance( @@ -198,11 +202,11 @@ pub mod pallet { } fn burn(mut _amount: Self::Balance) -> Self::PositiveImbalance { - Self::PositiveImbalance::zero() + unimplemented!() } fn issue(mut _amount: Self::Balance) -> Self::NegativeImbalance { - Self::NegativeImbalance::zero() + unimplemented!() } fn ensure_can_withdraw( @@ -214,11 +218,7 @@ pub mod pallet { if amount.is_zero() { return Ok(()); } - let mut lock = - StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); - let election_lock = ElectionLocks::::get(who).unwrap_or_default(); - let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); - lock = lock.max(election_lock).max(election_reserve); + let lock = Self::get_election_lock(who); ensure!(new_balance >= lock, Error::::LiquidityRestrictions); Ok(()) } @@ -229,25 +229,25 @@ pub mod pallet { _value: Self::Balance, _existence_requirement: ExistenceRequirement, ) -> DispatchResult { - Ok(()) + unimplemented!() } fn slash( - who: &T::AccountId, + _who: &T::AccountId, _value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { - (Self::NegativeImbalance::zero(), Self::total_balance(who)) + unimplemented!() } fn deposit_into_existing( _who: &T::AccountId, _value: Self::Balance, ) -> Result { - Ok(Self::PositiveImbalance::zero()) + unimplemented!() } fn deposit_creating(_who: &T::AccountId, _value: Self::Balance) -> Self::PositiveImbalance { - Self::PositiveImbalance::zero() + unimplemented!() } fn withdraw( @@ -256,14 +256,14 @@ pub mod pallet { _reasons: WithdrawReasons, _liveness: ExistenceRequirement, ) -> Result { - Ok(Self::NegativeImbalance::zero()) + unimplemented!() } fn make_free_balance_be( _who: &T::AccountId, _value: Self::Balance, ) -> SignedImbalance { - SignedImbalance::Positive(Self::PositiveImbalance::zero()) + unimplemented!() } } @@ -271,7 +271,7 @@ pub mod pallet { where BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_assets::Config>, - T: Config + pallet_balances::Config + vault::Config, + T: Config + pallet_balances::Config + vault::Config + pallet_elections_phragmen::Config, T: pallet_balances::Config>, { fn can_reserve(who: &T::AccountId, value: Self::Balance) -> bool { @@ -298,6 +298,9 @@ pub mod pallet { who: &T::AccountId, value: Self::Balance, ) -> (Self::NegativeImbalance, Self::Balance) { + if value == Zero::zero() { + return (NegativeImbalanceOf::::zero(), Zero::zero()); + } let actual = value.min(ElectionReserves::::get(who).unwrap_or_default()); ElectionReserves::::mutate(who, |reserve| { *reserve = Some(reserve.unwrap_or_default() - actual); @@ -319,24 +322,29 @@ pub mod pallet { _value: Self::Balance, _status: BalanceStatus, ) -> Result { - Ok(Zero::zero()) + unimplemented!() } } impl LockableCurrency for Pallet where BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_assets::Config>, - T: Config + pallet_balances::Config + vault::Config, + T: Config + pallet_balances::Config + vault::Config + pallet_elections_phragmen::Config, T: pallet_balances::Config>, { type Moment = T::BlockNumber; type MaxLocks = T::MaxLocks; fn set_lock( - _id: LockIdentifier, + id: LockIdentifier, who: &T::AccountId, amount: Self::Balance, _reasons: WithdrawReasons, ) { + if amount == Zero::zero() + || id != ::PalletId::get() + { + return; + } let actual = amount.min(Self::total_balance(who)); ElectionLocks::::insert(who, actual); } @@ -446,11 +454,7 @@ pub mod pallet { let free_stakes: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), &user); - let mut locked = - StakerAccounts::::get(&user).map_or(Zero::zero(), |status| status.locked); - let election_lock = ElectionLocks::::get(&user).unwrap_or_default(); - let election_reserve = ElectionReserves::::get(&user).unwrap_or_default(); - locked = locked.max(election_lock).max(election_reserve); + let locked = Self::get_election_lock(&user); let withdraw_amount = (active_stakes - locked).min(free_stakes); ::Currency::transfer( &T::WrappedBalancesAccountId::get(), @@ -478,11 +482,7 @@ pub mod pallet { Error::::UnwrapAmountExceedsAvaliableStake ); let active_stakes = Self::get_net_value(user.clone())?; - let mut locked = - StakerAccounts::::get(&user).map_or(Zero::zero(), |status| status.locked); - let election_lock = ElectionLocks::::get(&user).unwrap_or_default(); - let election_reserve = ElectionReserves::::get(&user).unwrap_or_default(); - locked = locked.max(election_lock).max(election_reserve); + let locked = Self::get_election_lock(&user); ensure!( amount + locked <= active_stakes, Error::::UnwrapAmountExceedsAvaliableStake, @@ -732,5 +732,12 @@ pub mod pallet { let vote_info = pallet_democracy::Pallet::::referendum_info(vote_id); matches!(vote_info, Some(ReferendumInfo::Ongoing(_))) } + + fn get_election_lock(who: &T::AccountId) -> BalanceOf { + let lock = StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); + let election_lock = ElectionLocks::::get(who).unwrap_or_default(); + let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); + lock.max(election_lock).max(election_reserve) + } } } From 61343a14c6958f8d508b4adc96f8ab2d64a732ac Mon Sep 17 00:00:00 2001 From: Index0011 Date: Mon, 22 May 2023 10:35:02 +0000 Subject: [PATCH 05/12] wpha_council --- pallets/phala/src/compute/wrapped_balances.rs | 88 ++++++++++++++++--- 1 file changed, 75 insertions(+), 13 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index d12ee9bbd5..23bd60df6a 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -94,11 +94,15 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn election_locks)] - pub type ElectionLocks = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf>; + pub type ElectionLocks = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + + #[pallet::storage] + #[pallet::getter(fn slash_debts)] + pub type SlashDebts = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; #[pallet::storage] #[pallet::getter(fn election_reserves)] - pub type ElectionReserves = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf>; + pub type ElectionReserves = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -128,6 +132,10 @@ pub mod pallet { aye_amount: BalanceOf, nay_amount: BalanceOf, }, + ReserveSlashed { + user: T::AccountId, + slash: BalanceOf, + } } #[pallet::error] @@ -148,6 +156,8 @@ pub mod pallet { LockLargerThanTotalBalance, LiquidityRestrictions, + + WphaNotSettled, } impl Currency for Pallet @@ -278,19 +288,19 @@ pub mod pallet { Self::total_balance(who) >= value } fn reserved_balance(who: &T::AccountId) -> Self::Balance { - ElectionReserves::::get(who).unwrap_or_default() + ElectionReserves::::get(who) } fn reserve(who: &T::AccountId, value: Self::Balance) -> DispatchResult { let actual = value.min(Self::total_balance(who)); ElectionReserves::::mutate(who, |reserve| { - *reserve = Some(reserve.unwrap_or_default() + actual); + *reserve += actual; }); Ok(()) } fn unreserve(who: &T::AccountId, value: Self::Balance) -> Self::Balance { - let actual = value.min(ElectionReserves::::get(who).unwrap_or_default()); + let actual = value.min(ElectionReserves::::get(who)); ElectionReserves::::mutate(who, |reserve| { - *reserve = Some(reserve.unwrap_or_default() - actual); + *reserve -= actual; }); value - actual } @@ -301,9 +311,21 @@ pub mod pallet { if value == Zero::zero() { return (NegativeImbalanceOf::::zero(), Zero::zero()); } - let actual = value.min(ElectionReserves::::get(who).unwrap_or_default()); + let mut actual = value.min(ElectionReserves::::get(who)); + let free_wpha: BalanceOf = + as Inspect>::balance( + T::WPhaAssetId::get(), + who, + ); + if free_wpha < actual { + let new_debt = actual - free_wpha; + actual = free_wpha; + SlashDebts::::mutate(who, |debt| { + *debt += new_debt; + }); + } ElectionReserves::::mutate(who, |reserve| { - *reserve = Some(reserve.unwrap_or_default() - actual); + *reserve -= actual; }); Self::burn_from(who, actual) .expect("burn nft when slash reserved should success; qed."); @@ -314,6 +336,10 @@ pub mod pallet { ExistenceRequirement::AllowDeath, ) .expect("slash imbalance should success; qed."); + Self::deposit_event(Event::::ReserveSlashed{ + user: who.clone(), + slash: actual, + }); (imbalance, value - actual) } fn repatriate_reserved( @@ -354,10 +380,10 @@ pub mod pallet { amount: Self::Balance, _reasons: WithdrawReasons, ) { - let current_lock = ElectionLocks::::get(who).unwrap_or_default(); + let current_lock = ElectionLocks::::get(who); let actual = (current_lock + amount).min(Self::total_balance(who)); ElectionLocks::::mutate(who, |locks| { - *locks = Some(locks.unwrap_or_default() + actual); + *locks += actual; }); } fn remove_lock(_id: LockIdentifier, who: &T::AccountId) { @@ -412,7 +438,8 @@ pub mod pallet { T: pallet_uniques::Config, T: pallet_assets::Config>, T: pallet_democracy::Config::Currency>, - T: Config + vault::Config, + T: Config + pallet_balances::Config + vault::Config + pallet_elections_phragmen::Config, + T: pallet_balances::Config>, { /// Wraps some pha and gain equal amount of W-PHA /// @@ -422,6 +449,10 @@ pub mod pallet { #[frame_support::transactional] pub fn wrap(origin: OriginFor, amount: BalanceOf) -> DispatchResult { let user = ensure_signed(origin)?; + ensure!( + !SlashDebts::::contains_key(&user), + Error::::WphaNotSettled, + ); ::Currency::transfer( &user, &T::WrappedBalancesAccountId::get(), @@ -450,6 +481,10 @@ pub mod pallet { #[frame_support::transactional] pub fn unwrap_all(origin: OriginFor) -> DispatchResult { let user = ensure_signed(origin)?; + ensure!( + !SlashDebts::::contains_key(&user), + Error::::WphaNotSettled, + ); let active_stakes = Self::get_net_value(user.clone())?; let free_stakes: BalanceOf = as Inspect< T::AccountId, @@ -590,6 +625,33 @@ pub mod pallet { } Ok(()) } + #[pallet::call_index(6)] + #[pallet::weight({0})] + #[frame_support::transactional] + pub fn settle_balance_debt(origin: OriginFor) -> DispatchResult { + let who = ensure_signed(origin)?; + let debt = SlashDebts::::get(&who); + if debt == Zero::zero() { + return Ok(()); + } + let free_wpha = as Inspect>::balance( + T::WPhaAssetId::get(), + &who, + ); + let slash = debt.min(free_wpha); + let mut new_debt = Zero::zero(); + if debt > free_wpha { + new_debt = debt - free_wpha; + } + let (imbalance, _) = Self::slash_reserved(&who, slash); + T::OnSlashed::on_unbalanced(imbalance); + if new_debt != Zero::zero() { + SlashDebts::::insert(&who, new_debt); + } else { + SlashDebts::::remove(&who); + } + Ok(()) + } } impl Pallet where @@ -735,8 +797,8 @@ pub mod pallet { fn get_election_lock(who: &T::AccountId) -> BalanceOf { let lock = StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); - let election_lock = ElectionLocks::::get(who).unwrap_or_default(); - let election_reserve = ElectionReserves::::get(who).unwrap_or_default(); + let election_lock = ElectionLocks::::get(who); + let election_reserve = ElectionReserves::::get(who); lock.max(election_lock).max(election_reserve) } } From 1ca33940c0d638865d5bf1799edc27486ee4ec2b Mon Sep 17 00:00:00 2001 From: Index0011 Date: Mon, 22 May 2023 10:36:24 +0000 Subject: [PATCH 06/12] wpha_council --- pallets/phala/src/compute/wrapped_balances.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index 23bd60df6a..a05e49e948 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -375,11 +375,16 @@ pub mod pallet { ElectionLocks::::insert(who, actual); } fn extend_lock( - _id: LockIdentifier, + id: LockIdentifier, who: &T::AccountId, amount: Self::Balance, _reasons: WithdrawReasons, ) { + if amount == Zero::zero() + || id != ::PalletId::get() + { + return; + } let current_lock = ElectionLocks::::get(who); let actual = (current_lock + amount).min(Self::total_balance(who)); ElectionLocks::::mutate(who, |locks| { From e512d91f6c2b657c387afe4475cc7a0c1f75e6b1 Mon Sep 17 00:00:00 2001 From: Index0011 Date: Mon, 22 May 2023 10:40:03 +0000 Subject: [PATCH 07/12] wpha_council --- pallets/phala/src/compute/wrapped_balances.rs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index a05e49e948..8baeb3f047 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -228,7 +228,7 @@ pub mod pallet { if amount.is_zero() { return Ok(()); } - let lock = Self::get_election_lock(who); + let lock = Self::get_lock(who); ensure!(new_balance >= lock, Error::::LiquidityRestrictions); Ok(()) } @@ -494,7 +494,7 @@ pub mod pallet { let free_stakes: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), &user); - let locked = Self::get_election_lock(&user); + let locked = Self::get_lock(&user); let withdraw_amount = (active_stakes - locked).min(free_stakes); ::Currency::transfer( &T::WrappedBalancesAccountId::get(), @@ -522,7 +522,7 @@ pub mod pallet { Error::::UnwrapAmountExceedsAvaliableStake ); let active_stakes = Self::get_net_value(user.clone())?; - let locked = Self::get_election_lock(&user); + let locked = Self::get_lock(&user); ensure!( amount + locked <= active_stakes, Error::::UnwrapAmountExceedsAvaliableStake, @@ -800,7 +800,7 @@ pub mod pallet { matches!(vote_info, Some(ReferendumInfo::Ongoing(_))) } - fn get_election_lock(who: &T::AccountId) -> BalanceOf { + fn get_lock(who: &T::AccountId) -> BalanceOf { let lock = StakerAccounts::::get(who).map_or(Zero::zero(), |status| status.locked); let election_lock = ElectionLocks::::get(who); let election_reserve = ElectionReserves::::get(who); From a4fbbd97893de788068454663bc0a39b6c78eee1 Mon Sep 17 00:00:00 2001 From: Index0011 <105425941+Index0011@users.noreply.github.com> Date: Mon, 12 Jun 2023 16:10:56 +0800 Subject: [PATCH 08/12] Update pallets/phala/src/compute/wrapped_balances.rs Co-authored-by: h4x3rotab --- pallets/phala/src/compute/wrapped_balances.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index 8baeb3f047..a4189af0e9 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -96,6 +96,7 @@ pub mod pallet { #[pallet::getter(fn election_locks)] pub type ElectionLocks = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + /// The WPHA a user owes the system because of a lack of liquid token. Wills be settled by `slash_reserved()` in the future. #[pallet::storage] #[pallet::getter(fn slash_debts)] pub type SlashDebts = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; From 63865407bf055ec3d1923a7b18ce242e86aa1b47 Mon Sep 17 00:00:00 2001 From: Index0011 <105425941+Index0011@users.noreply.github.com> Date: Mon, 12 Jun 2023 16:12:02 +0800 Subject: [PATCH 09/12] Update pallets/phala/src/compute/wrapped_balances.rs Co-authored-by: h4x3rotab --- pallets/phala/src/compute/wrapped_balances.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index a4189af0e9..ed08074b20 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -329,7 +329,7 @@ pub mod pallet { *reserve -= actual; }); Self::burn_from(who, actual) - .expect("burn nft when slash reserved should success; qed."); + .expect("there are enough WPHA to burn; qed."); let imbalance = ::Currency::withdraw( &T::WrappedBalancesAccountId::get(), actual, From cf8163b72994c551dd707b2c409babd1a885140b Mon Sep 17 00:00:00 2001 From: Index0011 Date: Mon, 12 Jun 2023 09:05:37 +0000 Subject: [PATCH 10/12] response for pr --- pallets/phala/src/compute/stake_pool_v2.rs | 10 +-- pallets/phala/src/compute/vault.rs | 1 + pallets/phala/src/compute/wrapped_balances.rs | 78 ++++++++++--------- 3 files changed, 47 insertions(+), 42 deletions(-) diff --git a/pallets/phala/src/compute/stake_pool_v2.rs b/pallets/phala/src/compute/stake_pool_v2.rs index 45150410c2..cf89cccfc5 100644 --- a/pallets/phala/src/compute/stake_pool_v2.rs +++ b/pallets/phala/src/compute/stake_pool_v2.rs @@ -309,7 +309,7 @@ pub mod pallet { BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { /// Creates a new stake pool #[pallet::call_index(0)] @@ -984,7 +984,7 @@ pub mod pallet { BalanceOf: FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { pub fn do_start_computing( owner: &T::AccountId, @@ -1178,7 +1178,7 @@ pub mod pallet { BalanceOf: FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { /// Called when gk send new payout information. /// Append specific worker's reward balance of current round, @@ -1211,7 +1211,7 @@ pub mod pallet { BalanceOf: FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { fn on_unbound(worker: &WorkerPublicKey, _force: bool) { // Usually called on worker force unbinding (force == true), but it's also possible @@ -1233,7 +1233,7 @@ pub mod pallet { BalanceOf: FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { fn on_stopped( _worker: &WorkerPublicKey, diff --git a/pallets/phala/src/compute/vault.rs b/pallets/phala/src/compute/vault.rs index 9d5db6753d..40bb79a9ea 100644 --- a/pallets/phala/src/compute/vault.rs +++ b/pallets/phala/src/compute/vault.rs @@ -147,6 +147,7 @@ pub mod pallet { BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, + T: Config + pallet_elections_phragmen::Config, { /// Creates a new vault #[pallet::call_index(0)] diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index ed08074b20..0e03ef110e 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -94,16 +94,19 @@ pub mod pallet { #[pallet::storage] #[pallet::getter(fn election_locks)] - pub type ElectionLocks = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + pub type ElectionLocks = + StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; /// The WPHA a user owes the system because of a lack of liquid token. Wills be settled by `slash_reserved()` in the future. #[pallet::storage] #[pallet::getter(fn slash_debts)] - pub type SlashDebts = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + pub type SlashDebts = + StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; #[pallet::storage] #[pallet::getter(fn election_reserves)] - pub type ElectionReserves = StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; + pub type ElectionReserves = + StorageMap<_, Twox64Concat, T::AccountId, BalanceOf, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] @@ -136,7 +139,8 @@ pub mod pallet { ReserveSlashed { user: T::AccountId, slash: BalanceOf, - } + debt: BalanceOf, + }, } #[pallet::error] @@ -153,11 +157,9 @@ pub mod pallet { ReferendumOngoing, /// The Iteration exceed the max limitaion IterationsIsNotVaild, - - LockLargerThanTotalBalance, - + /// The amount of lock is larger than the total balances you owned LiquidityRestrictions, - + /// There is a debt to settle and before it is done you can not unwrap WPha to Pha WphaNotSettled, } @@ -313,23 +315,22 @@ pub mod pallet { return (NegativeImbalanceOf::::zero(), Zero::zero()); } let mut actual = value.min(ElectionReserves::::get(who)); - let free_wpha: BalanceOf = - as Inspect>::balance( - T::WPhaAssetId::get(), - who, - ); + let free_wpha: BalanceOf = as Inspect< + T::AccountId, + >>::balance(T::WPhaAssetId::get(), who); + let mut total_debt = SlashDebts::::get(who); if free_wpha < actual { let new_debt = actual - free_wpha; actual = free_wpha; SlashDebts::::mutate(who, |debt| { *debt += new_debt; + total_debt = *debt; }); } ElectionReserves::::mutate(who, |reserve| { *reserve -= actual; }); - Self::burn_from(who, actual) - .expect("there are enough WPHA to burn; qed."); + Self::burn_from(who, actual).expect("there are enough WPHA to burn; qed."); let imbalance = ::Currency::withdraw( &T::WrappedBalancesAccountId::get(), actual, @@ -337,9 +338,10 @@ pub mod pallet { ExistenceRequirement::AllowDeath, ) .expect("slash imbalance should success; qed."); - Self::deposit_event(Event::::ReserveSlashed{ + Self::deposit_event(Event::::ReserveSlashed { user: who.clone(), slash: actual, + debt: total_debt, }); (imbalance, value - actual) } @@ -367,13 +369,11 @@ pub mod pallet { amount: Self::Balance, _reasons: WithdrawReasons, ) { - if amount == Zero::zero() - || id != ::PalletId::get() - { + Self::ensure_lock_id_supported(id); + if amount == Zero::zero() { return; } - let actual = amount.min(Self::total_balance(who)); - ElectionLocks::::insert(who, actual); + ElectionLocks::::insert(who, amount); } fn extend_lock( id: LockIdentifier, @@ -381,18 +381,16 @@ pub mod pallet { amount: Self::Balance, _reasons: WithdrawReasons, ) { - if amount == Zero::zero() - || id != ::PalletId::get() - { - return; - } - let current_lock = ElectionLocks::::get(who); - let actual = (current_lock + amount).min(Self::total_balance(who)); + Self::ensure_lock_id_supported(id); + if amount == Zero::zero() { + return; + } ElectionLocks::::mutate(who, |locks| { - *locks += actual; + *locks += amount; }); } - fn remove_lock(_id: LockIdentifier, who: &T::AccountId) { + fn remove_lock(id: LockIdentifier, who: &T::AccountId) { + Self::ensure_lock_id_supported(id); ElectionLocks::::remove(who); } } @@ -455,10 +453,6 @@ pub mod pallet { #[frame_support::transactional] pub fn wrap(origin: OriginFor, amount: BalanceOf) -> DispatchResult { let user = ensure_signed(origin)?; - ensure!( - !SlashDebts::::contains_key(&user), - Error::::WphaNotSettled, - ); ::Currency::transfer( &user, &T::WrappedBalancesAccountId::get(), @@ -488,7 +482,7 @@ pub mod pallet { pub fn unwrap_all(origin: OriginFor) -> DispatchResult { let user = ensure_signed(origin)?; ensure!( - !SlashDebts::::contains_key(&user), + SlashDebts::::get(&user) > Zero::zero(), Error::::WphaNotSettled, ); let active_stakes = Self::get_net_value(user.clone())?; @@ -515,6 +509,10 @@ pub mod pallet { #[frame_support::transactional] pub fn unwrap(origin: OriginFor, amount: BalanceOf) -> DispatchResult { let user = ensure_signed(origin)?; + ensure!( + SlashDebts::::get(&user) > Zero::zero(), + Error::::WphaNotSettled, + ); let free_stakes: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), &user); @@ -648,7 +646,7 @@ pub mod pallet { let mut new_debt = Zero::zero(); if debt > free_wpha { new_debt = debt - free_wpha; - } + } let (imbalance, _) = Self::slash_reserved(&who, slash); T::OnSlashed::on_unbalanced(imbalance); if new_debt != Zero::zero() { @@ -664,7 +662,7 @@ pub mod pallet { BalanceOf: sp_runtime::traits::AtLeast32BitUnsigned + Copy + FixedPointConvert + Display, T: pallet_uniques::Config, T: pallet_assets::Config>, - T: Config + vault::Config, + T: Config + vault::Config + pallet_elections_phragmen::Config, { /// Gets W-PHA's asset id pub fn get_asset_id() -> u32 { @@ -807,5 +805,11 @@ pub mod pallet { let election_reserve = ElectionReserves::::get(who); lock.max(election_lock).max(election_reserve) } + + fn ensure_lock_id_supported(id: LockIdentifier) { + if id != ::PalletId::get() { + panic!("LockIdentifier is not supported."); + } + } } } From ad50152ab401a0db06c12d4a0e1bd39ff38dbd7d Mon Sep 17 00:00:00 2001 From: Index0011 Date: Wed, 14 Jun 2023 05:08:40 +0000 Subject: [PATCH 11/12] remove total_debt --- pallets/phala/src/compute/wrapped_balances.rs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index 0e03ef110e..de541ad741 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -139,7 +139,6 @@ pub mod pallet { ReserveSlashed { user: T::AccountId, slash: BalanceOf, - debt: BalanceOf, }, } @@ -318,13 +317,11 @@ pub mod pallet { let free_wpha: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), who); - let mut total_debt = SlashDebts::::get(who); if free_wpha < actual { let new_debt = actual - free_wpha; actual = free_wpha; SlashDebts::::mutate(who, |debt| { *debt += new_debt; - total_debt = *debt; }); } ElectionReserves::::mutate(who, |reserve| { @@ -341,7 +338,6 @@ pub mod pallet { Self::deposit_event(Event::::ReserveSlashed { user: who.clone(), slash: actual, - debt: total_debt, }); (imbalance, value - actual) } From 8479485b27400f467e5e33395360badb17cfef2d Mon Sep 17 00:00:00 2001 From: Index0011 Date: Thu, 15 Jun 2023 01:30:34 +0000 Subject: [PATCH 12/12] add new-debt --- pallets/phala/src/compute/wrapped_balances.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pallets/phala/src/compute/wrapped_balances.rs b/pallets/phala/src/compute/wrapped_balances.rs index d9b1db06ee..bfc7805ce8 100644 --- a/pallets/phala/src/compute/wrapped_balances.rs +++ b/pallets/phala/src/compute/wrapped_balances.rs @@ -142,6 +142,7 @@ pub mod pallet { ReserveSlashed { user: T::AccountId, slash: BalanceOf, + new_debt: BalanceOf, }, } @@ -320,8 +321,9 @@ pub mod pallet { let free_wpha: BalanceOf = as Inspect< T::AccountId, >>::balance(T::WPhaAssetId::get(), who); + let mut new_debt = Zero::zero(); if free_wpha < actual { - let new_debt = actual - free_wpha; + new_debt = actual - free_wpha; actual = free_wpha; SlashDebts::::mutate(who, |debt| { *debt += new_debt; @@ -341,6 +343,7 @@ pub mod pallet { Self::deposit_event(Event::::ReserveSlashed { user: who.clone(), slash: actual, + new_debt, }); (imbalance, value - actual) }