diff --git a/Cargo.lock b/Cargo.lock index 5cd5e810f..95ec92ba6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1899,7 +1899,6 @@ dependencies = [ "log", "pallet-balances", "parity-scale-codec", - "runtime-common", "scale-info", "serde", "sp-core", @@ -3511,7 +3510,6 @@ dependencies = [ "pallet-balances", "pallet-vesting", "parity-scale-codec", - "runtime-common", "scale-info", "serde", "sp-core", @@ -5639,8 +5637,8 @@ dependencies = [ "log", "pallet-balances", "parity-scale-codec", - "runtime-common", "scale-info", + "sp-core", "sp-io", "sp-keystore", "sp-runtime", @@ -5788,7 +5786,6 @@ dependencies = [ "frame-system", "pallet-balances", "parity-scale-codec", - "runtime-common", "scale-info", "serde", "sp-core", @@ -6392,7 +6389,6 @@ dependencies = [ "pallet-session", "pallet-timestamp", "parity-scale-codec", - "runtime-common", "scale-info", "serde", "sp-consensus-aura", @@ -8572,6 +8568,7 @@ dependencies = [ "pallet-authorship", "pallet-balances", "pallet-transaction-payment", + "parachain-staking", "parity-scale-codec", "scale-info", "serde", diff --git a/nodes/parachain/src/chain_spec/peregrine.rs b/nodes/parachain/src/chain_spec/peregrine.rs index 6d294f7fc..78e455f3e 100644 --- a/nodes/parachain/src/chain_spec/peregrine.rs +++ b/nodes/parachain/src/chain_spec/peregrine.rs @@ -21,12 +21,12 @@ use cumulus_primitives_core::ParaId; use hex_literal::hex; use peregrine_runtime::{ - BalancesConfig, CouncilConfig, GenesisConfig, InflationInfo, KiltLaunchConfig, MinCollatorStake, - ParachainInfoConfig, ParachainStakingConfig, SessionConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, - VestingConfig, WASM_BINARY, + BalancesConfig, CouncilConfig, GenesisConfig, InflationInfo, KiltLaunchConfig, ParachainInfoConfig, + ParachainStakingConfig, SessionConfig, SudoConfig, SystemConfig, TechnicalCommitteeConfig, VestingConfig, + WASM_BINARY, }; use runtime_common::{ - constants::{INFLATION_CONFIG, MAX_COLLATOR_STAKE}, + constants::{kilt_inflation_config, staking::MinCollatorStake, MAX_COLLATOR_STAKE}, AccountId, AuthorityId, Balance, BlockNumber, }; use sc_service::ChainType; @@ -138,10 +138,6 @@ pub fn make_new_spec() -> Result { )) } -pub fn kilt_inflation_config() -> InflationInfo { - InflationInfo::from(INFLATION_CONFIG) -} - #[allow(clippy::too_many_arguments)] fn testnet_genesis( wasm_binary: &[u8], diff --git a/nodes/parachain/src/chain_spec/spiritnet.rs b/nodes/parachain/src/chain_spec/spiritnet.rs index bfba67a03..e024250b8 100644 --- a/nodes/parachain/src/chain_spec/spiritnet.rs +++ b/nodes/parachain/src/chain_spec/spiritnet.rs @@ -21,7 +21,7 @@ use cumulus_primitives_core::ParaId; use hex_literal::hex; use runtime_common::{ - constants::{INFLATION_CONFIG, KILT, MAX_COLLATOR_STAKE}, + constants::{kilt_inflation_config, staking::MinCollatorStake, KILT, MAX_COLLATOR_STAKE}, AccountId, AuthorityId, Balance, BlockNumber, }; use sc_service::ChainType; @@ -29,9 +29,8 @@ use sc_telemetry::TelemetryEndpoints; use sp_core::{crypto::UncheckedInto, sr25519}; use sp_runtime::traits::Zero; use spiritnet_runtime::{ - BalancesConfig, CouncilConfig, GenesisConfig, InflationInfo, KiltLaunchConfig, MinCollatorStake, - ParachainInfoConfig, ParachainStakingConfig, SessionConfig, SystemConfig, TechnicalCommitteeConfig, VestingConfig, - WASM_BINARY, + BalancesConfig, CouncilConfig, GenesisConfig, InflationInfo, KiltLaunchConfig, ParachainInfoConfig, + ParachainStakingConfig, SessionConfig, SystemConfig, TechnicalCommitteeConfig, VestingConfig, WASM_BINARY, }; use crate::chain_spec::{get_account_id_from_seed, get_from_seed, DEFAULT_PARA_ID, TELEMETRY_URL}; @@ -244,10 +243,6 @@ pub fn load_spiritnet_spec() -> Result { ChainSpec::from_json_bytes(&include_bytes!("../../res/spiritnet.json")[..]) } -pub fn kilt_inflation_config() -> InflationInfo { - InflationInfo::from(INFLATION_CONFIG) -} - #[allow(clippy::too_many_arguments)] fn testnet_genesis( wasm_binary: &[u8], diff --git a/pallets/attestation/src/mock.rs b/pallets/attestation/src/mock.rs index 8efb03401..15d8f8aaf 100644 --- a/pallets/attestation/src/mock.rs +++ b/pallets/attestation/src/mock.rs @@ -156,13 +156,11 @@ pub(crate) mod runtime { use ctype::CtypeCreatorOf; use frame_support::{parameter_types, weights::constants::RocksDbWeight}; use sp_core::{ed25519, sr25519, Pair}; - use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, MultiSignature, MultiSigner, }; - use std::sync::Arc; use kilt_support::mock::{mock_origin, SubjectId}; @@ -368,8 +366,8 @@ pub(crate) mod runtime { pub fn build_with_keystore(self) -> sp_io::TestExternalities { let mut ext = self.build(); - let keystore = KeyStore::new(); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + let keystore = sp_keystore::testing::KeyStore::new(); + ext.register_extension(sp_keystore::KeystoreExt(std::sync::Arc::new(keystore))); ext } diff --git a/pallets/delegation/src/mock.rs b/pallets/delegation/src/mock.rs index ede4f0cfb..ef30b34af 100644 --- a/pallets/delegation/src/mock.rs +++ b/pallets/delegation/src/mock.rs @@ -176,13 +176,11 @@ pub(crate) mod runtime { use codec::Encode; use frame_support::{parameter_types, weights::constants::RocksDbWeight}; use sp_core::{ed25519, sr25519, Pair}; - use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, MultiSignature, MultiSigner, }; - use sp_std::sync::Arc; use attestation::{mock::insert_attestation, AttestationDetails, ClaimHashOf}; use kilt_support::{ @@ -510,8 +508,8 @@ pub(crate) mod runtime { pub fn build_with_keystore(self) -> sp_io::TestExternalities { let mut ext = self.build(); - let keystore = KeyStore::new(); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + let keystore = sp_keystore::testing::KeyStore::new(); + ext.register_extension(sp_keystore::KeystoreExt(sp_std::sync::Arc::new(keystore))); ext } diff --git a/pallets/did/Cargo.toml b/pallets/did/Cargo.toml index 4dedc9d28..ffa81d577 100644 --- a/pallets/did/Cargo.toml +++ b/pallets/did/Cargo.toml @@ -17,17 +17,18 @@ env_logger = {version = "0.8.3"} serde = {version = "1.0.132"} ctype = {features = ["mock"], path = "../ctype"} + +frame-benchmarking = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} -runtime-common = {default-features = false, path = "../../runtimes/common"} +sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} [dependencies] # Internal dependencies -ctype = {optional = true, path = "../ctype"} +ctype = {path = "../ctype", optional = true} kilt-support = {default-features = false, path = "../../support"} -runtime-common = {default-features = false, path = "../../runtimes/common"} # External dependencies -env_logger = {default-features = false, optional = true, version = "0.8.3"} +env_logger = {default-features = false, version = "0.8.3", optional = true} hex = {default-features = false, features = ["alloc"], version = "0.4.2"} log = "0.4" @@ -42,7 +43,7 @@ sp-std = {branch = "polkadot-v0.9.17", default-features = false, git = "https:// # benchmarking frame-benchmarking = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} -pallet-balances = {optional = true, branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate", optional = true} [features] @@ -66,7 +67,6 @@ std = [ "frame-support/std", "frame-system/std", "hex/std", - "runtime-common/std", "kilt-support/std", "kilt-support/std", "log/std", diff --git a/pallets/did/src/benchmarking.rs b/pallets/did/src/benchmarking.rs index ce5699ca9..c7da7c74f 100644 --- a/pallets/did/src/benchmarking.rs +++ b/pallets/did/src/benchmarking.rs @@ -23,10 +23,9 @@ use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, Zero}; use frame_support::{assert_ok, traits::Currency}; use frame_system::RawOrigin; use kilt_support::signature::VerifySignature; -use runtime_common::AccountId; use sp_core::{crypto::KeyTypeId, ecdsa, ed25519, sr25519}; use sp_io::crypto::{ecdsa_generate, ecdsa_sign, ed25519_generate, ed25519_sign, sr25519_generate, sr25519_sign}; -use sp_runtime::{traits::IdentifyAccount, MultiSigner}; +use sp_runtime::{traits::IdentifyAccount, AccountId32, MultiSigner}; use sp_std::{convert::TryInto, vec::Vec}; use crate::{ @@ -118,9 +117,9 @@ fn save_service_endpoints(did_subject: &DidIdentifierOf, endpoints benchmarks! { where_clause { where - T::DidIdentifier: From, + T::DidIdentifier: From, ::Origin: From>, - ::AccountId: From, + ::AccountId: From, } /* create extrinsic */ diff --git a/pallets/did/src/did_details.rs b/pallets/did/src/did_details.rs index d4a07d6f1..528d64113 100644 --- a/pallets/did/src/did_details.rs +++ b/pallets/did/src/did_details.rs @@ -177,7 +177,7 @@ pub trait DidVerifiableIdentifier { ) -> Result; } -impl DidVerifiableIdentifier for runtime_common::DidIdentifier { +impl> DidVerifiableIdentifier for I { fn verify_and_recover_signature( &self, payload: &Payload, diff --git a/pallets/did/src/mock.rs b/pallets/did/src/mock.rs index ef765550f..ecc4fbe34 100644 --- a/pallets/did/src/mock.rs +++ b/pallets/did/src/mock.rs @@ -16,9 +16,6 @@ // If you feel like getting in touch with us, you can do so at info@botlabs.org -#![allow(clippy::from_over_into)] -#![allow(dead_code)] - use frame_support::{ parameter_types, traits::{Currency, OnUnbalanced, ReservableCurrency}, @@ -26,15 +23,13 @@ use frame_support::{ }; use frame_system::EnsureSigned; use pallet_balances::NegativeImbalance; -use runtime_common::{constants::MICRO_KILT, AccountId, Balance}; use sp_core::{ecdsa, ed25519, sr25519, Pair}; -use sp_keystore::{testing::KeyStore, KeystoreExt}; use sp_runtime::{ testing::{Header, H256}, traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, - MultiSigner, SaturatedConversion, + MultiSignature, MultiSigner, SaturatedConversion, }; -use sp_std::sync::Arc; +use sp_std::vec::Vec; use crate::{ self as did, @@ -50,14 +45,20 @@ use crate::{ #[cfg(not(feature = "runtime-benchmarks"))] use crate::{DidRawOrigin, EnsureDidOrigin}; -pub type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -pub type Block = frame_system::mocking::MockBlock; +pub(crate) type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +pub(crate) type Block = frame_system::mocking::MockBlock; +pub(crate) type Hash = sp_core::H256; +pub(crate) type Balance = u128; +pub(crate) type Signature = MultiSignature; +pub(crate) type AccountPublic = ::Signer; +pub(crate) type AccountId = ::AccountId; +pub(crate) type Index = u64; +pub(crate) type BlockNumber = u64; + +pub(crate) type DidIdentifier = AccountId; +pub(crate) type CtypeHash = Hash; -pub type TestDidIdentifier = runtime_common::AccountId; -pub type TestKeyId = KeyIdOf; -pub type TestBlockNumber = runtime_common::BlockNumber; -pub type TestCtypeOwner = TestDidIdentifier; -pub type TestCtypeHash = runtime_common::Hash; +const MICRO_KILT: Balance = 10u128.pow(9); frame_support::construct_runtime!( pub enum Test where @@ -80,11 +81,11 @@ parameter_types! { impl frame_system::Config for Test { type Origin = Origin; type Call = Call; - type Index = u64; - type BlockNumber = u64; - type Hash = runtime_common::Hash; + type Index = Index; + type BlockNumber = BlockNumber; + type Hash = Hash; type Hashing = BlakeTwo256; - type AccountId = <::Signer as IdentifyAccount>::AccountId; + type AccountId = <::Signer as IdentifyAccount>::AccountId; type Lookup = IdentityLookup; type Header = Header; type Event = (); @@ -138,10 +139,10 @@ where } impl Config for Test { - type DidIdentifier = TestDidIdentifier; + type DidIdentifier = DidIdentifier; type Origin = Origin; type Call = Call; - type EnsureOrigin = EnsureSigned; + type EnsureOrigin = EnsureSigned; type OriginSuccess = AccountId; type Event = (); type Currency = Balances; @@ -185,16 +186,16 @@ parameter_types! { impl ctype::Config for Test { #[cfg(feature = "runtime-benchmarks")] - type EnsureOrigin = EnsureSigned; + type EnsureOrigin = EnsureSigned; #[cfg(feature = "runtime-benchmarks")] - type OriginSuccess = runtime_common::AccountId; + type OriginSuccess = AccountId; #[cfg(not(feature = "runtime-benchmarks"))] - type EnsureOrigin = EnsureDidOrigin; + type EnsureOrigin = EnsureDidOrigin; #[cfg(not(feature = "runtime-benchmarks"))] - type OriginSuccess = DidRawOrigin; + type OriginSuccess = DidRawOrigin; - type CtypeCreatorId = TestCtypeOwner; + type CtypeCreatorId = DidIdentifier; type Event = (); type WeightInfo = (); type Currency = Balances; @@ -202,12 +203,9 @@ impl ctype::Config for Test { type FeeCollector = (); } -#[cfg(test)] -pub(crate) const ACCOUNT_00: runtime_common::AccountId = runtime_common::AccountId::new([1u8; 32]); -#[cfg(test)] -pub(crate) const ACCOUNT_01: runtime_common::AccountId = runtime_common::AccountId::new([2u8; 32]); -#[cfg(test)] -pub(crate) const ACCOUNT_FEE: runtime_common::AccountId = runtime_common::AccountId::new([u8::MAX; 32]); +pub(crate) const ACCOUNT_00: AccountId = AccountId::new([1u8; 32]); +pub(crate) const ACCOUNT_01: AccountId = AccountId::new([2u8; 32]); +pub(crate) const ACCOUNT_FEE: AccountId = AccountId::new([u8::MAX; 32]); const DEFAULT_AUTH_SEED: [u8; 32] = [4u8; 32]; const ALTERNATIVE_AUTH_SEED: [u8; 32] = [40u8; 32]; @@ -237,15 +235,15 @@ pub(crate) fn fill_public_keys(mut did_details: DidDetails) -> DidDetails< did_details } -pub fn get_did_identifier_from_ed25519_key(public_key: ed25519::Public) -> TestDidIdentifier { +pub fn get_did_identifier_from_ed25519_key(public_key: ed25519::Public) -> DidIdentifier { MultiSigner::from(public_key).into_account() } -pub fn get_did_identifier_from_sr25519_key(public_key: sr25519::Public) -> TestDidIdentifier { +pub fn get_did_identifier_from_sr25519_key(public_key: sr25519::Public) -> DidIdentifier { MultiSigner::from(public_key).into_account() } -pub fn get_did_identifier_from_ecdsa_key(public_key: ecdsa::Public) -> TestDidIdentifier { +pub fn get_did_identifier_from_ecdsa_key(public_key: ecdsa::Public) -> DidIdentifier { MultiSigner::from(public_key).into_account() } @@ -329,7 +327,7 @@ pub fn get_ecdsa_delegation_key(default: bool) -> ecdsa::Pair { } } -pub fn generate_key_id(key: &DidPublicKey) -> TestKeyId { +pub fn generate_key_id(key: &DidPublicKey) -> KeyIdOf { crate_utils::calculate_key_id::(key) } @@ -387,14 +385,14 @@ impl DeriveDidCallAuthorizationVerificationKeyRelationship for Call { // Always return a System::remark() extrinsic call #[cfg(feature = "runtime-benchmarks")] fn get_call_for_did_call_benchmark() -> Self { - Call::System(frame_system::Call::remark { remark: vec![] }) + Call::System(frame_system::Call::remark { remark: sp_std::vec![] }) } } pub fn generate_test_did_call( verification_key_required: DidVerificationKeyRelationship, - caller: TestDidIdentifier, - submitter: runtime_common::AccountId, + caller: DidIdentifier, + submitter: AccountId, ) -> DidAuthorizedCallOperationWithVerificationRelationship { let call = match verification_key_required { DidVerificationKeyRelationship::AssertionMethod => get_attestation_key_call(), @@ -413,30 +411,30 @@ pub fn generate_test_did_call( verification_key_relationship: verification_key_required, } } - +#[cfg(test)] #[allow(unused_must_use)] -pub fn initialize_logger() { +pub(crate) fn initialize_logger() { env_logger::builder().is_test(true).try_init(); } #[derive(Clone, Default)] -pub struct ExtBuilder { - dids_stored: Vec<(TestDidIdentifier, DidDetails)>, - service_endpoints: Vec<(TestDidIdentifier, Vec>)>, - deleted_dids: Vec, - ctypes_stored: Vec<(TestCtypeHash, TestCtypeOwner)>, +pub(crate) struct ExtBuilder { + dids_stored: Vec<(DidIdentifier, DidDetails)>, + service_endpoints: Vec<(DidIdentifier, Vec>)>, + deleted_dids: Vec, + ctypes_stored: Vec<(CtypeHash, DidIdentifier)>, balances: Vec<(AccountIdOf, Balance)>, } impl ExtBuilder { #[must_use] - pub fn with_dids(mut self, dids: Vec<(TestDidIdentifier, DidDetails)>) -> Self { + pub fn with_dids(mut self, dids: Vec<(DidIdentifier, DidDetails)>) -> Self { self.dids_stored = dids; self } #[must_use] - pub fn with_endpoints(mut self, endpoints: Vec<(TestDidIdentifier, Vec>)>) -> Self { + pub fn with_endpoints(mut self, endpoints: Vec<(DidIdentifier, Vec>)>) -> Self { self.service_endpoints = endpoints; self } @@ -448,13 +446,13 @@ impl ExtBuilder { } #[must_use] - pub fn with_ctypes(mut self, ctypes: Vec<(TestCtypeHash, TestCtypeOwner)>) -> Self { + pub fn with_ctypes(mut self, ctypes: Vec<(CtypeHash, DidIdentifier)>) -> Self { self.ctypes_stored = ctypes; self } #[must_use] - pub fn with_deleted_dids(mut self, dids: Vec) -> Self { + pub fn with_deleted_dids(mut self, dids: Vec) -> Self { self.deleted_dids = dids; self } @@ -500,8 +498,8 @@ impl ExtBuilder { pub fn build_with_keystore(self) -> sp_io::TestExternalities { let mut ext = self.build(None); - let keystore = KeyStore::new(); - ext.register_extension(KeystoreExt(Arc::new(keystore))); + let keystore = sp_keystore::testing::KeyStore::new(); + ext.register_extension(sp_keystore::KeystoreExt(sp_std::sync::Arc::new(keystore))); ext } diff --git a/pallets/did/src/mock_utils.rs b/pallets/did/src/mock_utils.rs index 91eb1d052..0a3ca10f8 100644 --- a/pallets/did/src/mock_utils.rs +++ b/pallets/did/src/mock_utils.rs @@ -18,7 +18,7 @@ use frame_support::storage::bounded_btree_set::BoundedBTreeSet; use kilt_support::deposit::Deposit; -use sp_runtime::{traits::Zero, SaturatedConversion}; +use sp_runtime::{traits::Zero, AccountId32, SaturatedConversion}; use sp_std::{ collections::btree_set::BTreeSet, convert::{TryFrom, TryInto}, @@ -96,13 +96,13 @@ pub fn generate_base_did_creation_details( pub fn generate_base_did_details(authentication_key: DidVerificationKey) -> DidDetails where T: Config, - ::AccountId: From, + ::AccountId: From, { DidDetails::new( authentication_key, BlockNumberOf::::default(), Deposit { - owner: runtime_common::AccountId::new([0u8; 32]).into(), + owner: AccountId32::new([0u8; 32]).into(), amount: Zero::zero(), }, ) diff --git a/pallets/did/src/tests.rs b/pallets/did/src/tests.rs index c904e147d..0311e8294 100644 --- a/pallets/did/src/tests.rs +++ b/pallets/did/src/tests.rs @@ -776,7 +776,7 @@ fn check_successful_authentication_key_update() { let old_did_details = generate_base_did_details::(DidVerificationKey::from(old_auth_key.public())); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update authentication key. The old one should be removed. ExtBuilder::default() @@ -817,7 +817,7 @@ fn check_successful_authentication_key_max_public_keys_update() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update authentication key. The old one should be removed. ExtBuilder::default() @@ -856,7 +856,7 @@ fn check_reused_key_authentication_key_update() { // Same key for auth and del key assert_ok!(old_did_details.update_delegation_key(DidVerificationKey::from(old_delegation_key.public()), 0u64)); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; ExtBuilder::default() .with_dids(vec![(alice_did.clone(), old_did_details)]) @@ -904,7 +904,7 @@ fn check_max_keys_authentication_key_update_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update authentication key. Since the old one is not removed because it is the // same as the delegation key, the update should fail as the max number of @@ -930,7 +930,7 @@ fn check_did_not_present_authentication_key_update_error() { let alice_did = get_did_identifier_from_ed25519_key(old_auth_key.public()); let new_auth_key = get_ed25519_authentication_key(false); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update authentication key. The old one should be removed. ExtBuilder::default().build(None).execute_with(|| { @@ -955,7 +955,7 @@ fn check_successful_delegation_key_update() { let mut old_did_details = generate_base_did_details::(DidVerificationKey::from(auth_key.public())); assert_ok!(old_did_details.update_delegation_key(DidVerificationKey::from(old_del_key.public()), 0u64)); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default() @@ -998,7 +998,7 @@ fn check_successful_delegation_key_max_public_keys_update() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default() @@ -1035,7 +1035,7 @@ fn check_reused_key_delegation_key_update() { // Same key for auth and del key assert_ok!(old_did_details.update_delegation_key(DidVerificationKey::from(old_del_key.public()), 0u64)); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; ExtBuilder::default() .with_dids(vec![(alice_did.clone(), old_did_details)]) @@ -1077,7 +1077,7 @@ fn check_max_public_keys_delegation_key_addition_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default() @@ -1112,7 +1112,7 @@ fn check_max_public_keys_reused_key_delegation_key_update_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should not be removed as it is still used // as authentication key. @@ -1137,7 +1137,7 @@ fn check_did_not_present_delegation_key_update_error() { let alice_did = get_did_identifier_from_ed25519_key(auth_key.public()); let new_del_key = get_sr25519_delegation_key(false); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default().build(None).execute_with(|| { @@ -1244,7 +1244,7 @@ fn check_successful_attestation_key_update() { let mut old_did_details = generate_base_did_details::(DidVerificationKey::from(auth_key.public())); assert_ok!(old_did_details.update_attestation_key(DidVerificationKey::from(old_att_key.public()), 0u64)); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update attestation key. The old one should be removed. ExtBuilder::default() @@ -1286,7 +1286,7 @@ fn check_successful_attestation_key_max_public_keys_update() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update attestation key. The old one should be removed. ExtBuilder::default() @@ -1322,7 +1322,7 @@ fn check_reused_key_attestation_key_update() { // Same key for auth and att key assert_ok!(old_did_details.update_attestation_key(DidVerificationKey::from(old_att_key.public()), 0u64)); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; ExtBuilder::default() .with_dids(vec![(alice_did.clone(), old_did_details)]) @@ -1364,7 +1364,7 @@ fn check_max_public_keys_attestation_key_addition_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update attestation key. The old one should be removed. ExtBuilder::default() @@ -1399,7 +1399,7 @@ fn check_max_public_keys_reused_key_attestation_key_update_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update attestation key. The old one should not be removed as it is still used // as authentication key. @@ -1424,7 +1424,7 @@ fn check_did_not_present_attestation_key_update_error() { let alice_did = get_did_identifier_from_ed25519_key(auth_key.public()); let new_att_key = get_sr25519_delegation_key(false); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default().build(None).execute_with(|| { @@ -1528,7 +1528,7 @@ fn check_successful_key_agreement_key_addition() { let old_did_details = generate_base_did_details::(DidVerificationKey::from(auth_key.public())); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; ExtBuilder::default() .with_dids(vec![(alice_did.clone(), old_did_details)]) @@ -1568,7 +1568,7 @@ fn check_max_public_keys_key_agreement_key_addition_error() { // MaxPublicKeysPerDid - MaxTotalKeyAgreementKeys many keys did_details = fill_public_keys(did_details); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; ExtBuilder::default() .with_dids(vec![(alice_did.clone(), did_details)]) @@ -1588,7 +1588,7 @@ fn check_did_not_present_key_agreement_key_addition_error() { let alice_did = get_did_identifier_from_ed25519_key(auth_key.public()); let new_enc_key = get_x25519_encryption_key(true); - let new_block_number: TestBlockNumber = 1; + let new_block_number: BlockNumber = 1; // Update delegation key. The old one should be removed. ExtBuilder::default().build(None).execute_with(|| { diff --git a/pallets/kilt-launch/Cargo.toml b/pallets/kilt-launch/Cargo.toml index 61dba5581..f755c4062 100644 --- a/pallets/kilt-launch/Cargo.toml +++ b/pallets/kilt-launch/Cargo.toml @@ -10,7 +10,6 @@ version = "1.6.2" targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] -runtime-common = {path = "../../runtimes/common", default-features = false} sp-core = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} sp-io = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} @@ -28,9 +27,6 @@ pallet-vesting = {git = "https://github.com/paritytech/substrate", default-featu sp-runtime = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} sp-std = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} -# benchmarking -runtime-common = {path = "../../runtimes/common", default-features = false, optional = true} - [features] default = ["std"] @@ -38,14 +34,12 @@ runtime-benchmarks = [ "frame-benchmarking", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", - "runtime-common", ] std = [ "codec/std", "frame-benchmarking/std", "frame-support/std", "frame-system/std", - "runtime-common/std", "log/std", "pallet-balances/std", "pallet-vesting/std", diff --git a/pallets/kilt-launch/src/benchmarking.rs b/pallets/kilt-launch/src/benchmarking.rs index 6829015cc..8c81f6170 100644 --- a/pallets/kilt-launch/src/benchmarking.rs +++ b/pallets/kilt-launch/src/benchmarking.rs @@ -18,8 +18,7 @@ use super::*; -#[allow(unused)] -use crate::{BalanceLocks, BalanceOf, LockedBalance, Pallet as KiltLaunch, UnownedAccount, KILT_LAUNCH_ID}; +use crate::{BalanceLocks, BalanceOf, LockedBalance, Pallet as KiltLaunch, UnownedAccount}; use frame_benchmarking::{account, benchmarks, impl_benchmark_test_suite, vec, whitelist_account, Zero}; use frame_support::{ assert_ok, @@ -29,12 +28,11 @@ use frame_support::{ use frame_system::{Pallet as System, RawOrigin}; use pallet_balances::Locks; use pallet_vesting::{Vesting, VestingInfo}; -use runtime_common::{constants::KILT, Balance}; use sp_runtime::traits::StaticLookup; use sp_std::convert::TryFrom; const SEED: u32 = 0; -const AMOUNT: Balance = KILT; +const AMOUNT: u128 = 1000; const PER_BLOCK: u32 = 100; const UNLOCK_BLOCK: u32 = 1337; @@ -65,9 +63,8 @@ type GenesisSetup = ( /// addresses. fn genesis_setup(n: u32) -> Result, &'static str> where - Balance: Into<::Balance>, - Balance: - Into<<::Currency as Currency<::AccountId>>::Balance>, + ::Balance: From, + <::Currency as Currency<::AccountId>>::Balance: From, { System::::set_block_number(0u32.into()); @@ -114,7 +111,12 @@ where } benchmarks! { - where_clause { where T: core::fmt::Debug, Balance: Into<::Balance>, Balance: Into<<::Currency as Currency<::AccountId>>::Balance>} + where_clause { + where + T: core::fmt::Debug, + ::Balance: From, + <::Currency as Currency<::AccountId>>::Balance: From, + } change_transfer_account { let transfer_account: T::AccountId = account("transfer_new", 0, SEED); diff --git a/pallets/kilt-launch/src/mock.rs b/pallets/kilt-launch/src/mock.rs index 8782cabae..74f705086 100644 --- a/pallets/kilt-launch/src/mock.rs +++ b/pallets/kilt-launch/src/mock.rs @@ -23,15 +23,23 @@ use frame_support::{assert_noop, assert_ok, parameter_types, traits::GenesisBuil use frame_system as system; use pallet_balances::{BalanceLock, Locks, Reasons}; use pallet_vesting::VestingInfo; -use runtime_common::{constants::MIN_VESTED_TRANSFER_AMOUNT, AccountId, Balance, BlockNumber, Hash, Index}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, ConvertInto, IdentityLookup, Zero}, - AccountId32, + traits::{BlakeTwo256, ConvertInto, IdentifyAccount, IdentityLookup, Verify, Zero}, + AccountId32, MultiSignature, }; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; +pub(crate) type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +pub(crate) type Block = frame_system::mocking::MockBlock; +pub(crate) type Hash = sp_core::H256; +pub(crate) type Balance = u128; +pub(crate) type Signature = MultiSignature; +pub(crate) type AccountPublic = ::Signer; +pub(crate) type AccountId = ::AccountId; +pub(crate) type Index = u64; +pub(crate) type BlockNumber = u64; + +pub const MILLI_KILT: Balance = 10u128.pow(12); pub const PSEUDO_1: AccountId = AccountId32::new([1u8; 32]); pub const PSEUDO_2: AccountId = AccountId32::new([2u8; 32]); @@ -126,7 +134,7 @@ impl kilt_launch::Config for Test { } parameter_types! { - pub const MinVestedTransfer: Balance = MIN_VESTED_TRANSFER_AMOUNT; + pub const MinVestedTransfer: Balance = 100 * MILLI_KILT; } impl pallet_vesting::Config for Test { @@ -136,24 +144,13 @@ impl pallet_vesting::Config for Test { // disable vested transfers by setting min amount to max balance type MinVestedTransfer = MinVestedTransfer; type WeightInfo = (); - const MAX_VESTING_SCHEDULES: u32 = runtime_common::constants::MAX_VESTING_SCHEDULES; + const MAX_VESTING_SCHEDULES: u32 = 28; } +#[derive(Default)] pub struct ExtBuilder { balance_locks: Vec<(AccountId, BlockNumber, Balance)>, vesting: Vec<(AccountId, BlockNumber, Balance)>, - #[allow(dead_code)] - transfer_account: AccountId, -} - -impl Default for ExtBuilder { - fn default() -> Self { - Self { - balance_locks: vec![], - vesting: vec![], - transfer_account: TRANSFER_ACCOUNT, - } - } } /// Calls `migrate_genesis_account` and checks whether balance, vesting and diff --git a/pallets/kilt-launch/src/tests.rs b/pallets/kilt-launch/src/tests.rs index ed3038726..204673b5b 100644 --- a/pallets/kilt-launch/src/tests.rs +++ b/pallets/kilt-launch/src/tests.rs @@ -27,7 +27,6 @@ use frame_support::{ }; use pallet_balances::{BalanceLock, Locks, Reasons}; use pallet_vesting::{Vesting as VestingStorage, VestingInfo}; -use runtime_common::{AccountId, BlockNumber}; use sp_runtime::traits::Zero; #[test] diff --git a/pallets/pallet-did-lookup/Cargo.toml b/pallets/pallet-did-lookup/Cargo.toml index 558f8a010..7633b7dbd 100644 --- a/pallets/pallet-did-lookup/Cargo.toml +++ b/pallets/pallet-did-lookup/Cargo.toml @@ -11,11 +11,11 @@ targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] kilt-support = {features = ["mock"], path = "../../support"} -runtime-common = {path = "../../runtimes/common"} pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-keystore = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} +sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} [dependencies] codec = {default-features = false, features = ["derive"], package = "parity-scale-codec", version = "2.3.1"} @@ -46,6 +46,7 @@ runtime-benchmarks = [ ] std = [ + "pallet-balances/std", "codec/std", "frame-benchmarking/std", "frame-support/std", diff --git a/pallets/pallet-did-lookup/src/mock.rs b/pallets/pallet-did-lookup/src/mock.rs index aa5628308..9cc14b74f 100644 --- a/pallets/pallet-did-lookup/src/mock.rs +++ b/pallets/pallet-did-lookup/src/mock.rs @@ -20,14 +20,21 @@ use frame_support::parameter_types; use kilt_support::mock::{mock_origin, SubjectId}; use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, + MultiSignature, }; use crate as pallet_did_lookup; -use runtime_common::{AccountId, AccountPublic, Balance, BlockHashCount, BlockNumber, Hash, Index, Signature}; -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; +pub(crate) type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +pub(crate) type Block = frame_system::mocking::MockBlock; +pub(crate) type Hash = sp_core::H256; +pub(crate) type Balance = u128; +pub(crate) type Signature = MultiSignature; +pub(crate) type AccountPublic = ::Signer; +pub(crate) type AccountId = ::AccountId; +pub(crate) type Index = u64; +pub(crate) type BlockNumber = u64; frame_support::construct_runtime!( pub enum Test where @@ -44,6 +51,7 @@ frame_support::construct_runtime!( parameter_types! { pub const SS58Prefix: u8 = 38; + pub const BlockHashCount: BlockNumber = 2400; } impl frame_system::Config for Test { @@ -116,8 +124,8 @@ impl mock_origin::Config for Test { type SubjectId = SubjectId; } -pub(crate) const ACCOUNT_00: runtime_common::AccountId = runtime_common::AccountId::new([1u8; 32]); -pub(crate) const ACCOUNT_01: runtime_common::AccountId = runtime_common::AccountId::new([2u8; 32]); +pub(crate) const ACCOUNT_00: AccountId = AccountId::new([1u8; 32]); +pub(crate) const ACCOUNT_01: AccountId = AccountId::new([2u8; 32]); pub(crate) const DID_00: SubjectId = SubjectId(ACCOUNT_00); pub(crate) const DID_01: SubjectId = SubjectId(ACCOUNT_01); diff --git a/pallets/pallet-did-lookup/src/tests.rs b/pallets/pallet-did-lookup/src/tests.rs index 8fdb48713..827c9ef16 100644 --- a/pallets/pallet-did-lookup/src/tests.rs +++ b/pallets/pallet-did-lookup/src/tests.rs @@ -19,7 +19,6 @@ use codec::Encode; use frame_support::{assert_noop, assert_ok}; use kilt_support::{deposit::Deposit, mock::mock_origin}; -use runtime_common::BlockNumber; use sp_runtime::{ app_crypto::{sr25519, Pair}, traits::IdentifyAccount, diff --git a/pallets/pallet-inflation/Cargo.toml b/pallets/pallet-inflation/Cargo.toml index 5ba38dcd4..570874028 100644 --- a/pallets/pallet-inflation/Cargo.toml +++ b/pallets/pallet-inflation/Cargo.toml @@ -12,8 +12,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] serde = {version = "1.0.132"} -runtime-common = {path = "../../runtimes/common"} - pallet-balances = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-core = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} sp-io = {branch = "polkadot-v0.9.17", default-features = false, git = "https://github.com/paritytech/substrate"} diff --git a/pallets/pallet-inflation/src/mock.rs b/pallets/pallet-inflation/src/mock.rs index caa06d4aa..432f39a3f 100644 --- a/pallets/pallet-inflation/src/mock.rs +++ b/pallets/pallet-inflation/src/mock.rs @@ -22,19 +22,30 @@ use frame_support::{ parameter_types, traits::{Currency, OnFinalize, OnInitialize, OnUnbalanced}, }; -use runtime_common::{ - constants::treasury::{INITIAL_PERIOD_LENGTH, INITIAL_PERIOD_REWARD_PER_BLOCK}, - AccountId, Balance, BlockHashCount, BlockNumber, Hash, Index, -}; + use sp_runtime::{ testing::Header, - traits::{BlakeTwo256, IdentityLookup}, + traits::{BlakeTwo256, IdentifyAccount, IdentityLookup, Verify}, + MultiSignature, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlock; - -pub(crate) const TREASURY_ACC: AccountId = runtime_common::AccountId::new([1u8; 32]); +type Hash = sp_core::H256; +type Balance = u128; +type Signature = MultiSignature; +type AccountPublic = ::Signer; +type AccountId = ::AccountId; +type Index = u64; +type BlockNumber = u64; + +pub(crate) const TREASURY_ACC: AccountId = AccountId::new([1u8; 32]); + +pub const BLOCKS_PER_YEAR: BlockNumber = 60_000 / 12_000 * 60 * 24 * 36525 / 100; +pub const KILT: Balance = 10u128.pow(15); +pub const INITIAL_PERIOD_LENGTH: BlockNumber = BLOCKS_PER_YEAR.saturating_mul(5); +const YEARLY_REWARD: Balance = 2_000_000u128 * KILT; +pub const INITIAL_PERIOD_REWARD_PER_BLOCK: Balance = YEARLY_REWARD / (BLOCKS_PER_YEAR as Balance); frame_support::construct_runtime!( pub enum Test where @@ -50,6 +61,7 @@ frame_support::construct_runtime!( parameter_types! { pub const SS58Prefix: u8 = 38; + pub const BlockHashCount: BlockNumber = 2400; } impl frame_system::Config for Test { diff --git a/pallets/parachain-staking/Cargo.toml b/pallets/parachain-staking/Cargo.toml index 5fbfff42d..98bcf2860 100644 --- a/pallets/parachain-staking/Cargo.toml +++ b/pallets/parachain-staking/Cargo.toml @@ -20,7 +20,6 @@ scale-info = {version = "1.0", default-features = false, features = ["derive"]} serde = {version = "1.0.132", optional = true} kilt-support = {default-features = false, path = "../../support"} -runtime-common = {path = "../../runtimes/common", default-features = false} frame-support = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} frame-system = {git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.17", default-features = false} @@ -44,7 +43,6 @@ runtime-benchmarks = [ std = [ "frame-support/std", "frame-system/std", - "runtime-common/std", "kilt-support/std", "log/std", "pallet-authorship/std", diff --git a/pallets/parachain-staking/src/benchmarking.rs b/pallets/parachain-staking/src/benchmarking.rs index c5f225452..1555c549d 100644 --- a/pallets/parachain-staking/src/benchmarking.rs +++ b/pallets/parachain-staking/src/benchmarking.rs @@ -26,7 +26,6 @@ use frame_support::{ }; use frame_system::{Pallet as System, RawOrigin}; use pallet_session::Pallet as Session; -use runtime_common::constants::BLOCKS_PER_YEAR; use sp_runtime::{ traits::{One, SaturatedConversion, StaticLookup}, Perquintill, @@ -138,7 +137,7 @@ benchmarks! { on_initialize_new_year { let old = >::get(); assert_eq!(>::get(), T::BlockNumber::zero()); - let block = (BLOCKS_PER_YEAR + 1u64).saturated_into::(); + let block = (T::BLOCKS_PER_YEAR + 1u32.into()).saturated_into::(); }: { Pallet::::on_initialize(block) } verify { let new = >::get(); @@ -187,6 +186,7 @@ benchmarks! { set_inflation { let inflation = InflationInfo::new( + T::BLOCKS_PER_YEAR.saturated_into(), Perquintill::from_percent(10), Perquintill::from_percent(15), Perquintill::from_percent(40), @@ -628,8 +628,8 @@ benchmarks! { impl_benchmark_test_suite!( Pallet, crate::mock::ExtBuilder::default() - .with_balances(vec![(u64::MAX, runtime_common::constants::KILT)]) - .with_collators(vec![(u64::MAX, runtime_common::constants::KILT)]) + .with_balances(vec![(u64::MAX, 1000 * crate::mock::MILLI_KILT)]) + .with_collators(vec![(u64::MAX, 1000 * crate::mock::MILLI_KILT)]) .build(), crate::mock::Test, ); diff --git a/pallets/parachain-staking/src/inflation.rs b/pallets/parachain-staking/src/inflation.rs index 57403bdea..e624881d4 100644 --- a/pallets/parachain-staking/src/inflation.rs +++ b/pallets/parachain-staking/src/inflation.rs @@ -19,7 +19,6 @@ //! Helper methods for computing issuance based on inflation use crate::{pallet::Config, types::BalanceOf}; use parity_scale_codec::{Decode, Encode, MaxEncodedLen}; -use runtime_common::constants::BLOCKS_PER_YEAR; use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, Perquintill, RuntimeDebug}; @@ -41,15 +40,15 @@ impl MaxEncodedLen for RewardRate { } /// Convert annual reward rate to per_block. -fn annual_to_per_block(rate: Perquintill) -> Perquintill { - rate / BLOCKS_PER_YEAR.max(1) +fn annual_to_per_block(blocks_per_year: u64, rate: Perquintill) -> Perquintill { + rate / blocks_per_year.max(1) } impl RewardRate { - pub fn new(rate: Perquintill) -> Self { + pub fn new(blocks_per_year: u64, rate: Perquintill) -> Self { RewardRate { annual: rate, - per_block: annual_to_per_block(rate), + per_block: annual_to_per_block(blocks_per_year, rate), } } } @@ -72,10 +71,10 @@ impl MaxEncodedLen for StakingInfo { } impl StakingInfo { - pub fn new(max_rate: Perquintill, annual_reward_rate: Perquintill) -> Self { + pub fn new(blocks_per_year: u64, max_rate: Perquintill, annual_reward_rate: Perquintill) -> Self { StakingInfo { max_rate, - reward_rate: RewardRate::new(annual_reward_rate), + reward_rate: RewardRate::new(blocks_per_year, annual_reward_rate), } } @@ -112,43 +111,44 @@ impl InflationInfo { /// /// Example: InflationInfo::new(Perquintill_from_percent(10), ...) pub fn new( + blocks_per_year: u64, collator_max_rate_percentage: Perquintill, collator_annual_reward_rate_percentage: Perquintill, delegator_max_rate_percentage: Perquintill, delegator_annual_reward_rate_percentage: Perquintill, ) -> Self { Self { - collator: StakingInfo::new(collator_max_rate_percentage, collator_annual_reward_rate_percentage), - delegator: StakingInfo::new(delegator_max_rate_percentage, delegator_annual_reward_rate_percentage), + collator: StakingInfo::new( + blocks_per_year, + collator_max_rate_percentage, + collator_annual_reward_rate_percentage, + ), + delegator: StakingInfo::new( + blocks_per_year, + delegator_max_rate_percentage, + delegator_annual_reward_rate_percentage, + ), } } /// Check whether the annual reward rate is approx. the per_block reward /// rate multiplied with the number of blocks per year - pub fn is_valid(&self) -> bool { - let years = BLOCKS_PER_YEAR; + pub fn is_valid(&self, blocks_per_year: u64) -> bool { self.collator.reward_rate.annual - >= Perquintill::from_parts(self.collator.reward_rate.per_block.deconstruct().saturating_mul(years)) - && self.delegator.reward_rate.annual - >= Perquintill::from_parts(self.delegator.reward_rate.per_block.deconstruct().saturating_mul(years)) - } -} - -impl From<(Perquintill, Perquintill, Perquintill, Perquintill)> for InflationInfo { - fn from( - ( - collator_max_rate_percentage, - collator_annual_reward_rate_percentage, - delegator_max_rate_percentage, - delegator_annual_reward_rate_percentage, - ): (Perquintill, Perquintill, Perquintill, Perquintill), - ) -> Self { - InflationInfo::new( - collator_max_rate_percentage, - collator_annual_reward_rate_percentage, - delegator_max_rate_percentage, - delegator_annual_reward_rate_percentage, - ) + >= Perquintill::from_parts( + self.collator + .reward_rate + .per_block + .deconstruct() + .saturating_mul(blocks_per_year), + ) && self.delegator.reward_rate.annual + >= Perquintill::from_parts( + self.delegator + .reward_rate + .per_block + .deconstruct() + .saturating_mul(blocks_per_year), + ) } } @@ -157,8 +157,7 @@ mod tests { use sp_runtime::Perbill; use super::*; - use crate::mock::{almost_equal, ExtBuilder, Test, DECIMALS}; - use runtime_common::constants::{BLOCKS_PER_YEAR, MAX_COLLATOR_STAKE}; + use crate::mock::{almost_equal, ExtBuilder, Test, DECIMALS, MAX_COLLATOR_STAKE}; #[test] fn perquintill() { @@ -168,18 +167,15 @@ mod tests { ); } - #[allow(clippy::assertions_on_constants)] - #[test] - fn blocks_per_year_saturation() { - assert!(BLOCKS_PER_YEAR < u64::MAX); - } - #[test] fn annual_to_block_rate() { let rate = Perquintill::one(); assert!(almost_equal( rate * 10_000_000_000u128, - Perquintill::from_parts(annual_to_per_block(rate).deconstruct() * BLOCKS_PER_YEAR) * 10_000_000_000u128, + Perquintill::from_parts( + annual_to_per_block(::BLOCKS_PER_YEAR, rate).deconstruct() + * ::BLOCKS_PER_YEAR + ) * 10_000_000_000u128, Perbill::from_perthousand(1) )); } @@ -187,6 +183,7 @@ mod tests { #[test] fn single_block_reward_collator() { let inflation = InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(10), Perquintill::from_percent(10), Perquintill::from_percent(40), @@ -214,15 +211,16 @@ mod tests { .build() .execute_with(|| { let inflation = InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(10), Perquintill::from_percent(15), Perquintill::from_percent(40), Perquintill::from_percent(10), ); - let years_u128: BalanceOf = BLOCKS_PER_YEAR as u128; + let years_u128: BalanceOf = ::BLOCKS_PER_YEAR as u128; // Dummy checks for correct instantiation - assert!(inflation.is_valid()); + assert!(inflation.is_valid(::BLOCKS_PER_YEAR)); assert_eq!(inflation.collator.max_rate, Perquintill::from_percent(10)); assert_eq!(inflation.collator.reward_rate.annual, Perquintill::from_percent(15)); assert!( diff --git a/pallets/parachain-staking/src/lib.rs b/pallets/parachain-staking/src/lib.rs index dabc1bdcd..d548582d4 100644 --- a/pallets/parachain-staking/src/lib.rs +++ b/pallets/parachain-staking/src/lib.rs @@ -192,7 +192,6 @@ pub mod pallet { use frame_system::pallet_prelude::*; use pallet_balances::{BalanceLock, Locks}; use pallet_session::ShouldEndSession; - use runtime_common::constants::BLOCKS_PER_YEAR; use scale_info::TypeInfo; use sp_runtime::{ traits::{Convert, One, SaturatedConversion, Saturating, StaticLookup, Zero}, @@ -349,6 +348,8 @@ pub mod pallet { /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; + + const BLOCKS_PER_YEAR: Self::BlockNumber; } #[pallet::error] @@ -548,7 +549,7 @@ pub mod pallet { post_weight = ::WeightInfo::on_initialize_round_update(); } // check for InflationInfo update - if now > BLOCKS_PER_YEAR.saturated_into::() { + if now > T::BLOCKS_PER_YEAR.saturated_into::() { post_weight = post_weight.saturating_add(Self::adjust_reward_rates(now)); } // check for network reward @@ -694,7 +695,10 @@ pub mod pallet { #[pallet::genesis_build] impl GenesisBuild for GenesisConfig { fn build(&self) { - assert!(self.inflation_config.is_valid(), "Invalid inflation configuration"); + assert!( + self.inflation_config.is_valid(T::BLOCKS_PER_YEAR.saturated_into()), + "Invalid inflation configuration" + ); >::put(self.inflation_config.clone()); MaxCollatorCandidateStake::::put(self.max_candidate_stake); @@ -783,13 +787,17 @@ pub mod pallet { ensure_root(origin)?; let inflation = InflationInfo::new( + T::BLOCKS_PER_YEAR.saturated_into(), collator_max_rate_percentage, collator_annual_reward_rate_percentage, delegator_max_rate_percentage, delegator_annual_reward_rate_percentage, ); - ensure!(inflation.is_valid(), Error::::InvalidSchedule); + ensure!( + inflation.is_valid(T::BLOCKS_PER_YEAR.saturated_into()), + Error::::InvalidSchedule + ); Self::deposit_event(Event::RoundInflationSet( inflation.collator.max_rate, inflation.collator.reward_rate.per_block, @@ -2676,7 +2684,7 @@ pub mod pallet { /// - Writes: LastRewardReduction, InflationConfig /// # fn adjust_reward_rates(now: T::BlockNumber) -> Weight { - let year = now / BLOCKS_PER_YEAR.saturated_into::(); + let year = now / T::BLOCKS_PER_YEAR; let last_update = >::get(); if year > last_update { let inflation = >::get(); @@ -2690,6 +2698,7 @@ pub mod pallet { }; let new_inflation = InflationInfo::new( + T::BLOCKS_PER_YEAR.saturated_into(), inflation.collator.max_rate, c_reward_rate, inflation.delegator.max_rate, diff --git a/pallets/parachain-staking/src/mock.rs b/pallets/parachain-staking/src/mock.rs index c3eb3960e..8a044d4f1 100644 --- a/pallets/parachain-staking/src/mock.rs +++ b/pallets/parachain-staking/src/mock.rs @@ -27,7 +27,6 @@ use frame_support::{ weights::Weight, }; use pallet_authorship::EventHandler; -use runtime_common::constants::{staking::NETWORK_REWARD_RATE, treasury::INITIAL_PERIOD_LENGTH, KILT}; use sp_consensus_aura::sr25519::AuthorityId; use sp_core::H256; use sp_runtime::{ @@ -38,16 +37,16 @@ use sp_runtime::{ }; use sp_std::fmt::Debug; -pub use runtime_common::BlockNumber; - -pub type AccountId = u64; -pub type Balance = u128; -pub const BLOCKS_PER_ROUND: BlockNumber = 5; -pub const DECIMALS: Balance = KILT; - -type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; -type Block = frame_system::mocking::MockBlock; +pub(crate) type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; +pub(crate) type Block = frame_system::mocking::MockBlock; +pub(crate) type Balance = u128; +pub(crate) type AccountId = u64; +pub(crate) type BlockNumber = u64; +pub(crate) const MILLI_KILT: Balance = 10u128.pow(12); +pub(crate) const MAX_COLLATOR_STAKE: Balance = 200_000 * 1000 * MILLI_KILT; +pub(crate) const BLOCKS_PER_ROUND: BlockNumber = 5; +pub(crate) const DECIMALS: Balance = 1000 * MILLI_KILT; pub(crate) const TREASURY_ACC: AccountId = u64::MAX; // Configure a mock runtime to test the pallet. @@ -145,8 +144,8 @@ parameter_types! { pub const MinDelegatorStake: Balance = 5; pub const MinDelegation: Balance = 3; pub const MaxUnstakeRequests: u32 = 6; - pub const NetworkRewardRate: Perquintill = NETWORK_REWARD_RATE; - pub const NetworkRewardStart: BlockNumber = INITIAL_PERIOD_LENGTH; + pub const NetworkRewardRate: Perquintill = Perquintill::from_percent(10); + pub const NetworkRewardStart: BlockNumber = 5 * 5 * 60 * 24 * 36525 / 100; } pub struct ToBeneficiary(); @@ -180,6 +179,7 @@ impl Config for Test { type NetworkRewardStart = NetworkRewardStart; type NetworkRewardBeneficiary = ToBeneficiary; type WeightInfo = (); + const BLOCKS_PER_YEAR: Self::BlockNumber = 5 * 60 * 24 * 36525 / 100; } impl_opaque_keys! { @@ -236,6 +236,7 @@ impl Default for ExtBuilder { collators: vec![], blocks_per_round: BLOCKS_PER_ROUND, inflation_config: InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(10), Perquintill::from_percent(15), Perquintill::from_percent(40), @@ -274,6 +275,7 @@ impl ExtBuilder { blocks_per_round: BlockNumber, ) -> Self { self.inflation_config = InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(col_max), Perquintill::from_percent(col_rewards), Perquintill::from_percent(d_max), diff --git a/pallets/parachain-staking/src/tests.rs b/pallets/parachain-staking/src/tests.rs index f9ead1d48..20e651a4e 100644 --- a/pallets/parachain-staking/src/tests.rs +++ b/pallets/parachain-staking/src/tests.rs @@ -28,8 +28,6 @@ use pallet_balances::{BalanceLock, Error as BalancesError, Reasons}; use pallet_session::{SessionManager, ShouldEndSession}; use sp_runtime::{traits::Zero, Perbill, Permill, Perquintill, SaturatedConversion}; -use runtime_common::constants::BLOCKS_PER_YEAR; - use crate::{ mock::{ almost_equal, events, last_event, roll_to, AccountId, Balance, Balances, BlockNumber, Event as MetaEvent, @@ -1460,6 +1458,7 @@ fn round_transitions() { let d_max = 40; let d_rewards = 10; let inflation = InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(col_max), Perquintill::from_percent(col_rewards), Perquintill::from_percent(d_max), @@ -1559,6 +1558,7 @@ fn round_transitions() { assert_eq!( StakePallet::inflation_config(), InflationInfo::new( + ::BLOCKS_PER_YEAR, Perquintill::from_percent(col_max), Perquintill::from_percent(col_rewards), Perquintill::from_percent(d_max), @@ -1737,7 +1737,7 @@ fn coinbase_rewards_many_blocks_simple_check() { let inflation = StakePallet::inflation_config(); let total_issuance = ::Currency::total_issuance(); assert_eq!(total_issuance, 160_000_000 * DECIMALS); - let end_block: BlockNumber = num_of_years * BLOCKS_PER_YEAR as BlockNumber; + let end_block: BlockNumber = num_of_years * Test::BLOCKS_PER_YEAR as BlockNumber; // set round robin authoring let authors: Vec> = (0u64..=end_block).map(|i| Some(i % 2 + 1)).collect(); roll_to(end_block, authors); @@ -2207,9 +2207,9 @@ fn update_inflation() { }, }, }; - assert!(!invalid_inflation.is_valid()); + assert!(!invalid_inflation.is_valid(::BLOCKS_PER_YEAR)); invalid_inflation.collator.reward_rate.per_block = Perquintill::zero(); - assert!(!invalid_inflation.is_valid()); + assert!(!invalid_inflation.is_valid(::BLOCKS_PER_YEAR)); assert_ok!(StakePallet::set_inflation( Origin::root(), @@ -2801,7 +2801,7 @@ fn adjust_reward_rates() { .build() .execute_with(|| { let inflation_0 = StakePallet::inflation_config(); - let num_of_years = 3 * BLOCKS_PER_YEAR; + let num_of_years = 3 * ::BLOCKS_PER_YEAR; // 1 authors every block let authors: Vec> = (0u64..=num_of_years).map(|_| Some(1u64)).collect(); @@ -2813,10 +2813,11 @@ fn adjust_reward_rates() { assert!(!d_rewards_0.is_zero()); // finish first year - System::set_block_number(BLOCKS_PER_YEAR); - roll_to(BLOCKS_PER_YEAR + 1, vec![]); + System::set_block_number(::BLOCKS_PER_YEAR); + roll_to(::BLOCKS_PER_YEAR + 1, vec![]); assert_eq!(StakePallet::last_reward_reduction(), 1u64); let inflation_1 = InflationInfo::new( + ::BLOCKS_PER_YEAR, inflation_0.collator.max_rate, Perquintill::from_parts(98000000000000000), inflation_0.delegator.max_rate, @@ -2824,7 +2825,7 @@ fn adjust_reward_rates() { ); assert_eq!(StakePallet::inflation_config(), inflation_1); // reward once in 2nd year - roll_to(BLOCKS_PER_YEAR + 2, authors.clone()); + roll_to(::BLOCKS_PER_YEAR + 2, authors.clone()); let c_rewards_1 = Balances::free_balance(&1) .saturating_sub(10_000_000 * DECIMALS) .saturating_sub(c_rewards_0); @@ -2840,10 +2841,11 @@ fn adjust_reward_rates() { assert!(d_rewards_0 > d_rewards_1); // finish 2nd year - System::set_block_number(2 * BLOCKS_PER_YEAR); - roll_to(2 * BLOCKS_PER_YEAR + 1, vec![]); + System::set_block_number(2 * ::BLOCKS_PER_YEAR); + roll_to(2 * ::BLOCKS_PER_YEAR + 1, vec![]); assert_eq!(StakePallet::last_reward_reduction(), 2u64); let inflation_2 = InflationInfo::new( + ::BLOCKS_PER_YEAR, inflation_0.collator.max_rate, Perquintill::from_parts(96040000000000000), inflation_0.delegator.max_rate, @@ -2851,7 +2853,7 @@ fn adjust_reward_rates() { ); assert_eq!(StakePallet::inflation_config(), inflation_2); // reward once in 3rd year - roll_to(2 * BLOCKS_PER_YEAR + 2, authors); + roll_to(2 * ::BLOCKS_PER_YEAR + 2, authors); let c_rewards_2 = Balances::free_balance(&1) .saturating_sub(10_000_000 * DECIMALS) .saturating_sub(c_rewards_0) diff --git a/runtimes/common/Cargo.toml b/runtimes/common/Cargo.toml index f6cdbbc17..ed77dc52c 100644 --- a/runtimes/common/Cargo.toml +++ b/runtimes/common/Cargo.toml @@ -14,6 +14,7 @@ serde = {version = "1.0.132", optional = true, features = ["derive"]} smallvec = "1.7.0" attestation = {default-features = false, path = "../../pallets/attestation"} +parachain-staking = {default-features = false, path = "../../pallets/parachain-staking"} frame-support = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} frame-system = {git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v0.9.17"} diff --git a/runtimes/common/src/constants.rs b/runtimes/common/src/constants.rs index bbc38b6a4..aecde66de 100644 --- a/runtimes/common/src/constants.rs +++ b/runtimes/common/src/constants.rs @@ -22,6 +22,8 @@ use frame_support::{ }; use sp_runtime::{Perbill, Perquintill}; +use parachain_staking::InflationInfo; + use crate::{Balance, BlockNumber}; /// This determines the average expected block time that we are targetting. @@ -41,7 +43,6 @@ pub const DAYS: BlockNumber = HOURS * 24; // Julian year as Substrate handles it pub const BLOCKS_PER_YEAR: BlockNumber = DAYS * 36525 / 100; -pub const MIN_VESTED_TRANSFER_AMOUNT: Balance = 100 * MILLI_KILT; pub const MAX_COLLATOR_STAKE: Balance = 200_000 * KILT; /// One KILT @@ -66,7 +67,6 @@ pub const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 0.5 seconds of compute with a 12 second average block time. pub const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2; -/// Inflation configuration which is used at genesis pub const INFLATION_CONFIG: (Perquintill, Perquintill, Perquintill, Perquintill) = ( // max collator staking rate Perquintill::from_percent(40), @@ -78,8 +78,20 @@ pub const INFLATION_CONFIG: (Perquintill, Perquintill, Perquintill, Perquintill) Perquintill::from_percent(8), ); -/// Copied from Kusama & Polkadot runtime -pub const MAX_VESTING_SCHEDULES: u32 = 28; +/// Inflation configuration which is used at genesis +pub fn kilt_inflation_config() -> InflationInfo { + InflationInfo::new( + BLOCKS_PER_YEAR, + // max collator staking rate + Perquintill::from_percent(40), + // collator reward rate + Perquintill::from_percent(10), + // max delegator staking rate + Perquintill::from_percent(10), + // delegator reward rate + Perquintill::from_percent(8), + ) +} /// Calculate the storage deposit based on the number of storage items and the /// combined byte size of those items. @@ -91,9 +103,18 @@ pub const fn deposit(items: u32, bytes: u32) -> Balance { /// The size is checked in the runtime by a test. pub const MAX_INDICES_BYTE_LENGTH: u32 = 49; +/// Copied from Kusama & Polkadot runtime +pub const MAX_VESTING_SCHEDULES: u32 = 28; + parameter_types! { + /// Vesting Pallet. Copied from Kusama & Polkadot runtime + pub const MinVestedTransfer: Balance = 100 * MILLI_KILT; + /// Deposits per byte pub const ByteDeposit: Balance = deposit(0, 1); + /// Index Pallet. Deposit taken for an account index pub const IndicesDeposit: Balance = deposit(1, MAX_INDICES_BYTE_LENGTH); + /// CType Pallet. Per byte fee for a ctype. + pub const CtypeFee: Balance = MILLI_KILT; } pub mod attestation { @@ -102,6 +123,11 @@ pub mod attestation { /// The size is checked in the runtime by a test. pub const MAX_ATTESTATION_BYTE_LENGTH: u32 = 179; pub const ATTESTATION_DEPOSIT: Balance = deposit(2, MAX_ATTESTATION_BYTE_LENGTH); + + parameter_types! { + pub const MaxDelegatedAttestations: u32 = 1000; + pub const AttestationDeposit: Balance = ATTESTATION_DEPOSIT; + } } pub mod delegation { @@ -113,6 +139,16 @@ pub mod delegation { pub const MAX_REVOCATIONS: u32 = 5; pub const MAX_REMOVALS: u32 = MAX_REVOCATIONS; pub const MAX_CHILDREN: u32 = 1000; + + parameter_types! { + pub const MaxSignatureByteLength: u16 = MAX_SIGNATURE_BYTE_LENGTH; + pub const MaxParentChecks: u32 = MAX_PARENT_CHECKS; + pub const MaxRevocations: u32 = MAX_REVOCATIONS; + pub const MaxRemovals: u32 = MAX_REMOVALS; + #[derive(Clone)] + pub const MaxChildren: u32 = MAX_CHILDREN; + pub const DelegationDeposit: Balance = DELEGATION_DEPOSIT; + } } pub mod staking { @@ -148,6 +184,42 @@ pub mod staking { pub const MIN_DELEGATOR_STAKE: Balance = 20 * KILT; pub const NETWORK_REWARD_RATE: Perquintill = Perquintill::from_percent(10); + + parameter_types! { + /// Minimum round length is 1 hour + pub const MinBlocksPerRound: BlockNumber = MIN_BLOCKS_PER_ROUND; + /// Default length of a round/session is 2 hours + pub const DefaultBlocksPerRound: BlockNumber = DEFAULT_BLOCKS_PER_ROUND; + /// Unstaked balance can be unlocked after 7 days + pub const StakeDuration: BlockNumber = STAKE_DURATION; + /// Collator exit requests are delayed by 4 hours (2 rounds/sessions) + pub const ExitQueueDelay: u32 = 2; + /// Minimum 16 collators selected per round, default at genesis and minimum forever after + pub const MinCollators: u32 = MIN_COLLATORS; + /// At least 4 candidates which cannot leave the network if there are no other candidates. + pub const MinRequiredCollators: u32 = 4; + /// We only allow one delegation per round. + pub const MaxDelegationsPerRound: u32 = 1; + /// Maximum 25 delegators per collator at launch, might be increased later + #[derive(Debug, PartialEq)] + pub const MaxDelegatorsPerCollator: u32 = MAX_DELEGATORS_PER_COLLATOR; + /// Maximum 1 collator per delegator at launch, will be increased later + #[derive(Debug, PartialEq)] + pub const MaxCollatorsPerDelegator: u32 = 1; + /// Minimum stake required to be reserved to be a collator is 10_000 + pub const MinCollatorStake: Balance = 10_000 * KILT; + /// Minimum stake required to be reserved to be a delegator is 1000 + pub const MinDelegatorStake: Balance = MIN_DELEGATOR_STAKE; + /// Maximum number of collator candidates + #[derive(Debug, PartialEq)] + pub const MaxCollatorCandidates: u32 = MAX_CANDIDATES; + /// Maximum number of concurrent requests to unlock unstaked balance + pub const MaxUnstakeRequests: u32 = 10; + /// The starting block number for the network rewards + pub const NetworkRewardStart: BlockNumber = super::treasury::INITIAL_PERIOD_LENGTH; + /// The rate in percent for the network rewards + pub const NetworkRewardRate: Perquintill = NETWORK_REWARD_RATE; + } } pub mod governance { @@ -204,6 +276,24 @@ pub mod governance { pub const TECHNICAL_MOTION_DURATION: BlockNumber = 4 * MINUTES; #[cfg(not(feature = "fast-gov"))] pub const TECHNICAL_MOTION_DURATION: BlockNumber = 3 * DAYS; + + parameter_types! { + // Democracy Pallet + pub const LaunchPeriod: BlockNumber = LAUNCH_PERIOD; + pub const VotingPeriod: BlockNumber = VOTING_PERIOD; + pub const FastTrackVotingPeriod: BlockNumber = FAST_TRACK_VOTING_PERIOD; + pub const MinimumDeposit: Balance = MIN_DEPOSIT; + pub const EnactmentPeriod: BlockNumber = ENACTMENT_PERIOD; + pub const CooloffPeriod: BlockNumber = COOLOFF_PERIOD; + // Council Pallet + pub const CouncilMotionDuration: BlockNumber = COUNCIL_MOTION_DURATION; + pub const CouncilMaxProposals: u32 = 100; + pub const CouncilMaxMembers: u32 = 100; + // Technical Committee + pub const TechnicalMotionDuration: BlockNumber = TECHNICAL_MOTION_DURATION; + pub const TechnicalMaxProposals: u32 = 100; + pub const TechnicalMaxMembers: u32 = 100; + } } pub mod did { @@ -230,6 +320,27 @@ pub mod did { pub const MAX_NUMBER_OF_TYPES_PER_SERVICE: u32 = 1; pub const MAX_SERVICE_URL_LENGTH: u32 = 200; pub const MAX_NUMBER_OF_URLS_PER_SERVICE: u32 = 1; + + parameter_types! { + pub const MaxNewKeyAgreementKeys: u32 = MAX_KEY_AGREEMENT_KEYS; + #[derive(Debug, Clone, PartialEq)] + pub const MaxUrlLength: u32 = MAX_URL_LENGTH; + pub const MaxPublicKeysPerDid: u32 = MAX_PUBLIC_KEYS_PER_DID; + #[derive(Debug, Clone, PartialEq)] + pub const MaxTotalKeyAgreementKeys: u32 = MAX_TOTAL_KEY_AGREEMENT_KEYS; + #[derive(Debug, Clone, PartialEq)] + pub const MaxEndpointUrlsCount: u32 = MAX_ENDPOINT_URLS_COUNT; + // Standalone block time is half the duration of a parachain block. + pub const MaxBlocksTxValidity: BlockNumber = MAX_BLOCKS_TX_VALIDITY; + pub const DidDeposit: Balance = DID_DEPOSIT; + pub const DidFee: Balance = DID_FEE; + pub const MaxNumberOfServicesPerDid: u32 = MAX_NUMBER_OF_SERVICES_PER_DID; + pub const MaxServiceIdLength: u32 = MAX_SERVICE_ID_LENGTH; + pub const MaxServiceTypeLength: u32 = MAX_SERVICE_TYPE_LENGTH; + pub const MaxServiceUrlLength: u32 = MAX_SERVICE_URL_LENGTH; + pub const MaxNumberOfTypesPerService: u32 = MAX_NUMBER_OF_TYPES_PER_SERVICE; + pub const MaxNumberOfUrlsPerService: u32 = MAX_NUMBER_OF_URLS_PER_SERVICE; + } } pub mod did_lookup { @@ -238,6 +349,10 @@ pub mod did_lookup { /// The size is checked in the runtime by a test. pub const MAX_CONNECTION_BYTE_LENGTH: u32 = 80; pub const DID_CONNECTION_DEPOSIT: Balance = deposit(1, MAX_CONNECTION_BYTE_LENGTH); + + parameter_types! { + pub const DidLookupDeposit: Balance = DID_CONNECTION_DEPOSIT; + } } pub mod treasury { @@ -246,6 +361,11 @@ pub mod treasury { pub const INITIAL_PERIOD_LENGTH: BlockNumber = BLOCKS_PER_YEAR.saturating_mul(5); const YEARLY_REWARD: Balance = 2_000_000u128 * KILT; pub const INITIAL_PERIOD_REWARD_PER_BLOCK: Balance = YEARLY_REWARD / (BLOCKS_PER_YEAR as Balance); + + parameter_types! { + pub const InitialPeriodLength: BlockNumber = INITIAL_PERIOD_LENGTH; + pub const InitialPeriodReward: Balance = INITIAL_PERIOD_REWARD_PER_BLOCK; + } } pub mod proxy { @@ -272,6 +392,12 @@ pub mod web3_names { /// The size is checked in the runtime by a test. pub const MAX_NAME_BYTE_LENGTH: u32 = 121; pub const DEPOSIT: Balance = deposit(2, MAX_NAME_BYTE_LENGTH); + + parameter_types! { + pub const Web3NameDeposit: Balance = DEPOSIT; + pub const MinNameLength: u32 = MIN_LENGTH; + pub const MaxNameLength: u32 = MAX_LENGTH; + } } pub mod preimage { @@ -281,3 +407,14 @@ pub mod preimage { pub const PreimageBaseDeposit: Balance = deposit(2, 64); } } + +#[cfg(test)] +mod tests { + use super::*; + // TODO: static assert + #[allow(clippy::assertions_on_constants)] + #[test] + fn blocks_per_year_saturation() { + assert!(BLOCKS_PER_YEAR < u64::MAX); + } +} diff --git a/runtimes/peregrine/src/lib.rs b/runtimes/peregrine/src/lib.rs index a75b53b57..9e149f293 100644 --- a/runtimes/peregrine/src/lib.rs +++ b/runtimes/peregrine/src/lib.rs @@ -41,7 +41,7 @@ use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, OpaqueKeys, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, Perbill, Permill, Perquintill, RuntimeDebug, + ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug, }; use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; @@ -261,18 +261,14 @@ impl pallet_session::Config for Runtime { type WeightInfo = weights::pallet_session::WeightInfo; } -parameter_types! { - pub const MinVestedTransfer: Balance = constants::MIN_VESTED_TRANSFER_AMOUNT; -} - impl pallet_vesting::Config for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; // disable vested transfers by setting min amount to max balance - type MinVestedTransfer = MinVestedTransfer; + type MinVestedTransfer = constants::MinVestedTransfer; type WeightInfo = weights::pallet_vesting::WeightInfo; - const MAX_VESTING_SCHEDULES: u32 = runtime_common::constants::MAX_VESTING_SCHEDULES; + const MAX_VESTING_SCHEDULES: u32 = constants::MAX_VESTING_SCHEDULES; } parameter_types! { @@ -349,12 +345,6 @@ impl pallet_scheduler::Config for Runtime { } parameter_types! { - pub const LaunchPeriod: BlockNumber = constants::governance::LAUNCH_PERIOD; - pub const VotingPeriod: BlockNumber = constants::governance::VOTING_PERIOD; - pub const FastTrackVotingPeriod: BlockNumber = constants::governance::FAST_TRACK_VOTING_PERIOD; - pub const MinimumDeposit: Balance = constants::governance::MIN_DEPOSIT; - pub const EnactmentPeriod: BlockNumber = constants::governance::ENACTMENT_PERIOD; - pub const CooloffPeriod: BlockNumber = constants::governance::COOLOFF_PERIOD; pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; @@ -364,11 +354,11 @@ impl pallet_democracy::Config for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type VoteLockingPeriod = VotingPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type MinimumDeposit = MinimumDeposit; + type EnactmentPeriod = constants::governance::EnactmentPeriod; + type VoteLockingPeriod = constants::governance::VotingPeriod; + type LaunchPeriod = constants::governance::LaunchPeriod; + type VotingPeriod = constants::governance::VotingPeriod; + type MinimumDeposit = constants::governance::MinimumDeposit; /// A straight majority of the council can decide what their next motion is. type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; /// A majority can have the next scheduled referendum be a straight @@ -383,7 +373,7 @@ impl pallet_democracy::Config for Runtime { type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>; type InstantAllowed = InstantAllowed; - type FastTrackVotingPeriod = FastTrackVotingPeriod; + type FastTrackVotingPeriod = constants::governance::FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to // it. type CancellationOrigin = EnsureOneOf< @@ -400,7 +390,7 @@ impl pallet_democracy::Config for Runtime { // Any single technical committee member may veto a coming council proposal, // however they can only do it once and it lasts only for the cooloff period. type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; + type CooloffPeriod = constants::governance::CooloffPeriod; type PreimageByteDeposit = constants::ByteDeposit; type Slash = Treasury; type Scheduler = Scheduler; @@ -448,38 +438,26 @@ impl pallet_treasury::Config for Runtime { type MaxApprovals = MaxApprovals; } -parameter_types! { - pub const CouncilMotionDuration: BlockNumber = constants::governance::COUNCIL_MOTION_DURATION; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 100; -} - type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; + type MotionDuration = constants::governance::CouncilMotionDuration; + type MaxProposals = constants::governance::CouncilMaxProposals; + type MaxMembers = constants::governance::CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; } -parameter_types! { - pub const TechnicalMotionDuration: BlockNumber = constants::governance::TECHNICAL_MOTION_DURATION; - pub const TechnicalMaxProposals: u32 = 100; - pub const TechnicalMaxMembers: u32 = 100; -} - type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; - type MotionDuration = TechnicalMotionDuration; - type MaxProposals = TechnicalMaxProposals; - type MaxMembers = TechnicalMaxMembers; + type MotionDuration = constants::governance::TechnicalMotionDuration; + type MaxProposals = constants::governance::TechnicalMaxProposals; + type MaxMembers = constants::governance::TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; } @@ -493,15 +471,10 @@ impl pallet_membership::Config for Runtime { type PrimeOrigin = MoreThanHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; - type MaxMembers = TechnicalMaxMembers; + type MaxMembers = constants::governance::TechnicalMaxMembers; type WeightInfo = weights::pallet_membership::WeightInfo; } -parameter_types! { - pub const MaxDelegatedAttestations: u32 = 1000; - pub const AttestationDeposit: Balance = constants::attestation::ATTESTATION_DEPOSIT; -} - impl attestation::Config for Runtime { type EnsureOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; @@ -510,23 +483,13 @@ impl attestation::Config for Runtime { type WeightInfo = weights::attestation::WeightInfo; type Currency = Balances; - type Deposit = AttestationDeposit; - type MaxDelegatedAttestations = MaxDelegatedAttestations; + type Deposit = constants::attestation::AttestationDeposit; + type MaxDelegatedAttestations = constants::attestation::MaxDelegatedAttestations; type AttesterId = DidIdentifier; type AuthorizationId = AuthorizationId<::DelegationNodeId>; type AccessControl = PalletAuthorize>; } -parameter_types! { - pub const MaxSignatureByteLength: u16 = constants::delegation::MAX_SIGNATURE_BYTE_LENGTH; - pub const MaxParentChecks: u32 = constants::delegation::MAX_PARENT_CHECKS; - pub const MaxRevocations: u32 = constants::delegation::MAX_REVOCATIONS; - pub const MaxRemovals: u32 = constants::delegation::MAX_REMOVALS; - #[derive(Clone)] - pub const MaxChildren: u32 = constants::delegation::MAX_CHILDREN; - pub const DelegationDeposit: Balance = constants::delegation::DELEGATION_DEPOSIT; -} - impl delegation::Config for Runtime { type DelegationEntityId = DidIdentifier; type DelegationNodeId = Hash; @@ -545,24 +508,20 @@ impl delegation::Config for Runtime { type DelegationSignatureVerification = AlwaysVerify, Self::Signature>; type Event = Event; - type MaxSignatureByteLength = MaxSignatureByteLength; - type MaxParentChecks = MaxParentChecks; - type MaxRevocations = MaxRevocations; - type MaxRemovals = MaxRemovals; - type MaxChildren = MaxChildren; + type MaxSignatureByteLength = constants::delegation::MaxSignatureByteLength; + type MaxParentChecks = constants::delegation::MaxParentChecks; + type MaxRevocations = constants::delegation::MaxRevocations; + type MaxRemovals = constants::delegation::MaxRemovals; + type MaxChildren = constants::delegation::MaxChildren; type WeightInfo = weights::delegation::WeightInfo; type Currency = Balances; - type Deposit = DelegationDeposit; -} - -parameter_types! { - pub const Fee: Balance = MILLI_KILT; + type Deposit = constants::delegation::DelegationDeposit; } impl ctype::Config for Runtime { type CtypeCreatorId = AccountId; type Currency = Balances; - type Fee = Fee; + type Fee = constants::CtypeFee; type FeeCollector = Treasury; type EnsureOrigin = did::EnsureDidOrigin; @@ -572,35 +531,14 @@ impl ctype::Config for Runtime { type WeightInfo = weights::ctype::WeightInfo; } -parameter_types! { - pub const MaxNewKeyAgreementKeys: u32 = constants::did::MAX_KEY_AGREEMENT_KEYS; - #[derive(Debug, Clone, PartialEq)] - pub const MaxUrlLength: u32 = constants::did::MAX_URL_LENGTH; - pub const MaxPublicKeysPerDid: u32 = constants::did::MAX_PUBLIC_KEYS_PER_DID; - #[derive(Debug, Clone, PartialEq)] - pub const MaxTotalKeyAgreementKeys: u32 = constants::did::MAX_TOTAL_KEY_AGREEMENT_KEYS; - #[derive(Debug, Clone, PartialEq)] - pub const MaxEndpointUrlsCount: u32 = constants::did::MAX_ENDPOINT_URLS_COUNT; - // Standalone block time is half the duration of a parachain block. - pub const MaxBlocksTxValidity: BlockNumber = constants::did::MAX_BLOCKS_TX_VALIDITY; - pub const DidDeposit: Balance = constants::did::DID_DEPOSIT; - pub const DidFee: Balance = constants::did::DID_FEE; - pub const MaxNumberOfServicesPerDid: u32 = constants::did::MAX_NUMBER_OF_SERVICES_PER_DID; - pub const MaxServiceIdLength: u32 = constants::did::MAX_SERVICE_ID_LENGTH; - pub const MaxServiceTypeLength: u32 = constants::did::MAX_SERVICE_TYPE_LENGTH; - pub const MaxServiceUrlLength: u32 = constants::did::MAX_SERVICE_URL_LENGTH; - pub const MaxNumberOfTypesPerService: u32 = constants::did::MAX_NUMBER_OF_TYPES_PER_SERVICE; - pub const MaxNumberOfUrlsPerService: u32 = constants::did::MAX_NUMBER_OF_URLS_PER_SERVICE; -} - impl did::Config for Runtime { type DidIdentifier = DidIdentifier; type Event = Event; type Call = Call; type Origin = Origin; type Currency = Balances; - type Deposit = DidDeposit; - type Fee = DidFee; + type Deposit = constants::did::DidDeposit; + type Fee = constants::did::DidFee; type FeeCollector = Treasury; #[cfg(not(feature = "runtime-benchmarks"))] @@ -613,23 +551,19 @@ impl did::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] type OriginSuccess = DidIdentifier; - type MaxNewKeyAgreementKeys = MaxNewKeyAgreementKeys; - type MaxTotalKeyAgreementKeys = MaxTotalKeyAgreementKeys; - type MaxPublicKeysPerDid = MaxPublicKeysPerDid; - type MaxBlocksTxValidity = MaxBlocksTxValidity; - type MaxNumberOfServicesPerDid = MaxNumberOfServicesPerDid; - type MaxServiceIdLength = MaxServiceIdLength; - type MaxServiceTypeLength = MaxServiceTypeLength; - type MaxServiceUrlLength = MaxServiceUrlLength; - type MaxNumberOfTypesPerService = MaxNumberOfTypesPerService; - type MaxNumberOfUrlsPerService = MaxNumberOfUrlsPerService; + type MaxNewKeyAgreementKeys = constants::did::MaxNewKeyAgreementKeys; + type MaxTotalKeyAgreementKeys = constants::did::MaxTotalKeyAgreementKeys; + type MaxPublicKeysPerDid = constants::did::MaxPublicKeysPerDid; + type MaxBlocksTxValidity = constants::did::MaxBlocksTxValidity; + type MaxNumberOfServicesPerDid = constants::did::MaxNumberOfServicesPerDid; + type MaxServiceIdLength = constants::did::MaxServiceIdLength; + type MaxServiceTypeLength = constants::did::MaxServiceTypeLength; + type MaxServiceUrlLength = constants::did::MaxServiceUrlLength; + type MaxNumberOfTypesPerService = constants::did::MaxNumberOfTypesPerService; + type MaxNumberOfUrlsPerService = constants::did::MaxNumberOfUrlsPerService; type WeightInfo = weights::did::WeightInfo; } -parameter_types! { - pub const DidLookupDeposit: Balance = constants::did_lookup::DID_CONNECTION_DEPOSIT; -} - impl pallet_did_lookup::Config for Runtime { type Event = Event; type Signature = Signature; @@ -637,7 +571,7 @@ impl pallet_did_lookup::Config for Runtime { type DidIdentifier = DidIdentifier; type Currency = Balances; - type Deposit = DidLookupDeposit; + type Deposit = constants::did_lookup::DidLookupDeposit; type EnsureOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; @@ -645,98 +579,59 @@ impl pallet_did_lookup::Config for Runtime { type WeightInfo = weights::pallet_did_lookup::WeightInfo; } -parameter_types! { - pub const Web3NameDeposit: Balance = constants::web3_names::DEPOSIT; - pub const MinNameLength: u32 = constants::web3_names::MIN_LENGTH; - pub const MaxNameLength: u32 = constants::web3_names::MAX_LENGTH; -} - impl pallet_web3_names::Config for Runtime { type BanOrigin = EnsureRoot; type OwnerOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; type Currency = Balances; - type Deposit = Web3NameDeposit; + type Deposit = constants::web3_names::Web3NameDeposit; type Event = Event; - type MaxNameLength = MaxNameLength; - type MinNameLength = MinNameLength; - type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; + type MaxNameLength = constants::web3_names::MaxNameLength; + type MinNameLength = constants::web3_names::MinNameLength; + type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name< + Runtime, + constants::web3_names::MinNameLength, + constants::web3_names::MaxNameLength, + >; type Web3NameOwner = DidIdentifier; type WeightInfo = weights::pallet_web3_names::WeightInfo; } -parameter_types! { - pub const InitialPeriodLength: BlockNumber = constants::treasury::INITIAL_PERIOD_LENGTH; - pub const InitialPeriodReward: Balance = constants::treasury::INITIAL_PERIOD_REWARD_PER_BLOCK; -} - impl pallet_inflation::Config for Runtime { type Currency = Balances; - type InitialPeriodLength = InitialPeriodLength; - type InitialPeriodReward = InitialPeriodReward; + type InitialPeriodLength = constants::treasury::InitialPeriodLength; + type InitialPeriodReward = constants::treasury::InitialPeriodReward; type Beneficiary = Treasury; type WeightInfo = weights::pallet_inflation::WeightInfo; } -parameter_types! { - /// Minimum round length is 1 hour - pub const MinBlocksPerRound: BlockNumber = constants::staking::MIN_BLOCKS_PER_ROUND; - /// Default length of a round/session is 2 hours - pub const DefaultBlocksPerRound: BlockNumber = constants::staking::DEFAULT_BLOCKS_PER_ROUND; - /// Unstaked balance can be unlocked after 7 days - pub const StakeDuration: BlockNumber = constants::staking::STAKE_DURATION; - /// Collator exit requests are delayed by 4 hours (2 rounds/sessions) - pub const ExitQueueDelay: u32 = 2; - /// Minimum 16 collators selected per round, default at genesis and minimum forever after - pub const MinCollators: u32 = constants::staking::MIN_COLLATORS; - /// At least 4 candidates which cannot leave the network if there are no other candidates. - pub const MinRequiredCollators: u32 = 4; - /// We only allow one delegation per round. - pub const MaxDelegationsPerRound: u32 = 1; - /// Maximum 25 delegators per collator at launch, might be increased later - #[derive(Debug, PartialEq)] - pub const MaxDelegatorsPerCollator: u32 = constants::staking::MAX_DELEGATORS_PER_COLLATOR; - /// Maximum 1 collator per delegator at launch, will be increased later - #[derive(Debug, PartialEq)] - pub const MaxCollatorsPerDelegator: u32 = 1; - /// Minimum stake required to be reserved to be a collator is 10_000 - pub const MinCollatorStake: Balance = 10_000 * KILT; - /// Minimum stake required to be reserved to be a delegator is 1000 - pub const MinDelegatorStake: Balance = constants::staking::MIN_DELEGATOR_STAKE; - /// Maximum number of collator candidates - #[derive(Debug, PartialEq)] - pub const MaxCollatorCandidates: u32 = constants::staking::MAX_CANDIDATES; - /// Maximum number of concurrent requests to unlock unstaked balance - pub const MaxUnstakeRequests: u32 = 10; - /// The starting block number for the network rewards - pub const NetworkRewardStart: BlockNumber = constants::treasury::INITIAL_PERIOD_LENGTH; - /// The rate in percent for the network rewards - pub const NetworkRewardRate: Perquintill = constants::staking::NETWORK_REWARD_RATE; -} - impl parachain_staking::Config for Runtime { type Event = Event; type Currency = Balances; type CurrencyBalance = Balance; - type MinBlocksPerRound = MinBlocksPerRound; - type DefaultBlocksPerRound = DefaultBlocksPerRound; - type StakeDuration = StakeDuration; - type ExitQueueDelay = ExitQueueDelay; - type MinCollators = MinCollators; - type MinRequiredCollators = MinRequiredCollators; - type MaxDelegationsPerRound = MaxDelegationsPerRound; - type MaxDelegatorsPerCollator = MaxDelegatorsPerCollator; - type MaxCollatorsPerDelegator = MaxCollatorsPerDelegator; - type MinCollatorStake = MinCollatorStake; - type MinCollatorCandidateStake = MinCollatorStake; - type MaxTopCandidates = MaxCollatorCandidates; - type MinDelegation = MinDelegatorStake; - type MinDelegatorStake = MinDelegatorStake; - type MaxUnstakeRequests = MaxUnstakeRequests; - type NetworkRewardRate = NetworkRewardRate; - type NetworkRewardStart = NetworkRewardStart; + + type MinBlocksPerRound = constants::staking::MinBlocksPerRound; + type DefaultBlocksPerRound = constants::staking::DefaultBlocksPerRound; + type StakeDuration = constants::staking::StakeDuration; + type ExitQueueDelay = constants::staking::ExitQueueDelay; + type MinCollators = constants::staking::MinCollators; + type MinRequiredCollators = constants::staking::MinRequiredCollators; + type MaxDelegationsPerRound = constants::staking::MaxDelegationsPerRound; + type MaxDelegatorsPerCollator = constants::staking::MaxDelegatorsPerCollator; + type MaxCollatorsPerDelegator = constants::staking::MaxCollatorsPerDelegator; + type MinCollatorStake = constants::staking::MinCollatorStake; + type MinCollatorCandidateStake = constants::staking::MinCollatorStake; + type MaxTopCandidates = constants::staking::MaxCollatorCandidates; + type MinDelegation = constants::staking::MinDelegatorStake; + type MinDelegatorStake = constants::staking::MinDelegatorStake; + type MaxUnstakeRequests = constants::staking::MaxUnstakeRequests; + type NetworkRewardRate = constants::staking::NetworkRewardRate; + type NetworkRewardStart = constants::staking::NetworkRewardStart; + type NetworkRewardBeneficiary = Treasury; type WeightInfo = weights::parachain_staking::WeightInfo; + + const BLOCKS_PER_YEAR: Self::BlockNumber = constants::BLOCKS_PER_YEAR; } impl pallet_utility::Config for Runtime { diff --git a/runtimes/spiritnet/src/lib.rs b/runtimes/spiritnet/src/lib.rs index 1561f5b01..51ee5764f 100644 --- a/runtimes/spiritnet/src/lib.rs +++ b/runtimes/spiritnet/src/lib.rs @@ -41,7 +41,7 @@ use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, OpaqueKeys, Verify}, transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, Perbill, Permill, Perquintill, RuntimeDebug, + ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug, }; use sp_std::{cmp::Ordering, prelude::*}; use sp_version::RuntimeVersion; @@ -266,18 +266,14 @@ impl pallet_session::Config for Runtime { type WeightInfo = weights::pallet_session::WeightInfo; } -parameter_types! { - pub const MinVestedTransfer: Balance = constants::MIN_VESTED_TRANSFER_AMOUNT; -} - impl pallet_vesting::Config for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; // disable vested transfers by setting min amount to max balance - type MinVestedTransfer = MinVestedTransfer; + type MinVestedTransfer = constants::MinVestedTransfer; type WeightInfo = weights::pallet_vesting::WeightInfo; - const MAX_VESTING_SCHEDULES: u32 = runtime_common::constants::MAX_VESTING_SCHEDULES; + const MAX_VESTING_SCHEDULES: u32 = constants::MAX_VESTING_SCHEDULES; } parameter_types! { @@ -354,12 +350,6 @@ impl pallet_scheduler::Config for Runtime { } parameter_types! { - pub const LaunchPeriod: BlockNumber = constants::governance::LAUNCH_PERIOD; - pub const VotingPeriod: BlockNumber = constants::governance::VOTING_PERIOD; - pub const FastTrackVotingPeriod: BlockNumber = constants::governance::FAST_TRACK_VOTING_PERIOD; - pub const MinimumDeposit: Balance = constants::governance::MIN_DEPOSIT; - pub const EnactmentPeriod: BlockNumber = constants::governance::ENACTMENT_PERIOD; - pub const CooloffPeriod: BlockNumber = constants::governance::COOLOFF_PERIOD; pub const InstantAllowed: bool = true; pub const MaxVotes: u32 = 100; pub const MaxProposals: u32 = 100; @@ -369,11 +359,11 @@ impl pallet_democracy::Config for Runtime { type Proposal = Call; type Event = Event; type Currency = Balances; - type EnactmentPeriod = EnactmentPeriod; - type VoteLockingPeriod = VotingPeriod; - type LaunchPeriod = LaunchPeriod; - type VotingPeriod = VotingPeriod; - type MinimumDeposit = MinimumDeposit; + type EnactmentPeriod = constants::governance::EnactmentPeriod; + type VoteLockingPeriod = constants::governance::VotingPeriod; + type LaunchPeriod = constants::governance::LaunchPeriod; + type VotingPeriod = constants::governance::VotingPeriod; + type MinimumDeposit = constants::governance::MinimumDeposit; /// A straight majority of the council can decide what their next motion is. type ExternalOrigin = pallet_collective::EnsureProportionAtLeast<_1, _2, AccountId, CouncilCollective>; /// A majority can have the next scheduled referendum be a straight @@ -388,7 +378,7 @@ impl pallet_democracy::Config for Runtime { type FastTrackOrigin = pallet_collective::EnsureProportionAtLeast<_2, _3, AccountId, TechnicalCollective>; type InstantOrigin = pallet_collective::EnsureProportionAtLeast<_1, _1, AccountId, TechnicalCollective>; type InstantAllowed = InstantAllowed; - type FastTrackVotingPeriod = FastTrackVotingPeriod; + type FastTrackVotingPeriod = constants::governance::FastTrackVotingPeriod; // To cancel a proposal which has been passed, 2/3 of the council must agree to // it. type CancellationOrigin = EnsureOneOf< @@ -405,7 +395,7 @@ impl pallet_democracy::Config for Runtime { // Any single technical committee member may veto a coming council proposal, // however they can only do it once and it lasts only for the cooloff period. type VetoOrigin = pallet_collective::EnsureMember; - type CooloffPeriod = CooloffPeriod; + type CooloffPeriod = constants::governance::CooloffPeriod; type PreimageByteDeposit = constants::ByteDeposit; type Slash = Treasury; type Scheduler = Scheduler; @@ -453,38 +443,26 @@ impl pallet_treasury::Config for Runtime { type MaxApprovals = MaxApprovals; } -parameter_types! { - pub const CouncilMotionDuration: BlockNumber = constants::governance::COUNCIL_MOTION_DURATION; - pub const CouncilMaxProposals: u32 = 100; - pub const CouncilMaxMembers: u32 = 100; -} - type CouncilCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = CouncilMaxMembers; + type MotionDuration = constants::governance::CouncilMotionDuration; + type MaxProposals = constants::governance::CouncilMaxProposals; + type MaxMembers = constants::governance::CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; } -parameter_types! { - pub const TechnicalMotionDuration: BlockNumber = constants::governance::TECHNICAL_MOTION_DURATION; - pub const TechnicalMaxProposals: u32 = 100; - pub const TechnicalMaxMembers: u32 = 100; -} - type TechnicalCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { type Origin = Origin; type Proposal = Call; type Event = Event; - type MotionDuration = TechnicalMotionDuration; - type MaxProposals = TechnicalMaxProposals; - type MaxMembers = TechnicalMaxMembers; + type MotionDuration = constants::governance::TechnicalMotionDuration; + type MaxProposals = constants::governance::TechnicalMaxProposals; + type MaxMembers = constants::governance::TechnicalMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type WeightInfo = weights::pallet_collective::WeightInfo; } @@ -498,15 +476,10 @@ impl pallet_membership::Config for Runtime { type PrimeOrigin = MoreThanHalfCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; - type MaxMembers = TechnicalMaxMembers; + type MaxMembers = constants::governance::TechnicalMaxMembers; type WeightInfo = weights::pallet_membership::WeightInfo; } -parameter_types! { - pub const MaxDelegatedAttestations: u32 = 1000; - pub const AttestationDeposit: Balance = constants::attestation::ATTESTATION_DEPOSIT; -} - impl attestation::Config for Runtime { type EnsureOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; @@ -515,23 +488,13 @@ impl attestation::Config for Runtime { type WeightInfo = weights::attestation::WeightInfo; type Currency = Balances; - type Deposit = AttestationDeposit; - type MaxDelegatedAttestations = MaxDelegatedAttestations; + type Deposit = constants::attestation::AttestationDeposit; + type MaxDelegatedAttestations = constants::attestation::MaxDelegatedAttestations; type AttesterId = DidIdentifier; type AuthorizationId = AuthorizationId<::DelegationNodeId>; type AccessControl = PalletAuthorize>; } -parameter_types! { - pub const MaxSignatureByteLength: u16 = constants::delegation::MAX_SIGNATURE_BYTE_LENGTH; - pub const MaxParentChecks: u32 = constants::delegation::MAX_PARENT_CHECKS; - pub const MaxRevocations: u32 = constants::delegation::MAX_REVOCATIONS; - pub const MaxRemovals: u32 = constants::delegation::MAX_REMOVALS; - #[derive(Clone)] - pub const MaxChildren: u32 = constants::delegation::MAX_CHILDREN; - pub const DelegationDeposit: Balance = constants::delegation::DELEGATION_DEPOSIT; -} - impl delegation::Config for Runtime { type DelegationEntityId = DidIdentifier; type DelegationNodeId = Hash; @@ -550,24 +513,20 @@ impl delegation::Config for Runtime { type DelegationSignatureVerification = AlwaysVerify, Self::Signature>; type Event = Event; - type MaxSignatureByteLength = MaxSignatureByteLength; - type MaxParentChecks = MaxParentChecks; - type MaxRevocations = MaxRevocations; - type MaxRemovals = MaxRemovals; - type MaxChildren = MaxChildren; + type MaxSignatureByteLength = constants::delegation::MaxSignatureByteLength; + type MaxParentChecks = constants::delegation::MaxParentChecks; + type MaxRevocations = constants::delegation::MaxRevocations; + type MaxRemovals = constants::delegation::MaxRemovals; + type MaxChildren = constants::delegation::MaxChildren; type WeightInfo = weights::delegation::WeightInfo; type Currency = Balances; - type Deposit = DelegationDeposit; -} - -parameter_types! { - pub const Fee: Balance = MILLI_KILT; + type Deposit = constants::delegation::DelegationDeposit; } impl ctype::Config for Runtime { type CtypeCreatorId = AccountId; type Currency = Balances; - type Fee = Fee; + type Fee = constants::CtypeFee; type FeeCollector = Treasury; type EnsureOrigin = did::EnsureDidOrigin; @@ -577,35 +536,14 @@ impl ctype::Config for Runtime { type WeightInfo = weights::ctype::WeightInfo; } -parameter_types! { - pub const MaxNewKeyAgreementKeys: u32 = constants::did::MAX_KEY_AGREEMENT_KEYS; - #[derive(Debug, Clone, PartialEq)] - pub const MaxUrlLength: u32 = constants::did::MAX_URL_LENGTH; - pub const MaxPublicKeysPerDid: u32 = constants::did::MAX_PUBLIC_KEYS_PER_DID; - #[derive(Debug, Clone, PartialEq)] - pub const MaxTotalKeyAgreementKeys: u32 = constants::did::MAX_TOTAL_KEY_AGREEMENT_KEYS; - #[derive(Debug, Clone, PartialEq)] - pub const MaxEndpointUrlsCount: u32 = constants::did::MAX_ENDPOINT_URLS_COUNT; - // Standalone block time is half the duration of a parachain block. - pub const MaxBlocksTxValidity: BlockNumber = constants::did::MAX_BLOCKS_TX_VALIDITY; - pub const DidDeposit: Balance = constants::did::DID_DEPOSIT; - pub const DidFee: Balance = constants::did::DID_FEE; - pub const MaxNumberOfServicesPerDid: u32 = constants::did::MAX_NUMBER_OF_SERVICES_PER_DID; - pub const MaxServiceIdLength: u32 = constants::did::MAX_SERVICE_ID_LENGTH; - pub const MaxServiceTypeLength: u32 = constants::did::MAX_SERVICE_TYPE_LENGTH; - pub const MaxServiceUrlLength: u32 = constants::did::MAX_SERVICE_URL_LENGTH; - pub const MaxNumberOfTypesPerService: u32 = constants::did::MAX_NUMBER_OF_TYPES_PER_SERVICE; - pub const MaxNumberOfUrlsPerService: u32 = constants::did::MAX_NUMBER_OF_URLS_PER_SERVICE; -} - impl did::Config for Runtime { type DidIdentifier = DidIdentifier; type Event = Event; type Call = Call; type Origin = Origin; type Currency = Balances; - type Deposit = DidDeposit; - type Fee = DidFee; + type Deposit = constants::did::DidDeposit; + type Fee = constants::did::DidFee; type FeeCollector = Treasury; #[cfg(not(feature = "runtime-benchmarks"))] @@ -618,23 +556,19 @@ impl did::Config for Runtime { #[cfg(feature = "runtime-benchmarks")] type OriginSuccess = DidIdentifier; - type MaxNewKeyAgreementKeys = MaxNewKeyAgreementKeys; - type MaxTotalKeyAgreementKeys = MaxTotalKeyAgreementKeys; - type MaxPublicKeysPerDid = MaxPublicKeysPerDid; - type MaxBlocksTxValidity = MaxBlocksTxValidity; - type MaxNumberOfServicesPerDid = MaxNumberOfServicesPerDid; - type MaxServiceIdLength = MaxServiceIdLength; - type MaxServiceTypeLength = MaxServiceTypeLength; - type MaxServiceUrlLength = MaxServiceUrlLength; - type MaxNumberOfTypesPerService = MaxNumberOfTypesPerService; - type MaxNumberOfUrlsPerService = MaxNumberOfUrlsPerService; + type MaxNewKeyAgreementKeys = constants::did::MaxNewKeyAgreementKeys; + type MaxTotalKeyAgreementKeys = constants::did::MaxTotalKeyAgreementKeys; + type MaxPublicKeysPerDid = constants::did::MaxPublicKeysPerDid; + type MaxBlocksTxValidity = constants::did::MaxBlocksTxValidity; + type MaxNumberOfServicesPerDid = constants::did::MaxNumberOfServicesPerDid; + type MaxServiceIdLength = constants::did::MaxServiceIdLength; + type MaxServiceTypeLength = constants::did::MaxServiceTypeLength; + type MaxServiceUrlLength = constants::did::MaxServiceUrlLength; + type MaxNumberOfTypesPerService = constants::did::MaxNumberOfTypesPerService; + type MaxNumberOfUrlsPerService = constants::did::MaxNumberOfUrlsPerService; type WeightInfo = weights::did::WeightInfo; } -parameter_types! { - pub const DidLookupDeposit: Balance = constants::did_lookup::DID_CONNECTION_DEPOSIT; -} - impl pallet_did_lookup::Config for Runtime { type Event = Event; type Signature = Signature; @@ -642,7 +576,7 @@ impl pallet_did_lookup::Config for Runtime { type DidIdentifier = DidIdentifier; type Currency = Balances; - type Deposit = DidLookupDeposit; + type Deposit = constants::did_lookup::DidLookupDeposit; type EnsureOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; @@ -650,98 +584,59 @@ impl pallet_did_lookup::Config for Runtime { type WeightInfo = weights::pallet_did_lookup::WeightInfo; } -parameter_types! { - pub const Web3NameDeposit: Balance = constants::web3_names::DEPOSIT; - pub const MinNameLength: u32 = constants::web3_names::MIN_LENGTH; - pub const MaxNameLength: u32 = constants::web3_names::MAX_LENGTH; -} - impl pallet_web3_names::Config for Runtime { type BanOrigin = EnsureRoot; type OwnerOrigin = did::EnsureDidOrigin; type OriginSuccess = did::DidRawOrigin; type Currency = Balances; - type Deposit = Web3NameDeposit; + type Deposit = constants::web3_names::Web3NameDeposit; type Event = Event; - type MaxNameLength = MaxNameLength; - type MinNameLength = MinNameLength; - type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name; + type MaxNameLength = constants::web3_names::MaxNameLength; + type MinNameLength = constants::web3_names::MinNameLength; + type Web3Name = pallet_web3_names::web3_name::AsciiWeb3Name< + Runtime, + constants::web3_names::MinNameLength, + constants::web3_names::MaxNameLength, + >; type Web3NameOwner = DidIdentifier; type WeightInfo = weights::pallet_web3_names::WeightInfo; } -parameter_types! { - pub const InitialPeriodLength: BlockNumber = constants::treasury::INITIAL_PERIOD_LENGTH; - pub const InitialPeriodReward: Balance = constants::treasury::INITIAL_PERIOD_REWARD_PER_BLOCK; -} - impl pallet_inflation::Config for Runtime { type Currency = Balances; - type InitialPeriodLength = InitialPeriodLength; - type InitialPeriodReward = InitialPeriodReward; + type InitialPeriodLength = constants::treasury::InitialPeriodLength; + type InitialPeriodReward = constants::treasury::InitialPeriodReward; type Beneficiary = Treasury; type WeightInfo = weights::pallet_inflation::WeightInfo; } -parameter_types! { - /// Minimum round length is 1 hour - pub const MinBlocksPerRound: BlockNumber = constants::staking::MIN_BLOCKS_PER_ROUND; - /// Default length of a round/session is 2 hours - pub const DefaultBlocksPerRound: BlockNumber = constants::staking::DEFAULT_BLOCKS_PER_ROUND; - /// Unstaked balance can be unlocked after 7 days - pub const StakeDuration: BlockNumber = constants::staking::STAKE_DURATION; - /// Collator exit requests are delayed by 4 hours (2 rounds/sessions) - pub const ExitQueueDelay: u32 = 2; - /// Minimum 16 collators selected per round, default at genesis and minimum forever after - pub const MinCollators: u32 = constants::staking::MIN_COLLATORS; - /// At least 4 candidates which cannot leave the network if there are no other candidates. - pub const MinRequiredCollators: u32 = 4; - /// We only allow one delegation per round. - pub const MaxDelegationsPerRound: u32 = 1; - /// Maximum 25 delegators per collator at launch, might be increased later - #[derive(Debug, PartialEq)] - pub const MaxDelegatorsPerCollator: u32 = constants::staking::MAX_DELEGATORS_PER_COLLATOR; - /// Maximum 1 collator per delegator at launch, will be increased later - #[derive(Debug, PartialEq)] - pub const MaxCollatorsPerDelegator: u32 = 1; - /// Minimum stake required to be reserved to be a collator is 10_000 - pub const MinCollatorStake: Balance = 10_000 * KILT; - /// Minimum stake required to be reserved to be a delegator is 1000 - pub const MinDelegatorStake: Balance = constants::staking::MIN_DELEGATOR_STAKE; - /// Maximum number of collator candidates - #[derive(Debug, PartialEq)] - pub const MaxCollatorCandidates: u32 = constants::staking::MAX_CANDIDATES; - /// Maximum number of concurrent requests to unlock unstaked balance - pub const MaxUnstakeRequests: u32 = 10; - /// The starting block number for the network rewards - pub const NetworkRewardStart: BlockNumber = constants::treasury::INITIAL_PERIOD_LENGTH; - /// The rate in percent for the network rewards - pub const NetworkRewardRate: Perquintill = constants::staking::NETWORK_REWARD_RATE; -} - impl parachain_staking::Config for Runtime { type Event = Event; type Currency = Balances; type CurrencyBalance = Balance; - type MinBlocksPerRound = MinBlocksPerRound; - type DefaultBlocksPerRound = DefaultBlocksPerRound; - type StakeDuration = StakeDuration; - type ExitQueueDelay = ExitQueueDelay; - type MinCollators = MinCollators; - type MinRequiredCollators = MinRequiredCollators; - type MaxDelegationsPerRound = MaxDelegationsPerRound; - type MaxDelegatorsPerCollator = MaxDelegatorsPerCollator; - type MaxCollatorsPerDelegator = MaxCollatorsPerDelegator; - type MinCollatorStake = MinCollatorStake; - type MinCollatorCandidateStake = MinCollatorStake; - type MaxTopCandidates = MaxCollatorCandidates; - type MinDelegation = MinDelegatorStake; - type MinDelegatorStake = MinDelegatorStake; - type MaxUnstakeRequests = MaxUnstakeRequests; - type NetworkRewardRate = NetworkRewardRate; - type NetworkRewardStart = NetworkRewardStart; + + type MinBlocksPerRound = constants::staking::MinBlocksPerRound; + type DefaultBlocksPerRound = constants::staking::DefaultBlocksPerRound; + type StakeDuration = constants::staking::StakeDuration; + type ExitQueueDelay = constants::staking::ExitQueueDelay; + type MinCollators = constants::staking::MinCollators; + type MinRequiredCollators = constants::staking::MinRequiredCollators; + type MaxDelegationsPerRound = constants::staking::MaxDelegationsPerRound; + type MaxDelegatorsPerCollator = constants::staking::MaxDelegatorsPerCollator; + type MaxCollatorsPerDelegator = constants::staking::MaxCollatorsPerDelegator; + type MinCollatorStake = constants::staking::MinCollatorStake; + type MinCollatorCandidateStake = constants::staking::MinCollatorStake; + type MaxTopCandidates = constants::staking::MaxCollatorCandidates; + type MinDelegation = constants::staking::MinDelegatorStake; + type MinDelegatorStake = constants::staking::MinDelegatorStake; + type MaxUnstakeRequests = constants::staking::MaxUnstakeRequests; + type NetworkRewardRate = constants::staking::NetworkRewardRate; + type NetworkRewardStart = constants::staking::NetworkRewardStart; + type NetworkRewardBeneficiary = Treasury; type WeightInfo = weights::parachain_staking::WeightInfo; + + const BLOCKS_PER_YEAR: Self::BlockNumber = constants::BLOCKS_PER_YEAR; } impl pallet_utility::Config for Runtime { diff --git a/runtimes/standalone/src/lib.rs b/runtimes/standalone/src/lib.rs index f15f7964c..4a98928ed 100644 --- a/runtimes/standalone/src/lib.rs +++ b/runtimes/standalone/src/lib.rs @@ -496,17 +496,13 @@ impl pallet_authorship::Config for Runtime { type EventHandler = (); } -parameter_types! { - pub const MinVestedTransfer: Balance = constants::MIN_VESTED_TRANSFER_AMOUNT; -} - impl pallet_vesting::Config for Runtime { type Event = Event; type Currency = Balances; type BlockNumberToBalance = ConvertInto; // disable vested transfers by setting min amount to max balance - type MinVestedTransfer = MinVestedTransfer; - const MAX_VESTING_SCHEDULES: u32 = runtime_common::constants::MAX_VESTING_SCHEDULES; + type MinVestedTransfer = constants::MinVestedTransfer; + const MAX_VESTING_SCHEDULES: u32 = constants::MAX_VESTING_SCHEDULES; type WeightInfo = (); }