Skip to content

Commit

Permalink
feat: tx-pause and safe-mode pallets integration (#1388)
Browse files Browse the repository at this point in the history
* feat: tx-pause and safe-mode pallets integration

* config updated and safe-mode coupled to DappStaking via Notify

* overhead benchmark comment added

* overhead benchmark command added - typo

* Revert "overhead benchmark command added - typo"

This reverts commit 03d0f9a.

* Revert "overhead benchmark comment added"

This reverts commit 96a0520.

* todo comment added to use proper benchmarking in the future

* remove useless crate option

Co-authored-by: Ermal Kaleci <[email protected]>

* remove useless crate option

* DbWeight from frame_system::Config used

* RuntimeAdjustedWeights type to handle weights override

* remove WeightToFee mock

* Revert "RuntimeAdjustedWeights type to handle weights override"

This reverts commit 1f400a4.

* base_extrinsic get from RuntimeBlockWeights for WeightToFee

---------

Co-authored-by: Ermal Kaleci <[email protected]>
  • Loading branch information
ipapandinas and ermalkaleci authored Dec 5, 2024
1 parent 29b3bd6 commit 17fc034
Show file tree
Hide file tree
Showing 11 changed files with 528 additions and 325 deletions.
612 changes: 326 additions & 286 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ pallet-message-queue = { git = "https://github.com/paritytech/polkadot-sdk", bra
pallet-membership = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-collective = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-democracy = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-tx-pause = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }
pallet-safe-mode = { git = "https://github.com/paritytech/polkadot-sdk", branch = "stable2407", default-features = false }

# EVM & Ethereum
# (wasm)
Expand Down
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
8 changes: 8 additions & 0 deletions runtime/local/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,13 @@ pallet-insecure-randomness-collective-flip = { workspace = true }
pallet-membership = { workspace = true }
pallet-preimage = { workspace = true }
pallet-proxy = { workspace = true }
pallet-safe-mode = { workspace = true }
pallet-scheduler = { workspace = true }
pallet-sudo = { workspace = true }
pallet-timestamp = { workspace = true }
pallet-transaction-payment = { workspace = true }
pallet-treasury = { workspace = true }
pallet-tx-pause = { workspace = true }
pallet-utility = { workspace = true }
pallet-vesting = { workspace = true }
sp-api = { workspace = true }
Expand Down Expand Up @@ -160,6 +162,8 @@ std = [
"pallet-utility/std",
"pallet-vesting/std",
"pallet-proxy/std",
"pallet-safe-mode/std",
"pallet-tx-pause/std",
"sp-api/std",
"sp-block-builder/std",
"sp-consensus-aura/std",
Expand Down Expand Up @@ -222,9 +226,11 @@ runtime-benchmarks = [
"pallet-evm-precompile-dapp-staking/runtime-benchmarks",
"pallet-grandpa/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-safe-mode/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-static-price-provider/runtime-benchmarks",
"pallet-sudo/runtime-benchmarks",
"pallet-tx-pause/runtime-benchmarks",
"pallet-utility/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
]
Expand All @@ -248,11 +254,13 @@ try-runtime = [
"pallet-sudo/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-tx-pause/try-runtime",
"pallet-utility/try-runtime",
"pallet-vesting/try-runtime",
"pallet-unified-accounts/try-runtime",
"pallet-ethereum/try-runtime",
"pallet-assets/try-runtime",
"pallet-safe-mode/try-runtime",
"pallet-scheduler/try-runtime",
"pallet-proxy/try-runtime",
"pallet-preimage/try-runtime",
Expand Down
2 changes: 2 additions & 0 deletions runtime/local/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ pub fn default_config() -> serde_json::Value {
democracy: Default::default(),
treasury: Default::default(),
community_treasury: Default::default(),
safe_mode: Default::default(),
tx_pause: Default::default(),
};

serde_json::to_value(&config).expect("Could not build genesis config.")
Expand Down
68 changes: 59 additions & 9 deletions runtime/local/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,9 @@ use frame_support::{
traits::{
fungible::{Balanced, Credit, HoldConsideration},
tokens::{PayFromAccount, UnityAssetBalanceConversion},
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, EqualPrivilegeOnly, FindAuthor, Get,
InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, WithdrawReasons,
AsEnsureOriginWithArg, ConstU128, ConstU32, ConstU64, Contains, EqualPrivilegeOnly,
FindAuthor, Get, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize,
WithdrawReasons,
},
weights::{
constants::{ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND},
Expand All @@ -41,7 +42,7 @@ use frame_support::{
};
use frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot, EnsureSigned,
EnsureRoot, EnsureSigned, EnsureWithSuccess,
};
use pallet_ethereum::PostLogContent;
use pallet_evm::{FeeCalculator, GasWeightMapping, Runner};
Expand Down Expand Up @@ -72,10 +73,10 @@ use astar_primitives::{
governance::{
CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst,
EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee,
EnsureRootOrTwoThirdsCommunityCouncil, EnsureRootOrTwoThirdsMainCouncil,
EnsureRootOrTwoThirdsTechnicalCommittee, MainCouncilCollectiveInst,
MainCouncilMembershipInst, MainTreasuryInst, TechnicalCommitteeCollectiveInst,
TechnicalCommitteeMembershipInst,
EnsureRootOrHalfTechnicalCommittee, EnsureRootOrTwoThirdsCommunityCouncil,
EnsureRootOrTwoThirdsMainCouncil, EnsureRootOrTwoThirdsTechnicalCommittee,
MainCouncilCollectiveInst, MainCouncilMembershipInst, MainTreasuryInst,
TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst,
},
Address, AssetId, Balance, BlockNumber, Hash, Header, Nonce,
};
Expand Down Expand Up @@ -207,10 +208,9 @@ parameter_types! {
}

// Configure FRAME pallets to include in runtime.

impl frame_system::Config for Runtime {
/// The basic call filter to use in dispatchable.
type BaseCallFilter = frame_support::traits::Everything;
type BaseCallFilter = InsideBoth<SafeMode, TxPause>;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The maximum length of a block (in bytes).
Expand Down Expand Up @@ -1132,6 +1132,52 @@ impl pallet_collective_proxy::Config for Runtime {
type WeightInfo = pallet_collective_proxy::weights::SubstrateWeight<Runtime>;
}

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

impl pallet_safe_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type Currency = Balances;
type RuntimeHoldReason = RuntimeHoldReason;
type WhitelistedCalls = SafeModeWhitelistedCalls;
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<EnsureRootOrHalfTechnicalCommittee, AccountId, ConstU32<{ 5 * MINUTES }>>;
type ForceExtendOrigin =
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>;
}

impl pallet_tx_pause::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type UnpauseOrigin = EnsureRootOrHalfTechnicalCommittee;
type WhitelistedCalls = ();
type MaxNameLen = ConstU32<256>;
type WeightInfo = pallet_tx_pause::weights::SubstrateWeight<Runtime>;
}

construct_runtime!(
pub struct Runtime {
System: frame_system = 10,
Expand Down Expand Up @@ -1176,6 +1222,8 @@ 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,
}
);

Expand Down Expand Up @@ -1295,6 +1343,8 @@ mod benches {
[pallet_dapp_staking, DappStaking]
[pallet_inflation, Inflation]
[pallet_dynamic_evm_base_fee, DynamicEvmBaseFee]
[pallet_tx_pause, TxPause]
[pallet_safe_mode, SafeMode]
);
}

Expand Down
8 changes: 8 additions & 0 deletions runtime/shibuya/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,15 @@ pallet-migrations = { workspace = true }
pallet-multisig = { workspace = true }
pallet-preimage = { workspace = true }
pallet-proxy = { workspace = true }
pallet-safe-mode = { workspace = true }
pallet-scheduler = { workspace = true }
pallet-session = { workspace = true }
pallet-sudo = { workspace = true }
pallet-timestamp = { workspace = true }
pallet-transaction-payment = { workspace = true }
pallet-transaction-payment-rpc-runtime-api = { workspace = true }
pallet-treasury = { workspace = true }
pallet-tx-pause = { workspace = true }
pallet-utility = { workspace = true }
pallet-vesting = { workspace = true }
vesting-mbm = { workspace = true }
Expand Down Expand Up @@ -223,13 +225,15 @@ std = [
"pallet-preimage/std",
"pallet-price-aggregator/std",
"pallet-proxy/std",
"pallet-safe-mode/std",
"pallet-scheduler/std",
"pallet-session/std",
"pallet-sudo/std",
"pallet-timestamp/std",
"pallet-transaction-payment-rpc-runtime-api/std",
"pallet-transaction-payment/std",
"pallet-treasury/std",
"pallet-tx-pause/std",
"pallet-unified-accounts/std",
"pallet-utility/std",
"pallet-vesting/std",
Expand Down Expand Up @@ -306,10 +310,12 @@ runtime-benchmarks = [
"pallet-preimage/runtime-benchmarks",
"pallet-price-aggregator/runtime-benchmarks",
"pallet-proxy/runtime-benchmarks",
"pallet-safe-mode/runtime-benchmarks",
"pallet-scheduler/runtime-benchmarks",
"pallet-sudo/runtime-benchmarks",
"pallet-timestamp/runtime-benchmarks",
"pallet-treasury/runtime-benchmarks",
"pallet-tx-pause/runtime-benchmarks",
"pallet-unified-accounts/runtime-benchmarks",
"pallet-utility/runtime-benchmarks",
"pallet-vesting/runtime-benchmarks",
Expand Down Expand Up @@ -367,12 +373,14 @@ try-runtime = [
"pallet-preimage/try-runtime",
"pallet-price-aggregator/try-runtime",
"pallet-proxy/try-runtime",
"pallet-safe-mode/try-runtime",
"pallet-scheduler/try-runtime",
"pallet-session/try-runtime",
"pallet-sudo/try-runtime",
"pallet-timestamp/try-runtime",
"pallet-transaction-payment/try-runtime",
"pallet-treasury/try-runtime",
"pallet-tx-pause/try-runtime",
"pallet-unified-accounts/try-runtime",
"pallet-utility/try-runtime",
"pallet-vesting/try-runtime",
Expand Down
2 changes: 2 additions & 0 deletions runtime/shibuya/src/genesis_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,8 @@ pub fn default_config(para_id: u32) -> serde_json::Value {
democracy: Default::default(),
treasury: Default::default(),
community_treasury: Default::default(),
safe_mode: Default::default(),
tx_pause: Default::default(),
};

serde_json::to_value(&config).expect("Could not build genesis config.")
Expand Down
Loading

0 comments on commit 17fc034

Please sign in to comment.