Skip to content

Commit

Permalink
config updated and safe-mode coupled to DappStaking via Notify
Browse files Browse the repository at this point in the history
  • Loading branch information
ipapandinas committed Nov 28, 2024
1 parent ae9ea5d commit ac5d44b
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 79 deletions.
27 changes: 23 additions & 4 deletions pallets/dapp-staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ use frame_support::{
pallet_prelude::*,
traits::{
fungible::{Inspect as FunInspect, MutateFreeze as FunMutateFreeze},
StorageVersion,
SafeModeNotify, StorageVersion,
},
weights::Weight,
};
Expand Down Expand Up @@ -682,9 +682,7 @@ pub mod pallet {
#[pallet::weight(T::WeightInfo::maintenance_mode())]
pub fn maintenance_mode(origin: OriginFor<T>, enabled: bool) -> DispatchResult {
T::ManagerOrigin::ensure_origin(origin)?;
ActiveProtocolState::<T>::mutate(|state| state.maintenance = enabled);

Self::deposit_event(Event::<T>::MaintenanceMode { enabled });
Self::set_maintenance_mode(enabled);
Ok(())
}

Expand Down Expand Up @@ -2210,6 +2208,14 @@ pub mod pallet {
Ok(())
}

/// Internal function to transition the dApp staking protocol maintenance mode.
/// Ensure this method is **not exposed publicly** and is only used for legitimate maintenance mode transitions invoked by privileged or trusted logic,
/// such as `T::ManagerOrigin` or a safe-mode enter/exit notification.
fn set_maintenance_mode(enabled: bool) {
ActiveProtocolState::<T>::mutate(|state| state.maintenance = enabled);
Self::deposit_event(Event::<T>::MaintenanceMode { enabled });
}

/// Ensure the correctness of the state of this pallet.
#[cfg(any(feature = "try-runtime", test))]
pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> {
Expand Down Expand Up @@ -2470,4 +2476,17 @@ pub mod pallet {
Ok(())
}
}

/// Implementation of the `SafeModeNotify` trait for the `DappStaking` pallet.
/// This integration ensures that the dApp staking protocol transitions to and from
/// maintenance mode when the runtime enters or exits safe mode.
impl<T: Config> SafeModeNotify for Pallet<T> {
fn entered() {
Self::set_maintenance_mode(true);
}

fn exited() {
Self::set_maintenance_mode(false);
}
}
}
24 changes: 23 additions & 1 deletion pallets/dapp-staking/src/test/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use frame_support::{
error::BadOrigin,
traits::{
fungible::Unbalanced as FunUnbalanced, Currency, Get, OnFinalize, OnInitialize,
ReservableCurrency,
ReservableCurrency, SafeModeNotify,
},
BoundedVec,
};
Expand Down Expand Up @@ -185,6 +185,28 @@ fn maintenance_mode_call_filtering_works() {
})
}

#[test]
fn maintenance_safe_mode_entered_exited_works() {
ExtBuilder::default().build_and_execute(|| {
// Check that maintenance mode is disabled by default
assert!(!ActiveProtocolState::<Test>::get().maintenance);

// Call entered and check post-state and event
DappStaking::entered();
assert!(ActiveProtocolState::<Test>::get().maintenance);
System::assert_last_event(RuntimeEvent::DappStaking(Event::MaintenanceMode {
enabled: true,
}));

// Call exited and check post-state and event
DappStaking::exited();
assert!(!ActiveProtocolState::<Test>::get().maintenance);
System::assert_last_event(RuntimeEvent::DappStaking(Event::MaintenanceMode {
enabled: false,
}));
})
}

#[test]
fn on_initialize_is_noop_if_no_era_change() {
ExtBuilder::default().build_and_execute(|| {
Expand Down
52 changes: 16 additions & 36 deletions runtime/local/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,6 @@ use pallet_evm::{FeeCalculator, GasWeightMapping, Runner};
use pallet_evm_precompile_assets_erc20::AddressToAssetId;
use pallet_grandpa::{fg_primitives, AuthorityList as GrandpaAuthorityList};
use pallet_transaction_payment::{FungibleAdapter, Multiplier, TargetedFeeAdjustment};
use pallet_tx_pause::RuntimeCallNameOf;
use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen};
use sp_api::impl_runtime_apis;
use sp_core::{crypto::KeyTypeId, sr25519, ConstBool, OpaqueMetadata, H160, H256, U256};
Expand Down Expand Up @@ -1128,57 +1127,39 @@ impl pallet_collective_proxy::Config for Runtime {
type WeightInfo = pallet_collective_proxy::weights::SubstrateWeight<Runtime>;
}

parameter_types! {
pub const EnterDuration: BlockNumber = 10 * MINUTES;
pub const EnterDepositAmount: Option<Balance> = None;
pub const ExtendDuration: BlockNumber = 5 * MINUTES;
pub const ExtendDepositAmount: Option<Balance> = None;
pub const ReleaseDelay: Option<u32> = None;
}

/// Calls that can bypass the safe-mode pallet.
pub struct SafeModeWhitelistedCalls;
impl Contains<RuntimeCall> for SafeModeWhitelistedCalls {
fn contains(call: &RuntimeCall) -> bool {
match call {
RuntimeCall::Sudo(_)
// System and Timestamp are required for block production
| RuntimeCall::System(_)
RuntimeCall::System(_)
| RuntimeCall::Timestamp(_)
| RuntimeCall::SafeMode(_)
| RuntimeCall::Sudo(_)
| RuntimeCall::TxPause(_) => true,
_ => false,
}
}
}

/// Calls that cannot be paused by the tx-pause pallet.
pub struct TxPauseWhitelistedCalls;
/// All calls can be paused, except Sudo calls.
impl Contains<RuntimeCallNameOf<Runtime>> for TxPauseWhitelistedCalls {
fn contains(full_name: &pallet_tx_pause::RuntimeCallNameOf<Runtime>) -> bool {
matches!(full_name.0.as_slice(), b"Sudo")
}
}

impl pallet_safe_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RuntimeHoldReason = RuntimeHoldReason;
type WhitelistedCalls = SafeModeWhitelistedCalls;
type EnterDuration = EnterDuration;
type EnterDepositAmount = EnterDepositAmount;
type ExtendDuration = ExtendDuration;
type ExtendDepositAmount = ExtendDepositAmount;
// The 'Success' value below represents the number of blocks that the origin may induce safe mode
type EnterDuration = ConstU32<{ 5 * MINUTES }>;
type EnterDepositAmount = ();
type ExtendDuration = ConstU32<{ 2 * MINUTES }>;
type ExtendDepositAmount = ();
// The 'Success' values below represent the number of blocks that the origin may induce safe mode
type ForceEnterOrigin =
EnsureWithSuccess<EnsureRootOrAllTechnicalCommittee, AccountId, EnterDuration>;
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 5 * MINUTES }>>;
type ForceExtendOrigin =
EnsureWithSuccess<EnsureRootOrAllTechnicalCommittee, AccountId, ExtendDuration>;
type ForceExitOrigin = EnsureRootOrAllTechnicalCommittee;
type ForceDepositOrigin = EnsureRootOrAllTechnicalCommittee;
type ReleaseDelay = ReleaseDelay;
type Notify = ();
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 2 * MINUTES }>>;
type ForceExitOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ForceDepositOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ReleaseDelay = ();
type Notify = DappStaking;
type WeightInfo = pallet_safe_mode::weights::SubstrateWeight<Runtime>;
}

Expand All @@ -1187,7 +1168,7 @@ impl pallet_tx_pause::Config for Runtime {
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type UnpauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type WhitelistedCalls = TxPauseWhitelistedCalls;
type WhitelistedCalls = ();
type MaxNameLen = ConstU32<256>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}
Expand Down Expand Up @@ -1236,9 +1217,8 @@ construct_runtime!(
Treasury: pallet_treasury::<Instance1> = 107,
CommunityTreasury: pallet_treasury::<Instance2> = 108,
CollectiveProxy: pallet_collective_proxy = 109,

SafeMode: pallet_safe_mode = 130,
TxPause: pallet_tx_pause = 131,
SafeMode: pallet_safe_mode = 110,
TxPause: pallet_tx_pause = 111,
}
);

Expand Down
60 changes: 22 additions & 38 deletions runtime/shibuya/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@ use pallet_identity::legacy::IdentityInfo;
use pallet_transaction_payment::{
FeeDetails, Multiplier, RuntimeDispatchInfo, TargetedFeeAdjustment,
};
use pallet_tx_pause::RuntimeCallNameOf;
use parity_scale_codec::{Compact, Decode, Encode, MaxEncodedLen};
use polkadot_runtime_common::BlockHashCount;
use sp_api::impl_runtime_apis;
Expand Down Expand Up @@ -89,7 +88,8 @@ use astar_primitives::{
CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst,
EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee,
EnsureRootOrFourFifthsCommunityCouncil, EnsureRootOrHalfCommunityCouncil,
EnsureRootOrHalfMainCouncil, EnsureRootOrHalfTechnicalCommittee, MainCouncilCollectiveInst,
EnsureRootOrHalfMainCouncil, EnsureRootOrHalfTechnicalCommittee,
EnsureRootOrTwoThirdsTechnicalCommittee, MainCouncilCollectiveInst,
MainCouncilMembershipInst, MainTreasuryInst, OracleMembershipInst,
TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst,
},
Expand Down Expand Up @@ -249,7 +249,9 @@ parameter_types! {
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
// Adjusting the base extrinsic weight to account for the additional database
// read introduced by the `tx-pause` pallet during extrinsic filtering.
weights.base_extrinsic = ExtrinsicBaseWeight::get().saturating_add(RocksDbWeight::get().reads(1));
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
Expand Down Expand Up @@ -1539,57 +1541,40 @@ impl pallet_migrations::Config for Runtime {
type WeightInfo = pallet_migrations::weights::SubstrateWeight<Runtime>;
}

parameter_types! {
pub const EnterDuration: BlockNumber = 4 * HOURS;
pub const EnterDepositAmount: Option<Balance> = None;
pub const ExtendDuration: BlockNumber = 2 * HOURS;
pub const ExtendDepositAmount: Option<Balance> = None;
pub const ReleaseDelay: Option<u32> = None;
}

/// Calls that can bypass the safe-mode pallet.
pub struct SafeModeWhitelistedCalls;
impl Contains<RuntimeCall> for SafeModeWhitelistedCalls {
fn contains(call: &RuntimeCall) -> bool {
match call {
RuntimeCall::Sudo(_)
// System and Timestamp are required for block production
| RuntimeCall::System(_)
RuntimeCall::System(_)
| RuntimeCall::Timestamp(_)
| RuntimeCall::SafeMode(_)
| RuntimeCall::ParachainSystem(_)
| RuntimeCall::Sudo(_)
| RuntimeCall::TxPause(_) => true,
_ => false,
}
}
}

/// Calls that cannot be paused by the tx-pause pallet.
pub struct TxPauseWhitelistedCalls;
/// All calls can be paused, except Sudo calls.
impl Contains<RuntimeCallNameOf<Runtime>> for TxPauseWhitelistedCalls {
fn contains(full_name: &pallet_tx_pause::RuntimeCallNameOf<Runtime>) -> bool {
matches!(full_name.0.as_slice(), b"Sudo")
}
}

impl pallet_safe_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RuntimeHoldReason = RuntimeHoldReason;
type WhitelistedCalls = SafeModeWhitelistedCalls;
type EnterDuration = EnterDuration;
type EnterDepositAmount = EnterDepositAmount;
type ExtendDuration = ExtendDuration;
type ExtendDepositAmount = ExtendDepositAmount;
// The 'Success' value below represents the number of blocks that the origin may induce safe mode
type EnterDuration = ConstU32<{ 4 * HOURS }>;
type EnterDepositAmount = ();
type ExtendDuration = ConstU32<{ 2 * HOURS }>;
type ExtendDepositAmount = ();
// The 'Success' values below represent the number of blocks that the origin may induce safe mode
type ForceEnterOrigin =
EnsureWithSuccess<EnsureRootOrAllTechnicalCommittee, AccountId, EnterDuration>;
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 4 * HOURS }>>;
type ForceExtendOrigin =
EnsureWithSuccess<EnsureRootOrAllTechnicalCommittee, AccountId, ExtendDuration>;
type ForceExitOrigin = EnsureRootOrAllTechnicalCommittee;
type ForceDepositOrigin = EnsureRootOrAllTechnicalCommittee;
type ReleaseDelay = ReleaseDelay;
type Notify = ();
EnsureWithSuccess<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 2 * HOURS }>>;
type ForceExitOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ForceDepositOrigin = EnsureRootOrTwoThirdsTechnicalCommittee;
type ReleaseDelay = ();
type Notify = DappStaking;
type WeightInfo = pallet_safe_mode::weights::SubstrateWeight<Runtime>;
}

Expand All @@ -1598,7 +1583,7 @@ impl pallet_tx_pause::Config for Runtime {
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type UnpauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type WhitelistedCalls = TxPauseWhitelistedCalls;
type WhitelistedCalls = ();
type MaxNameLen = ConstU32<256>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}
Expand Down Expand Up @@ -1675,12 +1660,11 @@ construct_runtime!(
Treasury: pallet_treasury::<Instance1> = 107,
CommunityTreasury: pallet_treasury::<Instance2> = 108,
CollectiveProxy: pallet_collective_proxy = 109,
SafeMode: pallet_safe_mode = 110,
TxPause: pallet_tx_pause = 111,

MultiBlockMigrations: pallet_migrations = 120,

SafeMode: pallet_safe_mode = 130,
TxPause: pallet_tx_pause = 131,

#[cfg(feature = "runtime-benchmarks")]
VestingMBM: vesting_mbm = 250,
}
Expand Down

0 comments on commit ac5d44b

Please sign in to comment.