rustfmt casper runtime and fix typos

Signed-off-by: Uncle Stretch <uncle.stretch@ghostchain.io>
This commit is contained in:
Uncle Stretch 2025-07-29 14:51:15 +03:00
parent 48ff511685
commit 8d69e5c87e
Signed by: str3tch
GPG Key ID: 84F3190747EE79AA
14 changed files with 897 additions and 830 deletions

View File

@ -1,6 +1,6 @@
[package] [package]
name = "casper-runtime" name = "casper-runtime"
version = "3.5.28" version = "3.5.29"
build = "build.rs" build = "build.rs"
description = "Runtime of the Casper Network" description = "Runtime of the Casper Network"
edition.workspace = true edition.workspace = true

View File

@ -86,7 +86,7 @@ pub mod fee {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::{ use super::{
currency::{STNK, STRH, CSPR}, currency::{CSPR, STNK, STRH},
fee::WeightToFee, fee::WeightToFee,
}; };
use crate::weights::ExtrinsicBaseWeight; use crate::weights::ExtrinsicBaseWeight;

View File

@ -1,9 +1,9 @@
pub mod block_weights; pub mod block_weights;
pub mod extrinsic_weights; pub mod extrinsic_weights;
pub mod rocksdb_weights;
pub mod paritydb_weights; pub mod paritydb_weights;
pub mod rocksdb_weights;
pub use block_weights::BlockExecutionWeight; pub use block_weights::BlockExecutionWeight;
pub use extrinsic_weights::ExtrinsicBaseWeight; pub use extrinsic_weights::ExtrinsicBaseWeight;
pub use rocksdb_weights::constants::RocksDbWeight;
pub use paritydb_weights::constants::ParityDbWeight; pub use paritydb_weights::constants::ParityDbWeight;
pub use rocksdb_weights::constants::RocksDbWeight;

View File

@ -1,4 +1,3 @@
//! Autogenerated bag thresholds. //! Autogenerated bag thresholds.
//! //!
//! Generated on 2024-06-30T17:36:29.986756974+00:00 //! Generated on 2024-06-30T17:36:29.986756974+00:00

View File

@ -2,25 +2,34 @@ use super::*;
use frame_support::{ use frame_support::{
parameter_types, parameter_types,
traits::{ traits::{
EitherOf, EitherOfDiverse, MapSuccess, OriginTrait, TryWithMorphedArg, tokens::pay::PayFromAccount, EitherOf, EitherOfDiverse, MapSuccess, OriginTrait,
tokens::pay::PayFromAccount, TryWithMorphedArg,
}, },
}; };
use frame_system::EnsureRootWithSuccess; use frame_system::EnsureRootWithSuccess;
use pallet_ranked_collective::EnsureOfRank;
use sp_core::{ConstU128, ConstU32}; use sp_core::{ConstU128, ConstU32};
use sp_runtime::traits::{ConstU16, TakeFirst}; use sp_runtime::traits::{ConstU16, TakeFirst};
use pallet_ranked_collective::EnsureOfRank;
use crate::{ use crate::{
AccountId,
Balance,
Balances,
Preimage,
Runtime,
// weights, // weights,
RuntimeCall, RuntimeEvent, Scheduler, DAYS, CSPR, AccountId, Balance, RuntimeCall,
TreasuryAccount, Balances, Preimage, Runtime, RuntimeEvent,
Scheduler,
TreasuryAccount,
CSPR,
DAYS,
}; };
mod origins; mod origins;
pub use origins::{ pub use origins::{
pallet_cult_origins, Geniuses, Degens, Zombies, Skeletons, Ghosts, pallet_cult_origins, CultTreasurySpender, Degens, EnsureCanPromoteTo, EnsureCanRetainAt,
EnsureCanRetainAt, EnsureCanPromoteTo, EnsureCult, ToVoice, CultTreasurySpender, EnsureCult, Geniuses, Ghosts, Skeletons, ToVoice, Zombies,
}; };
mod tracks; mod tracks;
@ -45,14 +54,10 @@ parameter_types! {
impl pallet_whitelist::Config for Runtime { impl pallet_whitelist::Config for Runtime {
type RuntimeCall = RuntimeCall; type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type WhitelistOrigin = EitherOfDiverse< type WhitelistOrigin =
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, EitherOfDiverse<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Skeletons>;
Skeletons, type DispatchWhitelistedOrigin =
>; EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Geniuses>;
type DispatchWhitelistedOrigin = EitherOf<
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Geniuses,
>;
type Preimages = Preimage; type Preimages = Preimage;
type WeightInfo = weights::pallet_whitelist::WeightInfo<Runtime>; type WeightInfo = weights::pallet_whitelist::WeightInfo<Runtime>;
} }
@ -81,7 +86,7 @@ impl pallet_referenda::Config<CultReferendaInstance> for Runtime {
(AccountId, u16), (AccountId, u16),
>, >,
TakeFirst, TakeFirst,
> >,
>; >;
type CancelOrigin = Skeletons; type CancelOrigin = Skeletons;
type KillOrigin = Ghosts; type KillOrigin = Ghosts;
@ -135,10 +140,13 @@ impl pallet_core_fellowship::Config<CultCoreInstance> for Runtime {
type Members = pallet_ranked_collective::Pallet<Runtime, CultCollectiveInstance>; type Members = pallet_ranked_collective::Pallet<Runtime, CultCollectiveInstance>;
type Balance = Balance; type Balance = Balance;
type ParamsOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Skeletons>; type ParamsOrigin =
EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Skeletons>;
type InductOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>; type InductOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>;
type ApproveOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, EnsureCanRetainAt>; type ApproveOrigin =
type PromoteOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, EnsureCanPromoteTo>; EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, EnsureCanRetainAt>;
type PromoteOrigin =
EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, EnsureCanPromoteTo>;
type EvidenceSize = ConstU32<65536>; type EvidenceSize = ConstU32<65536>;
} }

View File

@ -5,8 +5,8 @@ pub use pallet_cult_origins::*;
#[frame_support::pallet] #[frame_support::pallet]
pub mod pallet_cult_origins { pub mod pallet_cult_origins {
use crate::{Balance, CSPR};
use super::ranks; use super::ranks;
use crate::{Balance, CSPR};
use frame_support::pallet_prelude::*; use frame_support::pallet_prelude::*;
use pallet_ranked_collective::Rank; use pallet_ranked_collective::Rank;

View File

@ -1,4 +1,4 @@
use crate::{Balance, BlockNumber, RuntimeOrigin, DAYS, CSPR, HOURS, MINUTES}; use crate::{Balance, BlockNumber, RuntimeOrigin, CSPR, DAYS, HOURS, MINUTES};
use pallet_ranked_collective::Rank; use pallet_ranked_collective::Rank;
use sp_runtime::{traits::Convert, Perbill}; use sp_runtime::{traits::Convert, Perbill};
@ -255,7 +255,6 @@ const TRACKS_DATA: [(u16, pallet_referenda::TrackInfo<Balance, BlockNumber>); 15
min_support: RETAIN_MIN_SUPPORT, min_support: RETAIN_MIN_SUPPORT,
}, },
), ),
( (
constants::PROMOTE_TO_GENIUSES, constants::PROMOTE_TO_GENIUSES,
pallet_referenda::TrackInfo { pallet_referenda::TrackInfo {
@ -347,7 +346,7 @@ impl pallet_referenda::TracksInfo<Balance, BlockNumber> for TracksInfo {
// It is important that this is NOT availiable in production! // It is important that this is NOT availiable in production!
let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into(); let root: Self::RuntimeOrigin = frame_system::RawOrigin::Root.into();
if &root == id { if &root == id {
return Ok(tracks::GHOSTS) return Ok(tracks::GHOSTS);
} }
} }

View File

@ -3,20 +3,20 @@ use pallet_staking::Forcing;
use sp_staking::StakerStatus; use sp_staking::StakerStatus;
use crate::{opaque::SessionKeys, BABE_GENESIS_EPOCH_CONFIG}; use crate::{opaque::SessionKeys, BABE_GENESIS_EPOCH_CONFIG};
use primitives::{AccountId, AccountPublic};
use casper_runtime_constants::currency::CSPR; use casper_runtime_constants::currency::CSPR;
use primitives::{AccountId, AccountPublic};
use ghost_slow_clap::sr25519::AuthorityId as SlowClapId;
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use babe_primitives::AuthorityId as BabeId; use babe_primitives::AuthorityId as BabeId;
use ghost_slow_clap::sr25519::AuthorityId as SlowClapId;
use grandpa_primitives::AuthorityId as GrandpaId; use grandpa_primitives::AuthorityId as GrandpaId;
use sp_core::{sr25519, Pair, Public};
use sp_runtime::{traits::IdentifyAccount, Perbill};
#[cfg(not(feature = "std"))] #[cfg(not(feature = "std"))]
use sp_std::alloc::format; use sp_std::alloc::format;
use sp_std::vec::Vec;
use sp_std::prelude::*; use sp_std::prelude::*;
use sp_core::{sr25519, Pair, Public}; use sp_std::vec::Vec;
use sp_runtime::{Perbill, traits::IdentifyAccount};
#[derive(Encode, Clone)] #[derive(Encode, Clone)]
struct PreparedNetworkData { struct PreparedNetworkData {
@ -84,40 +84,69 @@ fn casper_testnet_accounts() -> Vec<AccountId> {
fn casper_testnet_evm_accounts() -> Vec<(AccountId, u128, u8)> { fn casper_testnet_evm_accounts() -> Vec<(AccountId, u128, u8)> {
vec![ vec![
// 01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198 // 01c928771aea942a1e7ac06adf2b73dfbc9a25d9eaa516e3673116af7f345198
(get_account_id_from_seed::<sr25519::Public>("1A69d2D5568D1878023EeB121a73d33B9116A760"), 1337 * CSPR, 1), (
get_account_id_from_seed::<sr25519::Public>("1A69d2D5568D1878023EeB121a73d33B9116A760"),
1337 * CSPR,
1,
),
// b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139 // b19a435901872f817185f7234a1484eae837613f9d10cf21927a23c2d8cb9139
(get_account_id_from_seed::<sr25519::Public>("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"), 1337 * CSPR, 2), (
get_account_id_from_seed::<sr25519::Public>("2f86cfBED3fbc1eCf2989B9aE5fc019a837A9C12"),
1337 * CSPR,
2,
),
// d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc // d3baf57b74d65719b2dc33f5a464176022d0cc5edbca002234229f3e733875fc
(get_account_id_from_seed::<sr25519::Public>("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"), 69 * CSPR, 3), (
get_account_id_from_seed::<sr25519::Public>("e83f67361Ac74D42A48E2DAfb6706eb047D8218D"),
69 * CSPR,
3,
),
// c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4 // c4683d566436af6b58b4a59c8f501319226e85b21869bf93d5eeb4596d4791d4
(get_account_id_from_seed::<sr25519::Public>("827ee4ad9b259b6fa1390ed60921508c78befd63"), 69 * CSPR, 4), (
get_account_id_from_seed::<sr25519::Public>("827ee4ad9b259b6fa1390ed60921508c78befd63"),
69 * CSPR,
4,
),
] ]
} }
fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> { fn casper_testnet_evm_networks() -> Vec<(u32, Vec<u8>)> {
vec![ vec![
(1, PreparedNetworkData { (
1,
PreparedNetworkData {
chain_name: "ethereum-mainnet".into(), chain_name: "ethereum-mainnet".into(),
default_endpoint: "https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(), default_endpoint:
"https://nd-422-757-666.p2pify.com/0a9d79d93fb2f4a4b1e04695da2b77a7/".into(),
finality_delay: Some(40), finality_delay: Some(40),
release_delay: Some(80), release_delay: Some(80),
network_type: Default::default(), network_type: Default::default(),
gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(), gatekeeper: "0x4d224452801aced8b2f0aebe155379bb5d594381".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(), topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
.into(),
incoming_fee: 0, incoming_fee: 0,
outgoing_fee: 0, outgoing_fee: 0,
}.encode()), }
(56, PreparedNetworkData { .encode(),
),
(
56,
PreparedNetworkData {
chain_name: "bnb-mainnet".into(), chain_name: "bnb-mainnet".into(),
default_endpoint: "https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/".into(), default_endpoint:
"https://bsc-mainnet.core.chainstack.com/35848e183f3e3303c8cfeacbea831cab/"
.into(),
finality_delay: Some(20), finality_delay: Some(20),
release_delay: Some(40), release_delay: Some(40),
network_type: Default::default(), network_type: Default::default(),
gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(), gatekeeper: "0x0E09FaBB73Bd3Ade0a17ECC321fD13a19e81cE82".into(),
topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef".into(), topic_name: "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef"
.into(),
incoming_fee: 0, incoming_fee: 0,
outgoing_fee: 0, outgoing_fee: 0,
}.encode()) }
.encode(),
),
] ]
} }
@ -127,7 +156,12 @@ fn casper_session_keys(
authority_discovery: AuthorityDiscoveryId, authority_discovery: AuthorityDiscoveryId,
slow_clap: SlowClapId, slow_clap: SlowClapId,
) -> SessionKeys { ) -> SessionKeys {
SessionKeys { babe, grandpa, authority_discovery, slow_clap } SessionKeys {
babe,
grandpa,
authority_discovery,
slow_clap,
}
} }
fn testnet_config_genesis( fn testnet_config_genesis(
@ -143,8 +177,7 @@ fn testnet_config_genesis(
ghost_accounts: Option<Vec<(AccountId, u128, u8)>>, ghost_accounts: Option<Vec<(AccountId, u128, u8)>>,
evm_networks: Option<Vec<(u32, Vec<u8>)>>, evm_networks: Option<Vec<(u32, Vec<u8>)>>,
) -> serde_json::Value { ) -> serde_json::Value {
let endowed_accounts: Vec<AccountId> = let endowed_accounts: Vec<AccountId> = endowed_accounts.unwrap_or_else(casper_testnet_accounts);
endowed_accounts.unwrap_or_else(casper_testnet_accounts);
let ghost_accounts: Vec<(AccountId, u128, u8)> = let ghost_accounts: Vec<(AccountId, u128, u8)> =
ghost_accounts.unwrap_or_else(casper_testnet_evm_accounts); ghost_accounts.unwrap_or_else(casper_testnet_evm_accounts);
@ -218,7 +251,9 @@ fn testnet_config_genesis(
fn casper_development_config_genesis() -> serde_json::Value { fn casper_development_config_genesis() -> serde_json::Value {
testnet_config_genesis( testnet_config_genesis(
vec![get_authority_keys_from_seed("Alice")], vec![get_authority_keys_from_seed("Alice")],
None, None, None, None,
None,
None,
) )
} }
@ -229,7 +264,9 @@ fn casper_local_config_genesis() -> serde_json::Value {
get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Alice"),
get_authority_keys_from_seed("Bob"), get_authority_keys_from_seed("Bob"),
], ],
None, None, None, None,
None,
None,
) )
} }
@ -240,9 +277,11 @@ pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option<sp_std::vec::Vec<
Ok("local_testnet") => casper_local_config_genesis(), Ok("local_testnet") => casper_local_config_genesis(),
_ => return None, _ => return None,
}; };
Some(serde_json::to_string(&patch) Some(
serde_json::to_string(&patch)
.expect("serialization to json is expected to work; qed") .expect("serialization to json is expected to work; qed")
.into_bytes()) .into_bytes(),
)
} }
/// Returns a list of identifiers for available builtin `RuntimeGenesisConfig` presets. /// Returns a list of identifiers for available builtin `RuntimeGenesisConfig` presets.

View File

@ -1,8 +1,5 @@
use super::*; use super::*;
use frame_support::{ use frame_support::{dispatch::DispatchResultWithPostInfo, traits::PrivilegeCmp};
dispatch::DispatchResultWithPostInfo,
traits::PrivilegeCmp,
};
use pallet_alliance::{ProposalIndex, ProposalProvider}; use pallet_alliance::{ProposalIndex, ProposalProvider};
use sp_runtime::DispatchError; use sp_runtime::DispatchError;
use sp_std::{cmp::Ordering, marker::PhantomData}; use sp_std::{cmp::Ordering, marker::PhantomData};
@ -14,7 +11,8 @@ type HashOf<T> = <T as frame_system::Config>::Hash;
/// Proposal provider for alliance pallet. /// Proposal provider for alliance pallet.
/// Adapter from collective pallet to alliance proposal provider trait. /// Adapter from collective pallet to alliance proposal provider trait.
pub struct AllianceProposalProvider<T, I = ()>(PhantomData<(T, I)>); pub struct AllianceProposalProvider<T, I = ()>(PhantomData<(T, I)>);
impl <T, I> ProposalProvider<AccountIdOf<T>, HashOf<T>, ProposalOf<T, I>> for AllianceProposalProvider<T, I> impl<T, I> ProposalProvider<AccountIdOf<T>, HashOf<T>, ProposalOf<T, I>>
for AllianceProposalProvider<T, I>
where where
T: pallet_collective::Config<I> + frame_system::Config, T: pallet_collective::Config<I> + frame_system::Config,
I: 'static, I: 'static,
@ -25,7 +23,12 @@ where
proposal: Box<ProposalOf<T, I>>, proposal: Box<ProposalOf<T, I>>,
length_bound: u32, length_bound: u32,
) -> Result<(u32, u32), DispatchError> { ) -> Result<(u32, u32), DispatchError> {
pallet_collective::Pallet::<T, I>::do_propose_proposed(who, threshold, proposal, length_bound) pallet_collective::Pallet::<T, I>::do_propose_proposed(
who,
threshold,
proposal,
length_bound,
)
} }
fn vote_proposal( fn vote_proposal(
@ -61,7 +64,7 @@ pub struct EqualOrGreatestRootCmp;
impl PrivilegeCmp<OriginCaller> for EqualOrGreatestRootCmp { impl PrivilegeCmp<OriginCaller> for EqualOrGreatestRootCmp {
fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> { fn cmp_privilege(left: &OriginCaller, right: &OriginCaller) -> Option<Ordering> {
if left == right { if left == right {
return Some(Ordering::Equal) return Some(Ordering::Equal);
} }
match (left, right) { match (left, right) {

View File

@ -1,63 +1,59 @@
#![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase // `construct_runtime!` does a lot of recursion and requires us to increase
// the limit to 256 // the limit to 256
#![recursion_limit = "256"] #![recursion_limit = "256"]
use frame_system::{EnsureRoot, EnsureRootWithSuccess};
use runtime_common::{
impls::DealWithFees, BlockHashCount, BlockLength, CurrencyToVote,
SlowAdjustingFeeUpdate, impl_runtime_weights, prod_or_fast,
};
use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId; use authority_discovery_primitives::AuthorityId as AuthorityDiscoveryId;
use frame_election_provider_support::{ use frame_election_provider_support::{
generate_solution_type, onchain, SequentialPhragmen, bounds::ElectionBoundsBuilder, generate_solution_type, onchain, SequentialPhragmen,
bounds::ElectionBoundsBuilder,
}; };
use frame_support::{ use frame_support::{
construct_runtime, parameter_types, construct_runtime,
genesis_builder_helper::{build_state, get_preset}, genesis_builder_helper::{build_state, get_preset},
parameter_types,
traits::{ traits::{
fungible::HoldConsideration, fungible::HoldConsideration, tokens::UnityAssetBalanceConversion, ConstU128, ConstU32,
tokens::UnityAssetBalanceConversion, EitherOf, EitherOfDiverse, InstanceFilter, KeyOwnerProofSystem, LinearStoragePrice,
ConstU128, ConstU32, EitherOf, EitherOfDiverse, InstanceFilter, WithdrawReasons,
KeyOwnerProofSystem, LinearStoragePrice, WithdrawReasons,
}, },
weights::ConstantMultiplier, PalletId weights::ConstantMultiplier,
PalletId,
};
use frame_system::{EnsureRoot, EnsureRootWithSuccess};
use runtime_common::{
impl_runtime_weights, impls::DealWithFees, prod_or_fast, BlockHashCount, BlockLength,
CurrencyToVote, SlowAdjustingFeeUpdate,
}; };
use frame_support::traits::tokens::pay::PayFromAccount;
#[cfg(feature = "runtime-benchmarks")] #[cfg(feature = "runtime-benchmarks")]
use runtime_common::benchmarking::BenchmarkTreasuryHelper; use runtime_common::benchmarking::BenchmarkTreasuryHelper;
use frame_support::traits::tokens::pay::PayFromAccount;
use pallet_transaction_payment::FungibleAdapter; use codec::{Decode, Encode, MaxEncodedLen};
use ghost_slow_clap::sr25519::AuthorityId as SlowClapId;
use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId};
use pallet_identity::legacy::IdentityInfo; use pallet_identity::legacy::IdentityInfo;
use ghost_slow_clap::sr25519::AuthorityId as SlowClapId;
use pallet_session::historical as session_historical; use pallet_session::historical as session_historical;
use pallet_transaction_payment::FungibleAdapter;
use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo};
use codec::{Decode, Encode, MaxEncodedLen};
use primitives::{ use primitives::{
AccountId, AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce, AccountId, AccountIndex, Balance, BlockNumber, Hash, Moment, Nonce, ReserveIdentifier,
Signature, ReserveIdentifier, Signature,
}; };
use sp_core::OpaqueMetadata; use sp_core::OpaqueMetadata;
use sp_runtime::{
create_runtime_str, generic, impl_opaque_keys, FixedU128,
curve::PiecewiseLinear,
traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, Extrinsic as ExtrinsicT,
OpaqueKeys, SaturatedConversion, Verify, IdentityLookup, ConvertInto,
ConstU16,
},
transaction_validity::{
TransactionPriority, TransactionSource, TransactionValidity,
},
ApplyExtrinsicResult, KeyTypeId, Perbill, Percent, Permill,
RuntimeDebug,
};
use sp_genesis_builder::PresetId; use sp_genesis_builder::PresetId;
use sp_runtime::{
create_runtime_str,
curve::PiecewiseLinear,
generic, impl_opaque_keys,
traits::{
AccountIdLookup, BlakeTwo256, Block as BlockT, ConstU16, ConvertInto,
Extrinsic as ExtrinsicT, IdentityLookup, OpaqueKeys, SaturatedConversion, Verify,
},
transaction_validity::{TransactionPriority, TransactionSource, TransactionValidity},
ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, RuntimeDebug,
};
use sp_std::prelude::*; use sp_std::prelude::*;
#[cfg(any(feature = "std", test))] #[cfg(any(feature = "std", test))]
use sp_version::NativeVersion; use sp_version::NativeVersion;
@ -75,20 +71,20 @@ pub use pallet_timestamp::Call as TimestampCall;
pub use sp_runtime::BuildStorage; pub use sp_runtime::BuildStorage;
/// Constant values used within the runtime. /// Constant values used within the runtime.
use casper_runtime_constants::{currency::*, time::*, fee::*}; use casper_runtime_constants::{currency::*, fee::*, time::*};
mod weights;
mod bag_thresholds; mod bag_thresholds;
mod impls;
mod genesis_config_presets; mod genesis_config_presets;
mod impls;
mod weights;
pub use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp}; pub use impls::{AllianceProposalProvider, EqualOrGreatestRootCmp};
// Governance configuration. // Governance configuration.
pub mod cult; pub mod cult;
use cult::{ use cult::{
pallet_cult_origins, CultCollectiveInstance, CultTreasurySpender, pallet_cult_origins, CultCollectiveInstance, CultTreasurySpender, Degens, Geniuses, Ghosts,
Geniuses, Degens, Zombies, Skeletons, Ghosts, Skeletons, Zombies,
}; };
pub const LOG_TARGET: &str = "runtime::casper"; pub const LOG_TARGET: &str = "runtime::casper";
@ -422,10 +418,12 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
type SignedMaxSubmissions = SignedMaxSubmissions; type SignedMaxSubmissions = SignedMaxSubmissions;
type SignedMaxRefunds = SignedMaxRefunds; type SignedMaxRefunds = SignedMaxRefunds;
type SignedRewardBase = SignedRewardBase; type SignedRewardBase = SignedRewardBase;
type SignedDepositBase = GeometricDepositBase<Balance, SignedFixedDeposit, SignedDepositIncreaseFactor>; type SignedDepositBase =
GeometricDepositBase<Balance, SignedFixedDeposit, SignedDepositIncreaseFactor>;
type SignedDepositByte = SignedDepositByte; type SignedDepositByte = SignedDepositByte;
type SignedDepositWeight = (); type SignedDepositWeight = ();
type SignedMaxWeight = <Self::MinerConfig as pallet_election_provider_multi_phase::MinerConfig>::MaxWeight; type SignedMaxWeight =
<Self::MinerConfig as pallet_election_provider_multi_phase::MinerConfig>::MaxWeight;
type MinerConfig = Self; type MinerConfig = Self;
type SlashHandler = (); type SlashHandler = ();
type RewardHandler = (); type RewardHandler = ();
@ -449,10 +447,7 @@ impl pallet_election_provider_multi_phase::Config for Runtime {
(), (),
>; >;
type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig; type BenchmarkingConfig = runtime_common::elections::BenchmarkConfig;
type ForceOrigin = EitherOf< type ForceOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Zombies,
>;
type MaxWinners = MaxActiveValidators; type MaxWinners = MaxActiveValidators;
type ElectionBounds = ElectionBounds; type ElectionBounds = ElectionBounds;
type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Runtime>; type WeightInfo = weights::pallet_election_provider_multi_phase::WeightInfo<Runtime>;
@ -508,10 +503,7 @@ impl pallet_staking::Config for Runtime {
type SessionsPerEra = SessionsPerEra; type SessionsPerEra = SessionsPerEra;
type BondingDuration = BondingDuration; type BondingDuration = BondingDuration;
type SlashDeferDuration = SlashDeferDuration; type SlashDeferDuration = SlashDeferDuration;
type AdminOrigin = EitherOf< type AdminOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Skeletons>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Skeletons,
>;
type SessionInterface = Self; type SessionInterface = Self;
type EraPayout = pallet_staking::ConvertCurve<RewardCurve>; type EraPayout = pallet_staking::ConvertCurve<RewardCurve>;
type MaxExposurePageSize = MaxExposurePageSize; type MaxExposurePageSize = MaxExposurePageSize;
@ -535,10 +527,7 @@ impl pallet_fast_unstake::Config for Runtime {
type Currency = Balances; type Currency = Balances;
type BatchSize = frame_support::traits::ConstU32<16>; type BatchSize = frame_support::traits::ConstU32<16>;
type Deposit = ConstU128<{ STRH }>; type Deposit = ConstU128<{ STRH }>;
type ControlOrigin = EitherOf< type ControlOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Zombies,
>;
type Staking = Staking; type Staking = Staking;
type MaxErasToCheckPerBlock = ConstU32<1>; type MaxErasToCheckPerBlock = ConstU32<1>;
type WeightInfo = weights::pallet_fast_unstake::WeightInfo<Runtime>; type WeightInfo = weights::pallet_fast_unstake::WeightInfo<Runtime>;
@ -599,10 +588,7 @@ impl pallet_treasury::Config for Runtime {
type ApproveOrigin = frame_support::traits::NeverEnsureOrigin<Balance>; type ApproveOrigin = frame_support::traits::NeverEnsureOrigin<Balance>;
#[cfg(feature = "runtime-benchmarks")] #[cfg(feature = "runtime-benchmarks")]
type ApproveOrigin = EnsureRoot<Self::AccountId>; type ApproveOrigin = EnsureRoot<Self::AccountId>;
type RejectOrigin = EitherOf< type RejectOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Degens>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Degens,
>;
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type OnSlash = Treasury; type OnSlash = Treasury;
@ -625,10 +611,7 @@ impl pallet_treasury::Config for Runtime {
type MaxApprovals = MaxApprovals; type MaxApprovals = MaxApprovals;
type WeightInfo = (); type WeightInfo = ();
type SpendOrigin = EitherOf< type SpendOrigin = EitherOf<EnsureRootWithSuccess<AccountId, MaxBalance>, CultTreasurySpender>;
EnsureRootWithSuccess<AccountId, MaxBalance>,
CultTreasurySpender
>;
type AssetKind = (); type AssetKind = ();
type Beneficiary = AccountId; type Beneficiary = AccountId;
@ -708,8 +691,7 @@ impl pallet_grandpa::Config for Runtime {
type MaxNominators = MaxNominators; type MaxNominators = MaxNominators;
type MaxSetIdSessionEntries = MaxSetIdSessionEntries; type MaxSetIdSessionEntries = MaxSetIdSessionEntries;
type KeyOwnerProof = type KeyOwnerProof = <Historical as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
<Historical as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;
type EquivocationReportSystem = type EquivocationReportSystem =
pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>; pallet_grandpa::EquivocationReportSystem<Self, Offences, Historical, ReportLongevity>;
@ -726,13 +708,17 @@ where
public: <Signature as Verify>::Signer, public: <Signature as Verify>::Signer,
account: AccountId, account: AccountId,
nonce: <Runtime as frame_system::Config>::Nonce, nonce: <Runtime as frame_system::Config>::Nonce,
) -> Option<(RuntimeCall, <UncheckedExtrinsic as ExtrinsicT>::SignaturePayload)> { ) -> Option<(
RuntimeCall,
<UncheckedExtrinsic as ExtrinsicT>::SignaturePayload,
)> {
use sp_runtime::traits::StaticLookup; use sp_runtime::traits::StaticLookup;
// take the biggest period possible // take the biggest period possible
let period = BlockHashCount::get() let period = BlockHashCount::get()
.checked_next_power_of_two() .checked_next_power_of_two()
.map(|c| c / 2).unwrap_or(2) as u64; .map(|c| c / 2)
.unwrap_or(2) as u64;
let current_block = System::block_number() let current_block = System::block_number()
.saturated_into::<u64>() .saturated_into::<u64>()
@ -746,9 +732,10 @@ where
frame_system::CheckSpecVersion::<Runtime>::new(), frame_system::CheckSpecVersion::<Runtime>::new(),
frame_system::CheckTxVersion::<Runtime>::new(), frame_system::CheckTxVersion::<Runtime>::new(),
frame_system::CheckGenesis::<Runtime>::new(), frame_system::CheckGenesis::<Runtime>::new(),
frame_system::CheckMortality::<Runtime>::from( frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
generic::Era::mortal(period, current_block), period,
), current_block,
)),
frame_system::CheckNonce::<Runtime>::from(nonce), frame_system::CheckNonce::<Runtime>::from(nonce),
frame_system::CheckWeight::<Runtime>::new(), frame_system::CheckWeight::<Runtime>::new(),
pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip), pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
@ -830,8 +817,17 @@ parameter_types! {
/// The type used to represent the kinds of proxying allowed. /// The type used to represent the kinds of proxying allowed.
#[derive( #[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Copy,
Decode, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo, Clone,
Eq,
PartialEq,
Ord,
PartialOrd,
Encode,
Decode,
RuntimeDebug,
MaxEncodedLen,
scale_info::TypeInfo,
)] )]
pub enum ProxyType { pub enum ProxyType {
Any = 0, Any = 0,
@ -856,42 +852,40 @@ impl InstanceFilter<RuntimeCall> for ProxyType {
ProxyType::NonTransfer => matches!(c, RuntimeCall::Balances { .. }), ProxyType::NonTransfer => matches!(c, RuntimeCall::Balances { .. }),
ProxyType::Governance => matches!( ProxyType::Governance => matches!(
c, c,
RuntimeCall::Bounties { .. } | RuntimeCall::Bounties { .. }
RuntimeCall::Utility { .. } | | RuntimeCall::Utility { .. }
RuntimeCall::ChildBounties { .. } | | RuntimeCall::ChildBounties { .. }
RuntimeCall::CultReferenda { .. } | | RuntimeCall::CultReferenda { .. }
RuntimeCall::CultCollective { .. } | | RuntimeCall::CultCollective { .. }
RuntimeCall::Whitelist { .. } | | RuntimeCall::Whitelist { .. }
RuntimeCall::AllianceMotion { .. } | | RuntimeCall::AllianceMotion { .. }
RuntimeCall::Alliance { .. } | | RuntimeCall::Alliance { .. }
RuntimeCall::Multisig { .. } | RuntimeCall::Multisig { .. }
), ),
ProxyType::Staking => matches!( ProxyType::Staking => matches!(
c, c,
RuntimeCall::Staking { .. } | RuntimeCall::Staking { .. }
RuntimeCall::Session { .. } | | RuntimeCall::Session { .. }
RuntimeCall::Utility { .. } | | RuntimeCall::Utility { .. }
RuntimeCall::FastUnstake { .. } | | RuntimeCall::FastUnstake { .. }
RuntimeCall::VoterList { .. } | | RuntimeCall::VoterList { .. }
RuntimeCall::NominationPools { .. } | RuntimeCall::NominationPools { .. }
), ),
ProxyType::IdentityJudgement => matches!( ProxyType::IdentityJudgement => matches!(
c, c,
RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) | RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. })
RuntimeCall::Utility { .. } | RuntimeCall::Utility { .. }
), ),
ProxyType::CancelProxy => matches!( ProxyType::CancelProxy => matches!(
c, c,
RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) | RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
RuntimeCall::Utility { .. } | | RuntimeCall::Utility { .. }
RuntimeCall::Multisig { .. } | RuntimeCall::Multisig { .. }
), ),
ProxyType::NominationPools => matches!( ProxyType::NominationPools => matches!(
c, c,
RuntimeCall::NominationPools { .. } | RuntimeCall::NominationPools { .. } | RuntimeCall::Utility { .. }
RuntimeCall::Utility { .. }
), ),
} }
} }
@ -940,10 +934,7 @@ impl pallet_nomination_pools::Config for Runtime {
type MaxUnbonding = <Self as pallet_staking::Config>::MaxUnlockingChunks; type MaxUnbonding = <Self as pallet_staking::Config>::MaxUnlockingChunks;
type PalletId = PoolsPalletId; type PalletId = PoolsPalletId;
type MaxPointsToBalance = MaxPointsToBalance; type MaxPointsToBalance = MaxPointsToBalance;
type AdminOrigin = EitherOf< type AdminOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Zombies,
>;
type WeightInfo = weights::pallet_nomination_pools::WeightInfo<Runtime>; type WeightInfo = weights::pallet_nomination_pools::WeightInfo<Runtime>;
} }
@ -1039,18 +1030,10 @@ impl ghost_networks::Config for Runtime {
type NetworkId = u64; type NetworkId = u64;
type Currency = Balances; type Currency = Balances;
type RegisterOrigin = EitherOf< type RegisterOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Ghosts>;
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, type UpdateOrigin = EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Zombies>;
Ghosts, type RemoveOrigin =
>; EitherOf<EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>, Skeletons>;
type UpdateOrigin = EitherOf<
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Zombies,
>;
type RemoveOrigin = EitherOf<
EnsureRootWithSuccess<Self::AccountId, ConstU16<65535>>,
Skeletons,
>;
type WeightInfo = weights::ghost_networks::WeightInfo<Runtime>; type WeightInfo = weights::ghost_networks::WeightInfo<Runtime>;
} }
@ -1061,7 +1044,6 @@ parameter_types! {
pub VestingBlocks: u32 = 10 * WEEKS; pub VestingBlocks: u32 = 10 * WEEKS;
} }
impl ghost_claims::Config<CultCollectiveInstance> for Runtime { impl ghost_claims::Config<CultCollectiveInstance> for Runtime {
type RuntimeEvent = RuntimeEvent; type RuntimeEvent = RuntimeEvent;
type VestingSchedule = Vesting; type VestingSchedule = Vesting;
@ -1714,7 +1696,10 @@ mod test_fees {
test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_00u128)); test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_00u128));
test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_000u128)); test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_000u128));
test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_000_000u128)); test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_000_000u128));
test_with_multiplier(Multiplier::saturating_from_rational(1u128, 1_000_000_000u128)); test_with_multiplier(Multiplier::saturating_from_rational(
1u128,
1_000_000_000u128,
));
} }
#[test] #[test]
@ -1736,14 +1721,21 @@ mod test_fees {
}; };
let mut active = target_voters; let mut active = target_voters;
while weight_with(active).all_lte(OffchainSolutionWeightLimit::get()) || while weight_with(active).all_lte(OffchainSolutionWeightLimit::get())
active == target_voters || active == target_voters
{ {
active += 1; active += 1;
} }
println!("can support {} nominators to yield a weight of {}", active, weight_with(active)); println!(
assert!(active > target_voters, "we need to reevaluate the weight of the election system"); "can support {} nominators to yield a weight of {}",
active,
weight_with(active)
);
assert!(
active > target_voters,
"we need to reevaluate the weight of the election system"
);
} }
#[test] #[test]
@ -1772,15 +1764,25 @@ mod test {
.collect(); .collect();
// Block number // Block number
assert!(whitelist.contains("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")); assert!(
whitelist.contains("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
);
// Total issuance // Total issuance
assert!(whitelist.contains("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")); assert!(
whitelist.contains("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
);
// Execution phase // Execution phase
assert!(whitelist.contains("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")); assert!(
whitelist.contains("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
);
// Event count // Event count
assert!(whitelist.contains("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")); assert!(
whitelist.contains("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
);
// System events // System events
assert!(whitelist.contains("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")); assert!(
whitelist.contains("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
);
} }
#[test] #[test]
@ -1817,13 +1819,21 @@ mod multiplier_tests {
#[test] #[test]
fn multiplier_can_grow_from_zero() { fn multiplier_can_grow_from_zero() {
let minimum_multiplier = MinimumMultiplier::get(); let minimum_multiplier = MinimumMultiplier::get();
let target = TargetBlockFullness::get() * let target = TargetBlockFullness::get()
BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap(); * BlockWeights::get()
.get(DispatchClass::Normal)
.max_total
.unwrap();
// if the min is too small, then this will not change, and we are doomed forever. // if the min is too small, then this will not change, and we are doomed forever.
// the weight is 1/100th bigger than target. // the weight is 1/100th bigger than target.
run_with_system_weight(target.saturating_mul(101) / 100, || { run_with_system_weight(target.saturating_mul(101) / 100, || {
let next = SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier); let next = SlowAdjustingFeeUpdate::<Runtime>::convert(minimum_multiplier);
assert!(next > minimum_multiplier, "{:?} !>= {:?}", next, minimum_multiplier); assert!(
next > minimum_multiplier,
"{:?} !>= {:?}",
next,
minimum_multiplier
);
}) })
} }
@ -1836,7 +1846,10 @@ mod multiplier_tests {
<Runtime as pallet_fast_unstake::Config>::BatchSize::get(), <Runtime as pallet_fast_unstake::Config>::BatchSize::get(),
) )
.ref_time() as f32; .ref_time() as f32;
println!("ratio of block weight for full batch fast-unstake {}", on_idle / block_time); println!(
"ratio of block weight for full batch fast-unstake {}",
on_idle / block_time
);
assert!(on_idle / block_time <= 0.5f32) assert!(on_idle / block_time <= 0.5f32)
} }
@ -1846,12 +1859,18 @@ mod multiplier_tests {
// assume the multiplier is initially set to its minimum. We update it with values twice the // assume the multiplier is initially set to its minimum. We update it with values twice the
//target (target is 25%, thus 50%) and we see at which point it reaches 1. //target (target is 25%, thus 50%) and we see at which point it reaches 1.
let mut multiplier = MinimumMultiplier::get(); let mut multiplier = MinimumMultiplier::get();
let block_weight = BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap(); let block_weight = BlockWeights::get()
.get(DispatchClass::Normal)
.max_total
.unwrap();
let mut blocks = 0; let mut blocks = 0;
let mut fees_paid = 0; let mut fees_paid = 0;
frame_system::Pallet::<Runtime>::set_block_consumed_resources(Weight::MAX, 0); frame_system::Pallet::<Runtime>::set_block_consumed_resources(Weight::MAX, 0);
let info = DispatchInfo { weight: Weight::MAX, ..Default::default() }; let info = DispatchInfo {
weight: Weight::MAX,
..Default::default()
};
let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default() let mut t: sp_io::TestExternalities = frame_system::GenesisConfig::default()
.build_storage::<Runtime>() .build_storage::<Runtime>()