From 6518a23e4131b7df875951978416c14e413a26b0 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:23:48 +0100 Subject: [PATCH 01/16] refactor(apis): group apis in its own module --- runtime/testnet/src/apis.rs | 485 ++++++++++++++++++++++++++++++++++++ 1 file changed, 485 insertions(+) create mode 100644 runtime/testnet/src/apis.rs diff --git a/runtime/testnet/src/apis.rs b/runtime/testnet/src/apis.rs new file mode 100644 index 00000000..74c8efd9 --- /dev/null +++ b/runtime/testnet/src/apis.rs @@ -0,0 +1,485 @@ +use alloc::vec::Vec; + +use codec::Encode; +use frame_support::{ + genesis_builder_helper::{build_state, get_preset}, + traits::tokens::{nonfungibles_v2::Inspect, Fortitude::Polite, Preservation::Preserve}, +}; +use pallet_revive::{evm::H160, AddressMapper}; +use sp_api::impl_runtime_apis; +use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; +use sp_runtime::{ + traits::Block as BlockT, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, +}; + +// Local module imports +use super::{ + config::system::RuntimeBlockWeights, genesis, AccountId, AuraId, Balance, Balances, Block, + BlockNumber, BlockWeights, Contracts, EventRecord, Executive, ExtrinsicInclusionMode, Hash, + InherentDataExt, Nfts, Nonce, ParachainSystem, Revive, Runtime, RuntimeCall, + RuntimeGenesisConfig, RuntimeOrigin, RuntimeVersion, SessionKeys, System, TransactionPayment, + UncheckedExtrinsic, Weight, CONTRACTS_DEBUG_OUTPUT, CONTRACTS_EVENTS, VERSION, *, +}; + +impl_runtime_apis! { + + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + Runtime::impl_slot_duration() + } + + fn authorities() -> Vec { + pallet_aura::Authorities::::get().into_inner() + } + } + + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block) + } + + fn initialize_block(header: &::Header) -> ExtrinsicInclusionMode{ + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + + fn metadata_at_version(version: u32) -> Option { + Runtime::metadata_at_version(version) + } + + fn metadata_versions() -> Vec { + Runtime::metadata_versions() + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Nonce { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_contracts::ContractsApi + for Runtime + { + fn call( + origin: AccountId, + dest: AccountId, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + input_data: Vec, + ) -> pallet_contracts::ContractExecResult { + let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); + Contracts::bare_call( + origin, + dest, + value, + gas_limit, + storage_deposit_limit, + input_data, + CONTRACTS_DEBUG_OUTPUT, + CONTRACTS_EVENTS, + pallet_contracts::Determinism::Enforced, + ) + } + + fn instantiate( + origin: AccountId, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + code: pallet_contracts::Code, + data: Vec, + salt: Vec, + ) -> pallet_contracts::ContractInstantiateResult + { + let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); + Contracts::bare_instantiate( + origin, + value, + gas_limit, + storage_deposit_limit, + code, + data, + salt, + CONTRACTS_DEBUG_OUTPUT, + CONTRACTS_EVENTS, + ) + } + + fn upload_code( + origin: AccountId, + code: Vec, + storage_deposit_limit: Option, + determinism: pallet_contracts::Determinism, + ) -> pallet_contracts::CodeUploadResult + { + Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism) + } + + fn get_storage( + address: AccountId, + key: Vec, + ) -> pallet_contracts::GetStorageResult { + Contracts::get_storage(address, key) + } + } + + impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { + fn can_build_upon( + included_hash: ::Hash, + slot: cumulus_primitives_aura::Slot, + ) -> bool { + Runtime::impl_can_build_upon(included_hash, slot) + } + } + + impl cumulus_primitives_core::CollectCollationInfo for Runtime { + fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { + ParachainSystem::collect_collation_info(header) + } + } + + impl pallet_nfts_runtime_api::NftsApi for Runtime { + fn owner(collection: u32, item: u32) -> Option { + >::owner(&collection, &item) + } + + fn collection_owner(collection: u32) -> Option { + >::collection_owner(&collection) + } + + fn attribute( + collection: u32, + item: u32, + key: Vec, + ) -> Option> { + >::attribute(&collection, &item, &key) + } + + fn custom_attribute( + account: AccountId, + collection: u32, + item: u32, + key: Vec, + ) -> Option> { + >::custom_attribute( + &account, + &collection, + &item, + &key, + ) + } + + fn system_attribute( + collection: u32, + item: Option, + key: Vec, + ) -> Option> { + >::system_attribute(&collection, item.as_ref(), &key) + } + + fn collection_attribute(collection: u32, key: Vec) -> Option> { + >::collection_attribute(&collection, &key) + } + } + + impl pallet_revive::ReviveApi for Runtime + { + fn balance(address: H160) -> Balance { + use frame_support::traits::fungible::Inspect; + let account = ::AddressMapper::to_account_id(&address); + Balances::reducible_balance(&account, Preserve, Polite) + } + + fn nonce(address: H160) -> Nonce { + let account = ::AddressMapper::to_account_id(&address); + System::account_nonce(account) + } + + fn eth_transact( + from: H160, + dest: Option, + value: Balance, + input: Vec, + gas_limit: Option, + storage_deposit_limit: Option, + ) -> pallet_revive::EthContractResult + { + use pallet_revive::AddressMapper; + let blockweights: BlockWeights = ::BlockWeights::get(); + let origin = ::AddressMapper::to_account_id(&from); + + let encoded_size = |pallet_call| { + let call = RuntimeCall::Revive(pallet_call); + let uxt: UncheckedExtrinsic = sp_runtime::generic::UncheckedExtrinsic::new_bare(call).into(); + uxt.encoded_size() as u32 + }; + + Revive::bare_eth_transact( + origin, + dest, + value, + input, + gas_limit.unwrap_or(blockweights.max_block), + storage_deposit_limit.unwrap_or(u128::MAX), + encoded_size, + pallet_revive::DebugInfo::UnsafeDebug, + pallet_revive::CollectEvents::UnsafeCollect, + ) + } + + fn call( + origin: AccountId, + dest: H160, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + input_data: Vec, + ) -> pallet_revive::ContractResult { + Revive::bare_call( + RuntimeOrigin::signed(origin), + dest, + value, + gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block), + storage_deposit_limit.unwrap_or(u128::MAX), + input_data, + pallet_revive::DebugInfo::UnsafeDebug, + pallet_revive::CollectEvents::UnsafeCollect, + ) + } + + fn instantiate( + origin: AccountId, + value: Balance, + gas_limit: Option, + storage_deposit_limit: Option, + code: pallet_revive::Code, + data: Vec, + salt: Option<[u8; 32]>, + ) -> pallet_revive::ContractResult + { + Revive::bare_instantiate( + RuntimeOrigin::signed(origin), + value, + gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block), + storage_deposit_limit.unwrap_or(u128::MAX), + code, + data, + salt, + pallet_revive::DebugInfo::UnsafeDebug, + pallet_revive::CollectEvents::UnsafeCollect, + ) + } + + fn upload_code( + origin: AccountId, + code: Vec, + storage_deposit_limit: Option, + ) -> pallet_revive::CodeUploadResult + { + Revive::bare_upload_code( + RuntimeOrigin::signed(origin), + code, + storage_deposit_limit.unwrap_or(u128::MAX), + ) + } + + fn get_storage( + address: H160, + key: [u8; 32], + ) -> pallet_revive::GetStorageResult { + Revive::get_storage( + address, + key + ) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, RuntimeBlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect, + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, alloc::string::String> { + use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; + + use frame_system_benchmarking::Pallet as SystemBench; + impl frame_system_benchmarking::Config for Runtime { + fn setup_set_code_requirements(code: &Vec) -> Result<(), BenchmarkError> { + ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); + Ok(()) + } + + fn verify_set_code() { + System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); + } + } + + use cumulus_pallet_session_benchmarking::Pallet as SessionBench; + impl cumulus_pallet_session_benchmarking::Config for Runtime {} + + use frame_support::traits::WhitelistedStorageKeys; + let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } + Ok(batches) + } + } + + impl sp_genesis_builder::GenesisBuilder for Runtime { + fn build_state(config: Vec) -> sp_genesis_builder::Result { + build_state::(config) + } + + fn get_preset(id: &Option) -> Option> { + get_preset::(id, genesis::get_preset) + } + + fn preset_names() -> Vec { + genesis::presets() + } + } +} From edd1668be2c7e4eea7bdf328637d629841f282ef Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:24:19 +0100 Subject: [PATCH 02/16] refactor(utility): utilities in its own module --- runtime/testnet/src/config/utility.rs | 75 +++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 runtime/testnet/src/config/utility.rs diff --git a/runtime/testnet/src/config/utility.rs b/runtime/testnet/src/config/utility.rs new file mode 100644 index 00000000..53720632 --- /dev/null +++ b/runtime/testnet/src/config/utility.rs @@ -0,0 +1,75 @@ +use frame_support::{ + pallet_prelude::ConstU32, + parameter_types, + traits::{fungible::HoldConsideration, EqualPrivilegeOnly, LinearStoragePrice}, +}; +use frame_system::EnsureRoot; +use parachains_common::Balance; + +use crate::{AccountId, Weight, deposit, Balances, OriginCaller, Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeHoldReason, Perbill}; +use crate::config::system::RuntimeBlockWeights; + +parameter_types! { + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = deposit(1, 88); + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = deposit(0, 32); + pub const MaxSignatories: u32 = 100; +} + +impl pallet_multisig::Config for Runtime { + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = MaxSignatories; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_multisig::weights::SubstrateWeight; +} + +parameter_types! { + pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); + pub const PreimageBaseDeposit: Balance = deposit(2, 64); + pub const PreimageByteDeposit: Balance = deposit(0, 1); +} + +impl pallet_preimage::Config for Runtime { + type Consideration = HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice, + >; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_preimage::weights::SubstrateWeight; +} + +parameter_types! { + pub MaximumSchedulerWeight: Weight = Perbill::from_percent(60) * + RuntimeBlockWeights::get().max_block; +} + +impl pallet_scheduler::Config for Runtime { + #[cfg(feature = "runtime-benchmarks")] + type MaxScheduledPerBlock = ConstU32<512>; + #[cfg(not(feature = "runtime-benchmarks"))] + type MaxScheduledPerBlock = ConstU32<50>; + type MaximumWeight = MaximumSchedulerWeight; + type OriginPrivilegeCmp = EqualPrivilegeOnly; + type PalletsOrigin = OriginCaller; + type Preimages = Preimage; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type ScheduleOrigin = EnsureRoot; + type WeightInfo = pallet_scheduler::weights::SubstrateWeight; +} + +impl pallet_utility::Config for Runtime { + type PalletsOrigin = OriginCaller; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_utility::weights::SubstrateWeight; +} From d708ff765458110086f9acc183139367e77b78ff Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:24:42 +0100 Subject: [PATCH 03/16] refactor(system): system in its own module --- runtime/testnet/src/config/system.rs | 164 +++++++++++++++++++++++++++ 1 file changed, 164 insertions(+) create mode 100644 runtime/testnet/src/config/system.rs diff --git a/runtime/testnet/src/config/system.rs b/runtime/testnet/src/config/system.rs new file mode 100644 index 00000000..04a69215 --- /dev/null +++ b/runtime/testnet/src/config/system.rs @@ -0,0 +1,164 @@ +use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; +use frame_support::{ + derive_impl, + pallet_prelude::ConstU32, + parameter_types, + traits::{ConstU64, Contains, EverythingBut}, +}; +use parachains_common::{Balance, Hash}; +use polkadot_runtime_common::BlockHashCount; +use sp_runtime::traits::{AccountIdLookup, BlakeTwo256}; + +use crate::{ + weights::RocksDbWeight, AccountId, AggregateMessageOrigin, Aura, BalancesCall, Block, + BlockExecutionWeight, BlockLength, BlockWeights, DispatchClass, ExtrinsicBaseWeight, + MessageQueue, Nonce, PalletInfo, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + RuntimeTask, RuntimeVersion, Weight, XcmpQueue, AVERAGE_ON_INITIALIZE_RATIO, + BLOCK_PROCESSING_VELOCITY, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, + RELAY_CHAIN_SLOT_DURATION_MILLIS, UNINCLUDED_SEGMENT_CAPACITY, VERSION, +}; + +parameter_types! { + pub const Version: RuntimeVersion = VERSION; + + // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`. + // The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the + // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize + // the lazy contract deletion. + pub RuntimeBlockLength: BlockLength = + BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() + .base_block(BlockExecutionWeight::get()) + .for_class(DispatchClass::all(), |weights| { + weights.base_extrinsic = ExtrinsicBaseWeight::get(); + }) + .for_class(DispatchClass::Normal, |weights| { + weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); + }) + .for_class(DispatchClass::Operational, |weights| { + weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); + // Operational transactions have some extra reserved space, so that they + // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. + weights.reserved = Some( + MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT + ); + }) + .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) + .build_or_panic(); + pub const SS58Prefix: u16 = 0; +} + +/// A type to identify filtered calls. +pub struct FilteredCalls; +impl Contains for FilteredCalls { + fn contains(c: &RuntimeCall) -> bool { + use BalancesCall::*; + matches!( + c, + RuntimeCall::Balances( + force_adjust_total_issuance { .. } | + force_set_balance { .. } | + force_transfer { .. } | + force_unreserve { .. } + ) + ) + } +} + +#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)] +impl frame_system::Config for Runtime { + /// The data to be stored in an account. + type AccountData = pallet_balances::AccountData; + /// The identifier used to distinguish between accounts. + type AccountId = AccountId; + /// The basic call filter to use in dispatchable. Supports everything as the default. + type BaseCallFilter = EverythingBut; + /// The block type. + type Block = Block; + /// Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + /// The maximum length of a block (in bytes). + type BlockLength = RuntimeBlockLength; + /// Block & extrinsics weights: base values and limits. + type BlockWeights = RuntimeBlockWeights; + /// The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + /// Weight information for the extensions of this pallet. + type ExtensionsWeightInfo = (); + /// The type for hashing blocks and tries. + type Hash = Hash; + /// The default hashing algorithm used. + type Hashing = BlakeTwo256; + /// The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; + type MaxConsumers = ConstU32<16>; + type MultiBlockMigrator = (); + /// The index type for storing how many extrinsics an account has signed. + type Nonce = Nonce; + /// What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + /// What to do if a new account is created. + type OnNewAccount = (); + /// The action to take on a Runtime Upgrade + type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; + /// Converts a module to the index of the module, injected by `construct_runtime!`. + type PalletInfo = PalletInfo; + type PostInherents = (); + type PostTransactions = (); + type PreInherents = (); + /// The aggregated dispatch type available for extrinsics, injected by + /// `construct_runtime!`. + type RuntimeCall = RuntimeCall; + /// The ubiquitous event type injected by `construct_runtime!`. + type RuntimeEvent = RuntimeEvent; + /// The ubiquitous origin type injected by `construct_runtime!`. + type RuntimeOrigin = RuntimeOrigin; + /// The aggregated Task type, injected by `construct_runtime!`. + type RuntimeTask = RuntimeTask; + /// This is used as an identifier of the chain. 42 is the generic substrate prefix. + type SS58Prefix = SS58Prefix; + type SingleBlockMigrations = (); + /// Weight information for the extrinsics of this pallet. + type SystemWeightInfo = frame_system::weights::SubstrateWeight; + /// Runtime version. + type Version = Version; +} + +parameter_types! { + pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); + pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; +} + +#[docify::export] +pub type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< + Runtime, + RELAY_CHAIN_SLOT_DURATION_MILLIS, + BLOCK_PROCESSING_VELOCITY, + UNINCLUDED_SEGMENT_CAPACITY, +>; + +impl cumulus_pallet_parachain_system::Config for Runtime { + type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases; + type ConsensusHook = ConsensusHook; + type DmpQueue = frame_support::traits::EnqueueWithOrigin; + type OnSystemEvent = (); + type OutboundXcmpMessageSource = XcmpQueue; + type ReservedDmpWeight = ReservedDmpWeight; + type ReservedXcmpWeight = ReservedXcmpWeight; + type RuntimeEvent = RuntimeEvent; + type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector; + type SelfParaId = parachain_info::Pallet; + type WeightInfo = (); + type XcmpMessageHandler = XcmpQueue; +} + +impl pallet_timestamp::Config for Runtime { + type MinimumPeriod = ConstU64<0>; + /// A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type WeightInfo = (); +} + +impl parachain_info::Config for Runtime {} From db23aa1e6d89672a7a42deb849ca3cb938fd4f3f Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:25:08 +0100 Subject: [PATCH 04/16] refactor(collation): collation in its own module --- runtime/testnet/src/config/collation.rs | 72 +++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 runtime/testnet/src/config/collation.rs diff --git a/runtime/testnet/src/config/collation.rs b/runtime/testnet/src/config/collation.rs new file mode 100644 index 00000000..e23eaf8a --- /dev/null +++ b/runtime/testnet/src/config/collation.rs @@ -0,0 +1,72 @@ +use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; +use pop_runtime_common::{HOURS, SLOT_DURATION}; + +use crate::{ + config::xcm::RelayLocation, parameter_types, AccountId, Aura, AuraId, Balances, BlockNumber, + BodyId, CollatorSelection, ConstBool, ConstU32, ConstU64, EitherOfDiverse, EnsureRoot, + PalletId, Runtime, RuntimeEvent, Session, SessionKeys, +}; + +impl pallet_authorship::Config for Runtime { + type EventHandler = (CollatorSelection,); + type FindAuthor = pallet_session::FindAccountFromAuthorIndex; +} + +#[docify::export(aura_config)] +impl pallet_aura::Config for Runtime { + type AllowMultipleBlocksPerSlot = ConstBool; + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<100_000>; + type SlotDuration = ConstU64; +} + +parameter_types! { + pub const PotId: PalletId = PalletId(*b"PotStake"); + pub const SessionLength: BlockNumber = 6 * HOURS; + // StakingAdmin pluralistic body. + pub const StakingAdminBodyId: BodyId = BodyId::Defense; +} + +/// We allow root and the StakingAdmin to execute privileged collator selection operations. +pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< + EnsureRoot, + EnsureXcm>, +>; + +impl pallet_collator_selection::Config for Runtime { + type Currency = Balances; + // should be a multiple of session or things will get inconsistent + type KickThreshold = Period; + type MaxCandidates = ConstU32<100>; + type MaxInvulnerables = ConstU32<20>; + type MinEligibleCollators = ConstU32<4>; + type PotId = PotId; + type RuntimeEvent = RuntimeEvent; + type UpdateOrigin = CollatorSelectionUpdateOrigin; + type ValidatorId = ::AccountId; + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type ValidatorRegistration = Session; + type WeightInfo = (); +} + +impl cumulus_pallet_aura_ext::Config for Runtime {} + +parameter_types! { + pub const Period: u32 = 6 * HOURS; + pub const Offset: u32 = 0; +} + +impl pallet_session::Config for Runtime { + type Keys = SessionKeys; + type NextSessionRotation = pallet_session::PeriodicSessions; + type RuntimeEvent = RuntimeEvent; + // Essentially just Aura, but let's be pedantic. + type SessionHandler = ::KeyTypeIdProviders; + type SessionManager = CollatorSelection; + type ShouldEndSession = pallet_session::PeriodicSessions; + type ValidatorId = ::AccountId; + // we don't have stash and controller, thus we don't need the convert as well. + type ValidatorIdOf = pallet_collator_selection::IdentityCollator; + type WeightInfo = (); +} From 7d395702ccea021cbbae6e08aa8f227bf4569e2c Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:26:43 +0100 Subject: [PATCH 05/16] refactor(assets): use pallet-nfts-sdk --- runtime/testnet/src/config/assets.rs | 82 +++++++++------------------- runtime/testnet/src/config/proxy.rs | 1 + 2 files changed, 27 insertions(+), 56 deletions(-) diff --git a/runtime/testnet/src/config/assets.rs b/runtime/testnet/src/config/assets.rs index 6a54f368..17a0abc8 100644 --- a/runtime/testnet/src/config/assets.rs +++ b/runtime/testnet/src/config/assets.rs @@ -5,6 +5,7 @@ use frame_support::{ }; use frame_system::{EnsureRoot, EnsureSigned}; use pallet_nfts::PalletFeatures; +use pallet_nfts_sdk as pallet_nfts; use parachains_common::{AssetIdForTrustBackedAssets, CollectionId, ItemId, Signature}; use sp_runtime::traits::Verify; @@ -27,13 +28,34 @@ parameter_types! { pub const MetadataDepositPerByte: Balance = deposit(0, 1); } +pub(crate) type TrustBackedAssetsInstance = pallet_assets::Instance1; +pub type TrustBackedAssetsCall = pallet_assets::Call; +impl pallet_assets::Config for Runtime { + type ApprovalDeposit = ApprovalDeposit; + type AssetAccountDeposit = AssetAccountDeposit; + type AssetDeposit = AssetDeposit; + type AssetId = AssetIdForTrustBackedAssets; + type AssetIdParameter = codec::Compact; + type Balance = Balance; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); + type CallbackHandle = (); + type CreateOrigin = AsEnsureOriginWithArg>; + type Currency = Balances; + type Extra = (); + type ForceOrigin = AssetsForceOrigin; + type Freezer = (); + type MetadataDepositBase = MetadataDepositBase; + type MetadataDepositPerByte = MetadataDepositPerByte; + type RemoveItemsLimit = ConstU32<1000>; + type RuntimeEvent = RuntimeEvent; + type StringLimit = AssetsStringLimit; + type WeightInfo = pallet_assets::weights::SubstrateWeight; +} + parameter_types! { pub NftsPalletFeatures: PalletFeatures = PalletFeatures::all_enabled(); - // Key = 68 bytes (4+16+32+16), Value = 52 bytes (4+32+16) - pub const NftsCollectionBalanceDeposit: Balance = deposit(1, 120); pub const NftsCollectionDeposit: Balance = 10 * UNIT; - // Key = 116 bytes (4+16+32+16+32+16), Value = 21 bytes (1+4+16) - pub const NftsCollectionApprovalDeposit: Balance = deposit(1, 137); pub const NftsItemDeposit: Balance = UNIT / 100; pub const NftsMetadataDepositBase: Balance = deposit(1, 129); pub const NftsAttributeDepositBase: Balance = deposit(1, 0); @@ -45,8 +67,6 @@ impl pallet_nfts::Config for Runtime { // TODO: source from primitives type ApprovalsLimit = ConstU32<20>; type AttributeDepositBase = NftsAttributeDepositBase; - type CollectionApprovalDeposit = NftsCollectionApprovalDeposit; - type CollectionBalanceDeposit = NftsCollectionBalanceDeposit; type CollectionDeposit = NftsCollectionDeposit; // TODO: source from primitives type CollectionId = CollectionId; @@ -101,53 +121,3 @@ impl pallet_nft_fractionalization::Config for Runtime { type StringLimit = AssetsStringLimit; type WeightInfo = pallet_nft_fractionalization::weights::SubstrateWeight; } - -pub(crate) type TrustBackedAssetsInstance = pallet_assets::Instance1; -pub type TrustBackedAssetsCall = pallet_assets::Call; -impl pallet_assets::Config for Runtime { - type ApprovalDeposit = ApprovalDeposit; - type AssetAccountDeposit = AssetAccountDeposit; - type AssetDeposit = AssetDeposit; - type AssetId = AssetIdForTrustBackedAssets; - type AssetIdParameter = codec::Compact; - type Balance = Balance; - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); - type CallbackHandle = (); - type CreateOrigin = AsEnsureOriginWithArg>; - type Currency = Balances; - type Extra = (); - type ForceOrigin = AssetsForceOrigin; - type Freezer = (); - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type RemoveItemsLimit = ConstU32<1000>; - type RuntimeEvent = RuntimeEvent; - type StringLimit = AssetsStringLimit; - type WeightInfo = pallet_assets::weights::SubstrateWeight; -} - -#[cfg(test)] -mod tests { - use frame_support::traits::StorageInfoTrait; - - use super::*; - - #[test] - fn ensure_account_balance_deposit() { - let max_size = pallet_nfts::AccountBalance::::storage_info() - .first() - .and_then(|info| info.max_size) - .unwrap_or_default(); - assert_eq!(deposit(1, max_size), NftsCollectionBalanceDeposit::get()); - } - - #[test] - fn ensure_collection_approval_deposit() { - let max_size = pallet_nfts::CollectionApprovals::::storage_info() - .first() - .and_then(|info| info.max_size) - .unwrap_or_default(); - assert_eq!(deposit(1, max_size), NftsCollectionApprovalDeposit::get()); - } -} diff --git a/runtime/testnet/src/config/proxy.rs b/runtime/testnet/src/config/proxy.rs index ff70240e..dd322bc2 100644 --- a/runtime/testnet/src/config/proxy.rs +++ b/runtime/testnet/src/config/proxy.rs @@ -1,4 +1,5 @@ use frame_support::traits::InstanceFilter; +use pallet_nfts_sdk as pallet_nfts; use pop_runtime_common::proxy::{ AnnouncementDepositBase, AnnouncementDepositFactor, MaxPending, MaxProxies, ProxyDepositBase, ProxyDepositFactor, ProxyType, From 5a003e5b9f310275398cf3956b7440166fd8d007 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:28:54 +0100 Subject: [PATCH 06/16] refactor(xcm): xcm fee tweaks & queue pallets into xcm module --- runtime/testnet/src/config/xcm.rs | 137 +++++++++++++++++++++--------- 1 file changed, 97 insertions(+), 40 deletions(-) diff --git a/runtime/testnet/src/config/xcm.rs b/runtime/testnet/src/config/xcm.rs index 6e972945..73852076 100644 --- a/runtime/testnet/src/config/xcm.rs +++ b/runtime/testnet/src/config/xcm.rs @@ -1,28 +1,44 @@ +use alloc::vec::Vec; use core::marker::PhantomData; +use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ parameter_types, - traits::{ConstU32, Contains, ContainsPair, Everything, Get, Nothing}, + traits::{ + tokens::imbalance::ResolveTo, ConstU32, Contains, ContainsPair, Equals, Everything, Get, + Nothing, TransformOrigin, + }, weights::Weight, }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; +use parachains_common::{ + message_queue::{NarrowOriginToSibling, ParaIdToSibling}, + xcm_config::ParentRelayOrSiblingParachains, +}; use polkadot_parachain_primitives::primitives::Sibling; -use polkadot_runtime_common::impls::ToAuthor; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; +use pop_runtime_common::UNIT; use xcm::latest::prelude::*; use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, + AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; use crate::{ - AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + config::{ + monetary::{TransactionByteFee, TreasuryAccount}, + system::RuntimeBlockWeights, + }, + AccountId, AllPalletsWithSystem, Balances, MessageQueue, ParachainInfo, ParachainSystem, + Perbill, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, + XcmpQueue, }; parameter_types! { @@ -34,6 +50,31 @@ parameter_types! { // For the real deployment, it is recommended to set `RelayNetwork` according to the relay chain // and prepend `UniversalLocation` with `GlobalConsensus(RelayNetwork::get())`. pub UniversalLocation: InteriorLocation = Parachain(ParachainInfo::parachain_id().into()).into(); + pub MessageQueueIdleServiceWeight: Weight = Perbill::from_percent(20) * RuntimeBlockWeights::get().max_block; + pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; + pub const BaseDeliveryFee: u128 = (UNIT / 100).saturating_mul(3); +} + +impl pallet_message_queue::Config for Runtime { + type HeapSize = ConstU32<{ 103 * 1024 }>; + type IdleMaxServiceWeight = MessageQueueIdleServiceWeight; + type MaxStale = ConstU32<8>; + #[cfg(feature = "runtime-benchmarks")] + type MessageProcessor = + pallet_message_queue::mock_helpers::NoopMessageProcessor; + #[cfg(not(feature = "runtime-benchmarks"))] + type MessageProcessor = xcm_builder::ProcessXcmMessage< + AggregateMessageOrigin, + xcm_executor::XcmExecutor, + RuntimeCall, + >; + // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: + type QueueChangeHandler = NarrowOriginToSibling; + type QueuePausedQuery = NarrowOriginToSibling; + type RuntimeEvent = RuntimeEvent; + type ServiceWeight = MessageQueueServiceWeight; + type Size = u32; + type WeightInfo = pallet_message_queue::weights::SubstrateWeight; } /// Type for specifying how a `Location` can be converted into an `AccountId`. This is used @@ -91,21 +132,13 @@ parameter_types! { pub const MaxAssetsIntoHolding: u32 = 64; } -pub struct ParentOrParentsExecutivePlurality; -impl Contains for ParentOrParentsExecutivePlurality { - fn contains(location: &Location) -> bool { - matches!(location.unpack(), (1, []) | (1, [Plurality { id: BodyId::Executive, .. }])) - } -} - pub type Barrier = TrailingSetTopicAsId<( TakeWeightCredit, AllowKnownQueryResponses, WithComputedOrigin< ( AllowTopLevelPaidExecutionFrom, - AllowExplicitUnpaidExecutionFrom, - // ^^^ Parent and its exec plurality get free execution + AllowSubscriptionsFrom, ), UniversalLocation, ConstU32<8>, @@ -124,26 +157,17 @@ impl> ContainsPair for NativeAssetFrom { } } -/// Accepts native assets, except from the relay because AH functions as the reserve. -pub struct NativeAssetExceptRelay; -impl ContainsPair for NativeAssetExceptRelay { - fn contains(asset: &Asset, origin: &Location) -> bool { - log::trace!( - target: "xcm::contains", - "asset: {:?}, origin: {:?}", - asset, - origin - ); - // Exclude the relay location. - if matches!(origin, Location { parents: 1, interior: Here }) { - return false; - } - matches!(asset.id, AssetId(ref id) if id == origin) +/// Filter to determine if all specified assets are supported, used with +/// reserve-transfers. +pub struct FilterByAssets(PhantomData); +impl> Contains<(Location, Vec)> for FilterByAssets { + fn contains(t: &(Location, Vec)) -> bool { + t.1.iter().all(|a| Assets::contains(&a.id.0)) } } /// Combinations of (Asset, Location) pairs which we trust as reserves. -pub type TrustedReserves = (NativeAssetFrom, NativeAssetExceptRelay); +pub type TrustedReserves = NativeAssetFrom; pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { @@ -156,7 +180,11 @@ impl xcm_executor::Config for XcmConfig { type AssetTrap = PolkadotXcm; type Barrier = Barrier; type CallDispatcher = RuntimeCall; - type FeeManager = (); + type FeeManager = XcmFeeManagerFromComponents< + // No locations have waived fees. + (), + SendXcmFeeToAccount, + >; type HrmpChannelAcceptedHandler = (); type HrmpChannelClosingHandler = (); type HrmpNewChannelOpenRequestHandler = (); @@ -170,8 +198,13 @@ impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; type SafeCallFilter = Everything; type SubscriptionService = PolkadotXcm; - type Trader = - UsingComponents>; + type Trader = UsingComponents< + WeightToFee, + RelayLocation, + AccountId, + Balances, + ResolveTo, + >; type TransactionalProcessor = FrameTransactionalProcessor; type UniversalAliases = Nothing; // Teleporting is disabled. @@ -184,11 +217,19 @@ impl xcm_executor::Config for XcmConfig { /// No local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; +/// Means to price the delivery of an XCM to the parent chain. +pub type PriceForParentDelivery = + ExponentialPrice; + +/// Means to price the delivery of an XCM to a sibling chain. +pub type PriceForSiblingDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; @@ -214,10 +255,9 @@ impl pallet_xcm::Config for Runtime { type WeightInfo = pallet_xcm::TestWeightInfo; type XcmExecuteFilter = Everything; type XcmExecutor = XcmExecutor; - // TODO: add filter to only allow reserve transfers of native to relay/asset hub - type XcmReserveTransferFilter = Everything; + type XcmReserveTransferFilter = FilterByAssets>; type XcmRouter = XcmRouter; - type XcmTeleportFilter = Everything; + type XcmTeleportFilter = Nothing; const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; } @@ -226,3 +266,20 @@ impl cumulus_pallet_xcm::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; } + +impl cumulus_pallet_xcmp_queue::Config for Runtime { + type ChannelInfo = ParachainSystem; + type ControllerOrigin = EnsureRoot; + type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; + // Limit the number of messages and signals a HRML channel can have at most + type MaxActiveOutboundChannels = ConstU32<128>; + type MaxInboundSuspended = sp_core::ConstU32<1_000>; + // Limit the number of HRML channels + type MaxPageSize = ConstU32<{ 103 * 1024 }>; + type PriceForSiblingDelivery = PriceForSiblingDelivery; + type RuntimeEvent = RuntimeEvent; + type VersionWrapper = PolkadotXcm; + type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight; + // Enqueue XCMP messages from siblings for later processing. + type XcmpQueue = TransformOrigin; +} From 8c1928f804b9360aea8756f9cd36c2ebc1e606ec Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:29:34 +0100 Subject: [PATCH 07/16] refactor(config): config mod --- runtime/testnet/src/config/mod.rs | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/runtime/testnet/src/config/mod.rs b/runtime/testnet/src/config/mod.rs index 1ef83bc1..0f384569 100644 --- a/runtime/testnet/src/config/mod.rs +++ b/runtime/testnet/src/config/mod.rs @@ -1,7 +1,20 @@ mod api; // Public due to pop api integration tests crate. pub mod assets; +// Collation. +pub(crate) mod collation; +// Contracts. mod contracts; -mod proxy; +/// Governance. +pub mod governance; +/// Monetary matters. +pub(crate) mod monetary; +/// Proxy. +pub(crate) mod proxy; +/// System functionality. +pub mod system; +// Utility. +mod utility; // Public due to integration tests crate. pub mod xcm; +mod utility; From 29d135b3e4b77e9e4048836bed4f15694ffb7524 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:30:07 +0100 Subject: [PATCH 08/16] feat(contracts): impl pallet_revive --- runtime/testnet/src/config/contracts.rs | 54 +++++++++++++++++++++++-- 1 file changed, 51 insertions(+), 3 deletions(-) diff --git a/runtime/testnet/src/config/contracts.rs b/runtime/testnet/src/config/contracts.rs index 11c10bec..6a2797d7 100644 --- a/runtime/testnet/src/config/contracts.rs +++ b/runtime/testnet/src/config/contracts.rs @@ -2,14 +2,15 @@ use core::marker::PhantomData; use frame_support::{ parameter_types, - traits::{ConstBool, ConstU32, Nothing, Randomness}, + traits::{ConstBool, ConstU32, ConstU64, Nothing, Randomness}, }; use frame_system::{pallet_prelude::BlockNumberFor, EnsureSigned}; +use pop_runtime_common::UNIT; use super::api::{self, Config}; use crate::{ - deposit, Balance, Balances, Perbill, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, - Timestamp, + deposit, Balance, Balances, Perbill, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, + RuntimeHoldReason, Timestamp, TransactionPayment, }; fn schedule() -> pallet_contracts::Schedule { @@ -33,12 +34,16 @@ impl Randomness> for Dum } } +// 18 decimals +const ETH: u128 = 1_000_000_000_000_000_000; + parameter_types! { pub const DepositPerItem: Balance = deposit(1, 0); pub const DepositPerByte: Balance = deposit(0, 1); pub Schedule: pallet_contracts::Schedule = schedule::(); pub const DefaultDepositLimit: Balance = deposit(1024, 1024 * 1024); pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); + pub const NativeToEthRatio: u32 = (ETH/UNIT) as u32; } impl pallet_contracts::Config for Runtime { @@ -83,6 +88,49 @@ impl pallet_contracts::Config for Runtime { type Xcm = pallet_xcm::Pallet; } +impl pallet_revive::Config for Runtime { + type AddressMapper = pallet_revive::AccountId32Mapper; + // No runtime dispatchables are callable from contracts. + type CallFilter = Nothing; + type ChainExtension = (); + // EVM chain id. 3,395 is a unique ID still. + type ChainId = ConstU64<3_395>; + // 30 percent of storage deposit held for using a code hash. + type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; + type Currency = Balances; + type Debug = (); + type DepositPerByte = DepositPerByte; + type DepositPerItem = DepositPerItem; + type InstantiateOrigin = EnsureSigned; + // 1 ETH : 1_000_000 UNIT + type NativeToEthRatio = NativeToEthRatio; + // 512 MB. Used in an integrity test that verifies the runtime has enough memory. + type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeHoldReason = RuntimeHoldReason; + // 128 MB. Used in an integrity that verifies the runtime has enough memory. + type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>; + type Time = Timestamp; + // Disables access to unsafe host fns such as xcm_send. + type UnsafeUnstableInterface = ConstBool; + type UploadOrigin = EnsureSigned; + type WeightInfo = pallet_revive::weights::SubstrateWeight; + type WeightPrice = TransactionPayment; + type Xcm = PolkadotXcm; +} + +impl TryFrom for pallet_revive::Call { + type Error = (); + + fn try_from(value: RuntimeCall) -> Result { + match value { + RuntimeCall::Revive(call) => Ok(call), + _ => Err(()), + } + } +} + // IMPORTANT: only runtime calls through the api are allowed. #[test] fn contracts_prevents_runtime_calls() { From c224de33dcec8d35897a6570a0cd70993603b295 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:30:48 +0100 Subject: [PATCH 09/16] feat(monetary): impl pallet_treasury --- runtime/testnet/src/config/monetary.rs | 127 +++++++++++++++++++++++++ 1 file changed, 127 insertions(+) create mode 100644 runtime/testnet/src/config/monetary.rs diff --git a/runtime/testnet/src/config/monetary.rs b/runtime/testnet/src/config/monetary.rs new file mode 100644 index 00000000..e93927ec --- /dev/null +++ b/runtime/testnet/src/config/monetary.rs @@ -0,0 +1,127 @@ +use frame_support::traits::{ + fungible, + tokens::{imbalance::ResolveTo, PayFromAccount, UnityAssetBalanceConversion}, + Imbalance, NeverEnsureOrigin, OnUnbalanced, +}; +use pop_runtime_common::{EXISTENTIAL_DEPOSIT, MICRO_UNIT}; +use sp_core::crypto::Ss58Codec; +use sp_runtime::traits::{AccountIdConversion, IdentityLookup}; + +use crate::{ + parameter_types, AccountId, Balance, Balances, BlockNumber, ConstU32, ConstU8, + ConstantMultiplier, EnsureRoot, PalletId, Runtime, RuntimeEvent, RuntimeFreezeReason, + RuntimeHoldReason, SlowAdjustingFeeUpdate, System, VariantCountOf, WeightToFee, DAYS, +}; + +const TREASURY_PALLET_ID: PalletId = PalletId(*b"treasury"); + +parameter_types! { + pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; + pub TreasuryAccount: AccountId = TREASURY_PALLET_ID.into_account_truncating(); +} + +impl pallet_balances::Config for Runtime { + type AccountStore = System; + /// The type for recording an account's balance. + type Balance = Balance; + type DoneSlashHandler = (); + type DustRemoval = (); + type ExistentialDeposit = ExistentialDeposit; + type FreezeIdentifier = RuntimeFreezeReason; + type MaxFreezes = VariantCountOf; + type MaxLocks = ConstU32<50>; + type MaxReserves = ConstU32<50>; + type ReserveIdentifier = [u8; 8]; + /// The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeHoldReason = RuntimeHoldReason; + type WeightInfo = pallet_balances::weights::SubstrateWeight; +} + +parameter_types! { + /// Relay Chain `TransactionByteFee` / 10 + pub const TransactionByteFee: Balance = 10 * MICRO_UNIT; + pub MaintenanceAccount: AccountId = AccountId::from_ss58check("1Y3M8pnn3rJcxQn46SbocHcUHYfs4j8W2zHX7XNK99LGSVe").expect("maintenance address is valid SS58"); +} + +/// DealWithFees is used to handle fees and tips in the OnChargeTransaction trait, +/// by implementing OnUnbalanced. +pub struct DealWithFees; +impl OnUnbalanced> for DealWithFees { + fn on_unbalanceds( + mut fees_then_tips: impl Iterator>, + ) { + if let Some(mut fees) = fees_then_tips.next() { + if let Some(tips) = fees_then_tips.next() { + tips.merge_into(&mut fees); + } + let split = fees.ration(50, 50); + ResolveTo::::on_unbalanced(split.0); + ResolveTo::::on_unbalanced(split.1); + } + } +} +/// The type responsible for payment in pallet_transaction_payment. +pub type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter; + +impl pallet_transaction_payment::Config for Runtime { + type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; + type LengthToFee = ConstantMultiplier; + type OnChargeTransaction = OnChargeTransaction; + type OperationalFeeMultiplier = ConstU8<5>; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + type WeightToFee = WeightToFee; +} + +pub(crate) type TreasuryPaymaster = PayFromAccount; +parameter_types! { + pub const SpendPeriod: BlockNumber = 6 * DAYS; + pub const TreasuryPalletId: PalletId = TREASURY_PALLET_ID; + pub const MaxApprovals: u32 = 100; + pub const PayoutPeriod: BlockNumber = 30 * DAYS; +} + +#[cfg(feature = "runtime-benchmarks")] +pub struct BenchmarkHelper; +#[cfg(feature = "runtime-benchmarks")] +impl pallet_treasury::ArgumentsFactory<(), AccountId> for BenchmarkHelper { + fn create_asset_kind(_seed: u32) -> () { + () + } + + fn create_beneficiary(seed: [u8; 32]) -> AccountId { + let account_id = AccountId::from(seed); + Balances::force_set_balance( + crate::RuntimeOrigin::root(), + account_id.clone().into(), + EXISTENTIAL_DEPOSIT, + ) + .unwrap(); + account_id + } +} +impl pallet_treasury::Config for Runtime { + type AssetKind = (); + type BalanceConverter = UnityAssetBalanceConversion; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = BenchmarkHelper; + type Beneficiary = AccountId; + type BeneficiaryLookup = IdentityLookup; + type BlockNumberProvider = System; + type Burn = (); + type BurnDestination = (); + type Currency = Balances; + type MaxApprovals = MaxApprovals; + type PalletId = TreasuryPalletId; + type Paymaster = TreasuryPaymaster; + type PayoutPeriod = PayoutPeriod; + type RejectOrigin = EnsureRoot; + type RuntimeEvent = RuntimeEvent; + type SpendFunds = (); + /// Never allow origins except via the proposals process. + type SpendOrigin = NeverEnsureOrigin; + type SpendPeriod = SpendPeriod; + type WeightInfo = pallet_treasury::weights::SubstrateWeight; +} From f69df95fbf2d4b7635a96d7c2c9519575e164896 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:31:24 +0100 Subject: [PATCH 10/16] feat(governance): impl council & motion --- runtime/testnet/src/config/governance.rs | 68 ++++++++++++++++++++++++ runtime/testnet/src/genesis.rs | 16 ++---- 2 files changed, 73 insertions(+), 11 deletions(-) create mode 100644 runtime/testnet/src/config/governance.rs diff --git a/runtime/testnet/src/config/governance.rs b/runtime/testnet/src/config/governance.rs new file mode 100644 index 00000000..e31731ed --- /dev/null +++ b/runtime/testnet/src/config/governance.rs @@ -0,0 +1,68 @@ +use frame_support::{ + parameter_types, + traits::{EitherOfDiverse, NeverEnsureOrigin}, +}; +use frame_system::EnsureRoot; +use pallet_collective::EnsureProportionAtLeast; +use sp_core::crypto::Ss58Codec; + +use crate::{ + config::system::RuntimeBlockWeights, AccountId, BlockNumber, Runtime, RuntimeCall, + RuntimeEvent, RuntimeOrigin, Weight, DAYS, +}; + +// Type aliases for council origins. +type AtLeastThreeFourthsOfCouncil = EitherOfDiverse< + EnsureRoot, + EnsureProportionAtLeast, +>; +type UnanimousCouncilVote = EitherOfDiverse< + EnsureRoot, + EnsureProportionAtLeast, +>; + +/// SUDO account set at genesis. +const SUDO_ACCOUNT: &str = "5FPL3ZLqUk6MyBoZrQZ1Co29WAteX6T6N68TZ6jitHvhpyuD"; + +parameter_types! { + pub CouncilMotionDuration: BlockNumber = 7 * DAYS; + pub const CouncilMaxProposals: u32 = 100; + pub const CouncilMaxMembers: u32 = 100; + pub MaxProposalWeight: Weight = sp_runtime::Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block; + pub SudoAddress: AccountId = AccountId::from_ss58check(SUDO_ACCOUNT).expect("sudo address is valid SS58"); +} + +pub type CouncilCollective = pallet_collective::Instance1; +impl pallet_collective::Config for Runtime { + type Consideration = (); + type DefaultVote = pallet_collective::MoreThanMajorityThenPrimeDefaultVote; + type DisapproveOrigin = EnsureRoot; + type KillOrigin = EnsureRoot; + type MaxMembers = CouncilMaxMembers; + type MaxProposalWeight = MaxProposalWeight; + type MaxProposals = CouncilMaxProposals; + type MotionDuration = CouncilMotionDuration; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type SetMembersOrigin = EnsureRoot; + type WeightInfo = pallet_collective::weights::SubstrateWeight; +} + +impl pallet_motion::Config for Runtime { + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + // Simple majority is disabled. + type SimpleMajorityOrigin = NeverEnsureOrigin<()>; + // At least 3/4 of the council vote is needed. + type SuperMajorityOrigin = AtLeastThreeFourthsOfCouncil; + // A unanimous council vote is needed. + type UnanimousOrigin = UnanimousCouncilVote; + type WeightInfo = pallet_motion::weights::SubstrateWeight; +} + +impl pallet_sudo::Config for Runtime { + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); +} diff --git a/runtime/testnet/src/genesis.rs b/runtime/testnet/src/genesis.rs index f20954bf..dd71668e 100644 --- a/runtime/testnet/src/genesis.rs +++ b/runtime/testnet/src/genesis.rs @@ -6,7 +6,10 @@ use pop_runtime_common::genesis::*; use sp_core::crypto::Ss58Codec; use sp_genesis_builder::PresetId; -use crate::{AssetsConfig, BalancesConfig, SessionKeys, EXISTENTIAL_DEPOSIT, UNIT}; +use crate::{ + config::governance::SudoAddress, AssetsConfig, BalancesConfig, SessionKeys, + EXISTENTIAL_DEPOSIT, UNIT, +}; /// A development chain running on a single node, using the `testnet` runtime. pub const TESTNET_DEV: &str = "pop-testnet-dev"; @@ -27,15 +30,6 @@ const ENDOWMENT: Balance = 10_000_000 * UNIT; /// The default XCM version to set in genesis config. const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION; -/// SUDO account set at genesis. -const TESTNET_SUDO_ACCOUNT: &str = "5FPL3ZLqUk6MyBoZrQZ1Co29WAteX6T6N68TZ6jitHvhpyuD"; - -// Returns the SUDO account's address as an `AccountId`. -// This function will return an error if the SS58 address is invalid. -fn sudo_account_id() -> AccountId { - AccountId::from_ss58check(TESTNET_SUDO_ACCOUNT).expect("sudo address is valid SS58") -} - /// Returns a JSON blob representation of the built-in `RuntimeGenesisConfig` identified by `id`. pub(crate) fn get_preset(id: &PresetId) -> Option> { let patch = match id.as_str() { @@ -113,7 +107,7 @@ fn live_config() -> Value { (collator_2_account_id, collator_2_aura_id), ], vec![], - sudo_account_id(), + SudoAddress::get(), PARA_ID, ) } From 8f8c87e29c5468667a9c9e7a735025b5b4ef284d Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 02:32:17 +0100 Subject: [PATCH 11/16] feat(testnet): include new pallets into testnet runtime --- Cargo.lock | 8 +- runtime/testnet/Cargo.toml | 26 +- runtime/testnet/src/lib.rs | 789 +++---------------------------------- 3 files changed, 90 insertions(+), 733 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7d115e5a..cf852e88 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13808,7 +13808,7 @@ dependencies = [ [[package]] name = "pop-runtime-testnet" -version = "0.4.2" +version = "0.4.3" dependencies = [ "cumulus-pallet-aura-ext 0.18.0", "cumulus-pallet-parachain-system 0.18.0", @@ -13839,20 +13839,24 @@ dependencies = [ "pallet-authorship 39.0.0", "pallet-balances 40.0.0", "pallet-collator-selection 20.0.0", + "pallet-collective", "pallet-contracts", "pallet-message-queue 42.0.0", + "pallet-motion", "pallet-multisig 39.0.0", "pallet-nft-fractionalization", - "pallet-nfts 31.0.0", + "pallet-nfts 33.0.0", "pallet-nfts-runtime-api 25.0.0", "pallet-preimage 39.0.0", "pallet-proxy 39.0.0", + "pallet-revive", "pallet-scheduler 40.0.0", "pallet-session 39.0.0", "pallet-sudo 39.0.0", "pallet-timestamp 38.0.0", "pallet-transaction-payment 39.0.0", "pallet-transaction-payment-rpc-runtime-api 39.0.0", + "pallet-treasury 38.0.0", "pallet-utility 39.0.0", "pallet-xcm 18.0.0", "parachains-common 19.0.0", diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index 0784c894..39cf4dab 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -6,7 +6,7 @@ homepage.workspace = true license = "Unlicense" name = "pop-runtime-testnet" repository.workspace = true -version = "0.4.2" +version = "0.4.3" [package.metadata.docs.rs] targets = [ "x86_64-unknown-linux-gnu" ] @@ -24,6 +24,7 @@ smallvec.workspace = true # Local pallet-api.workspace = true +pallet-motion.workspace = true pop-chain-extension.workspace = true pop-primitives.workspace = true pop-runtime-common.workspace = true @@ -41,20 +42,23 @@ pallet-assets.workspace = true pallet-aura.workspace = true pallet-authorship.workspace = true pallet-balances.workspace = true +pallet-collective.workspace = true pallet-contracts.workspace = true pallet-message-queue.workspace = true pallet-multisig.workspace = true pallet-nft-fractionalization.workspace = true -pallet-nfts.workspace = true pallet-nfts-runtime-api.workspace = true +pallet-nfts-sdk.workspace = true pallet-preimage.workspace = true pallet-proxy.workspace = true +pallet-revive.workspace = true pallet-scheduler.workspace = true pallet-session.workspace = true pallet-sudo.workspace = true pallet-timestamp.workspace = true pallet-transaction-payment.workspace = true pallet-transaction-payment-rpc-runtime-api.workspace = true +pallet-treasury.workspace = true pallet-utility.workspace = true sp-api.workspace = true sp-block-builder.workspace = true @@ -125,20 +129,24 @@ std = [ "pallet-authorship/std", "pallet-balances/std", "pallet-collator-selection/std", + "pallet-collective/std", "pallet-contracts/std", "pallet-message-queue/std", + "pallet-motion/std", "pallet-multisig/std", "pallet-nft-fractionalization/std", "pallet-nfts-runtime-api/std", - "pallet-nfts/std", + "pallet-nfts-sdk/std", "pallet-preimage/std", "pallet-proxy/std", + "pallet-revive/std", "pallet-scheduler/std", "pallet-session/std", "pallet-sudo/std", "pallet-timestamp/std", "pallet-transaction-payment-rpc-runtime-api/std", "pallet-transaction-payment/std", + "pallet-treasury/std", "pallet-utility/std", "pallet-xcm/std", "parachain-info/std", @@ -180,17 +188,21 @@ runtime-benchmarks = [ "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collator-selection/runtime-benchmarks", + "pallet-collective/runtime-benchmarks", "pallet-contracts/runtime-benchmarks", "pallet-message-queue/runtime-benchmarks", + "pallet-motion/runtime-benchmarks", "pallet-multisig/runtime-benchmarks", "pallet-nft-fractionalization/runtime-benchmarks", - "pallet-nfts/runtime-benchmarks", + "pallet-nfts-sdk/runtime-benchmarks", "pallet-preimage/runtime-benchmarks", "pallet-proxy/runtime-benchmarks", + "pallet-revive/runtime-benchmarks", "pallet-scheduler/runtime-benchmarks", "pallet-sudo/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-transaction-payment/runtime-benchmarks", + "pallet-treasury/runtime-benchmarks", "pallet-utility/runtime-benchmarks", "pallet-xcm/runtime-benchmarks", "parachains-common/runtime-benchmarks", @@ -218,18 +230,22 @@ try-runtime = [ "pallet-authorship/try-runtime", "pallet-balances/try-runtime", "pallet-collator-selection/try-runtime", + "pallet-collective/try-runtime", "pallet-contracts/try-runtime", "pallet-message-queue/try-runtime", + "pallet-motion/try-runtime", "pallet-multisig/try-runtime", "pallet-nft-fractionalization/try-runtime", - "pallet-nfts/try-runtime", + "pallet-nfts-sdk/try-runtime", "pallet-preimage/try-runtime", "pallet-proxy/try-runtime", + "pallet-revive/try-runtime", "pallet-scheduler/try-runtime", "pallet-session/try-runtime", "pallet-sudo/try-runtime", "pallet-timestamp/try-runtime", "pallet-transaction-payment/try-runtime", + "pallet-treasury/try-runtime", "pallet-utility/try-runtime", "pallet-xcm/try-runtime", "parachain-info/try-runtime", diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index b70e935c..e57ce724 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -6,6 +6,7 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +mod apis; // Public due to integration tests crate. pub mod config; @@ -17,19 +18,15 @@ extern crate alloc; use alloc::{borrow::Cow, vec::Vec}; -use config::xcm::{RelayLocation, XcmOriginToTransactDispatchOrigin}; -use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; -use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; +pub use apis::{RuntimeApi, RUNTIME_API_VERSIONS}; +use config::system::ConsensusHook; +use cumulus_primitives_core::AggregateMessageOrigin; +use cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim; +use frame_metadata_hash_extension::CheckMetadataHash; use frame_support::{ - derive_impl, dispatch::DispatchClass, - genesis_builder_helper::{build_state, get_preset}, parameter_types, - traits::{ - fungible::HoldConsideration, tokens::nonfungibles_v2::Inspect, ConstBool, ConstU32, - ConstU64, ConstU8, Contains, EitherOfDiverse, EqualPrivilegeOnly, EverythingBut, - LinearStoragePrice, TransformOrigin, VariantCountOf, - }, + traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, VariantCountOf}, weights::{ ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, @@ -38,15 +35,15 @@ use frame_support::{ }; use frame_system::{ limits::{BlockLength, BlockWeights}, - EnsureRoot, + CheckGenesis, CheckMortality, CheckNonZeroSender, CheckNonce, CheckSpecVersion, CheckTxVersion, + CheckWeight, EnsureRoot, }; use pallet_api::fungibles; use pallet_balances::Call as BalancesCall; -use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; -use parachains_common::message_queue::{NarrowOriginToSibling, ParaIdToSibling}; -use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; +use pallet_nfts_sdk as pallet_nfts; +use pallet_transaction_payment::ChargeTransactionPayment; // Polkadot imports -use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; +use polkadot_runtime_common::SlowAdjustingFeeUpdate; pub use pop_runtime_common::{ deposit, AuraId, Balance, BlockNumber, Hash, Nonce, Signature, AVERAGE_ON_INITIALIZE_RATIO, BLOCK_PROCESSING_VELOCITY, DAYS, EXISTENTIAL_DEPOSIT, HOURS, MAXIMUM_BLOCK_WEIGHT, MICRO_UNIT, @@ -54,21 +51,17 @@ pub use pop_runtime_common::{ UNINCLUDED_SEGMENT_CAPACITY, UNIT, }; use smallvec::smallvec; -use sp_api::impl_runtime_apis; -use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; use sp_runtime::{ generic, impl_opaque_keys, traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, Verify}, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, }; pub use sp_runtime::{ExtrinsicInclusionMode, MultiAddress, Perbill, Permill}; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; +use weights::{BlockExecutionWeight, ExtrinsicBaseWeight}; // XCM Imports use xcm::latest::prelude::BodyId; @@ -79,6 +72,12 @@ pub type AccountId = <::Signer as IdentifyAccount>::Account /// The address format for describing accounts. pub type Address = MultiAddress; +/// Record of an event happening. +pub type EventRecord = frame_system::EventRecord< + ::RuntimeEvent, + ::Hash, +>; + /// Block header type as expected by this runtime. pub type Header = generic::Header; @@ -93,21 +92,45 @@ pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type TxExtension = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckMortality, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim, - frame_metadata_hash_extension::CheckMetadataHash, + CheckNonZeroSender, + CheckSpecVersion, + CheckTxVersion, + CheckGenesis, + CheckMortality, + CheckNonce, + CheckWeight, + ChargeTransactionPayment, + StorageWeightReclaim, + CheckMetadataHash, ); +/// EthExtra converts an unsigned Call::eth_transact into a CheckedExtrinsic. +#[derive(Clone, PartialEq, Eq, Debug)] +pub struct EthExtraImpl; + +impl pallet_revive::evm::runtime::EthExtra for EthExtraImpl { + type Config = Runtime; + type Extension = TxExtension; + + fn get_eth_extension(nonce: u32, tip: Balance) -> Self::Extension { + ( + CheckNonZeroSender::::new(), + CheckSpecVersion::::new(), + CheckTxVersion::::new(), + CheckGenesis::::new(), + CheckMortality::from(generic::Era::Immortal), + CheckNonce::::from(nonce), + CheckWeight::::new(), + ChargeTransactionPayment::::from(tip), + StorageWeightReclaim::::new(), + CheckMetadataHash::::new(false), + ) + } +} + /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = - generic::UncheckedExtrinsic; + pallet_revive::evm::runtime::UncheckedExtrinsic; /// Migrations to apply on runtime upgrade. /// @@ -191,18 +214,13 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { impl_name: Cow::Borrowed("pop"), authoring_version: 1, #[allow(clippy::zero_prefixed_literal)] - spec_version: 00_04_02, + spec_version: 00_04_03, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, system_version: 1, }; -type EventRecord = frame_system::EventRecord< - ::RuntimeEvent, - ::Hash, ->; - // Prints debug output of the `contracts` pallet to stdout if the node is // started with `-lruntime::contracts=debug`. const CONTRACTS_DEBUG_OUTPUT: pallet_contracts::DebugInfo = @@ -216,351 +234,11 @@ pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } } -parameter_types! { - pub const Version: RuntimeVersion = VERSION; - - // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`. - // The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the - // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize - // the lazy contract deletion. - pub RuntimeBlockLength: BlockLength = - BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder() - .base_block(BlockExecutionWeight::get()) - .for_class(DispatchClass::all(), |weights| { - weights.base_extrinsic = ExtrinsicBaseWeight::get(); - }) - .for_class(DispatchClass::Normal, |weights| { - weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT); - }) - .for_class(DispatchClass::Operational, |weights| { - weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT); - // Operational transactions have some extra reserved space, so that they - // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`. - weights.reserved = Some( - MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT - ); - }) - .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) - .build_or_panic(); - pub const SS58Prefix: u16 = 0; -} - -/// A type to identify filtered calls. -pub struct FilteredCalls; -impl Contains for FilteredCalls { - fn contains(c: &RuntimeCall) -> bool { - use BalancesCall::*; - matches!( - c, - RuntimeCall::Balances( - force_adjust_total_issuance { .. } | - force_set_balance { .. } | - force_transfer { .. } | - force_unreserve { .. } - ) - ) - } -} - -/// The default types are being injected by [`derive_impl`](`frame_support::derive_impl`) from -/// [`ParaChainDefaultConfig`](`struct@frame_system::config_preludes::ParaChainDefaultConfig`), -/// but overridden as needed. -#[derive_impl(frame_system::config_preludes::ParaChainDefaultConfig)] -impl frame_system::Config for Runtime { - /// The data to be stored in an account. - type AccountData = pallet_balances::AccountData; - /// The identifier used to distinguish between accounts. - type AccountId = AccountId; - /// The basic call filter to use in dispatchable. Supports everything as the default. - type BaseCallFilter = EverythingBut; - /// The block type. - type Block = Block; - /// Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - /// The maximum length of a block (in bytes). - type BlockLength = RuntimeBlockLength; - /// Block & extrinsics weights: base values and limits. - type BlockWeights = RuntimeBlockWeights; - /// The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - /// The type for hashing blocks and tries. - type Hash = Hash; - type MaxConsumers = frame_support::traits::ConstU32<16>; - /// The index type for storing how many extrinsics an account has signed. - type Nonce = Nonce; - /// The action to take on a Runtime Upgrade - type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; - /// This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - /// Runtime version. - type Version = Version; -} - -impl pallet_timestamp::Config for Runtime { - type MinimumPeriod = ConstU64<0>; - /// A timestamp: milliseconds since the unix epoch. - type Moment = u64; - #[cfg(feature = "std")] - type OnTimestampSet = (); - #[cfg(not(feature = "std"))] - type OnTimestampSet = Aura; - type WeightInfo = (); -} - -impl pallet_authorship::Config for Runtime { - type EventHandler = (CollatorSelection,); - type FindAuthor = pallet_session::FindAccountFromAuthorIndex; -} - -parameter_types! { - pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT; -} - -impl pallet_balances::Config for Runtime { - type AccountStore = System; - /// The type for recording an account's balance. - type Balance = Balance; - type DoneSlashHandler = (); - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = VariantCountOf; - type MaxLocks = ConstU32<50>; - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - /// The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - type RuntimeFreezeReason = RuntimeFreezeReason; - type RuntimeHoldReason = RuntimeHoldReason; - type WeightInfo = pallet_balances::weights::SubstrateWeight; -} - -parameter_types! { - /// Relay Chain `TransactionByteFee` / 10 - pub const TransactionByteFee: Balance = 10 * MICRO_UNIT; -} - -impl pallet_transaction_payment::Config for Runtime { - type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; - type LengthToFee = ConstantMultiplier; - type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter; - type OperationalFeeMultiplier = ConstU8<5>; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); - type WeightToFee = WeightToFee; -} - -impl pallet_sudo::Config for Runtime { - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = (); -} - -parameter_types! { - pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); - pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4); - pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent; -} - -#[docify::export] -type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< - Runtime, - RELAY_CHAIN_SLOT_DURATION_MILLIS, - BLOCK_PROCESSING_VELOCITY, - UNINCLUDED_SEGMENT_CAPACITY, ->; - -impl cumulus_pallet_parachain_system::Config for Runtime { - type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases; - type ConsensusHook = ConsensusHook; - type DmpQueue = frame_support::traits::EnqueueWithOrigin; - type OnSystemEvent = (); - type OutboundXcmpMessageSource = XcmpQueue; - type ReservedDmpWeight = ReservedDmpWeight; - type ReservedXcmpWeight = ReservedXcmpWeight; - type RuntimeEvent = RuntimeEvent; - type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector; - type SelfParaId = parachain_info::Pallet; - type WeightInfo = (); - type XcmpMessageHandler = XcmpQueue; -} - -impl parachain_info::Config for Runtime {} - -parameter_types! { - pub MessageQueueServiceWeight: Weight = Perbill::from_percent(35) * RuntimeBlockWeights::get().max_block; -} - -impl pallet_message_queue::Config for Runtime { - type HeapSize = sp_core::ConstU32<{ 103 * 1024 }>; - type IdleMaxServiceWeight = (); - type MaxStale = sp_core::ConstU32<8>; - #[cfg(feature = "runtime-benchmarks")] - type MessageProcessor = pallet_message_queue::mock_helpers::NoopMessageProcessor< - cumulus_primitives_core::AggregateMessageOrigin, - >; - #[cfg(not(feature = "runtime-benchmarks"))] - type MessageProcessor = xcm_builder::ProcessXcmMessage< - AggregateMessageOrigin, - xcm_executor::XcmExecutor, - RuntimeCall, - >; - // The XCMP queue pallet is only ever able to handle the `Sibling(ParaId)` origin: - type QueueChangeHandler = NarrowOriginToSibling; - type QueuePausedQuery = NarrowOriginToSibling; - type RuntimeEvent = RuntimeEvent; - type ServiceWeight = MessageQueueServiceWeight; - type Size = u32; - type WeightInfo = (); -} - -impl cumulus_pallet_aura_ext::Config for Runtime {} - -impl cumulus_pallet_xcmp_queue::Config for Runtime { - type ChannelInfo = ParachainSystem; - type ControllerOrigin = EnsureRoot; - type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; - // Limit the number of messages and signals a HRML channel can have at most - type MaxActiveOutboundChannels = ConstU32<128>; - type MaxInboundSuspended = sp_core::ConstU32<1_000>; - // Limit the number of HRML channels - type MaxPageSize = ConstU32<{ 103 * 1024 }>; - type PriceForSiblingDelivery = NoPriceForMessageDelivery; - type RuntimeEvent = RuntimeEvent; - type VersionWrapper = (); - type WeightInfo = (); - // Enqueue XCMP messages from siblings for later processing. - type XcmpQueue = TransformOrigin; -} - impl cumulus_pallet_xcmp_queue::migration::v5::V5Config for Runtime { // This must be the same as the `ChannelInfo` from the `Config`: type ChannelList = ParachainSystem; } -parameter_types! { - pub const Period: u32 = 6 * HOURS; - pub const Offset: u32 = 0; -} - -impl pallet_session::Config for Runtime { - type Keys = SessionKeys; - type NextSessionRotation = pallet_session::PeriodicSessions; - type RuntimeEvent = RuntimeEvent; - // Essentially just Aura, but let's be pedantic. - type SessionHandler = ::KeyTypeIdProviders; - type SessionManager = CollatorSelection; - type ShouldEndSession = pallet_session::PeriodicSessions; - type ValidatorId = ::AccountId; - // we don't have stash and controller, thus we don't need the convert as well. - type ValidatorIdOf = pallet_collator_selection::IdentityCollator; - type WeightInfo = (); -} - -#[docify::export(aura_config)] -impl pallet_aura::Config for Runtime { - type AllowMultipleBlocksPerSlot = ConstBool; - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<100_000>; - type SlotDuration = ConstU64; -} - -parameter_types! { - pub const PotId: PalletId = PalletId(*b"PotStake"); - pub const SessionLength: BlockNumber = 6 * HOURS; - // StakingAdmin pluralistic body. - pub const StakingAdminBodyId: BodyId = BodyId::Defense; -} - -/// We allow root and the StakingAdmin to execute privileged collator selection operations. -pub type CollatorSelectionUpdateOrigin = EitherOfDiverse< - EnsureRoot, - EnsureXcm>, ->; - -impl pallet_collator_selection::Config for Runtime { - type Currency = Balances; - // should be a multiple of session or things will get inconsistent - type KickThreshold = Period; - type MaxCandidates = ConstU32<100>; - type MaxInvulnerables = ConstU32<20>; - type MinEligibleCollators = ConstU32<4>; - type PotId = PotId; - type RuntimeEvent = RuntimeEvent; - type UpdateOrigin = CollatorSelectionUpdateOrigin; - type ValidatorId = ::AccountId; - type ValidatorIdOf = pallet_collator_selection::IdentityCollator; - type ValidatorRegistration = Session; - type WeightInfo = (); -} - -parameter_types! { - pub MaximumSchedulerWeight: Weight = Perbill::from_percent(60) * - RuntimeBlockWeights::get().max_block; -} - -impl pallet_scheduler::Config for Runtime { - #[cfg(feature = "runtime-benchmarks")] - type MaxScheduledPerBlock = ConstU32<512>; - #[cfg(not(feature = "runtime-benchmarks"))] - type MaxScheduledPerBlock = ConstU32<50>; - type MaximumWeight = MaximumSchedulerWeight; - type OriginPrivilegeCmp = EqualPrivilegeOnly; - type PalletsOrigin = OriginCaller; - type Preimages = Preimage; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type ScheduleOrigin = EnsureRoot; - type WeightInfo = pallet_scheduler::weights::SubstrateWeight; -} - -parameter_types! { - pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); - pub const PreimageBaseDeposit: Balance = deposit(2, 64); - pub const PreimageByteDeposit: Balance = deposit(0, 1); -} - -impl pallet_preimage::Config for Runtime { - type Consideration = HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice, - >; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_preimage::weights::SubstrateWeight; -} - -parameter_types! { - // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. - pub const DepositBase: Balance = deposit(1, 88); - // Additional storage item size of 32 bytes. - pub const DepositFactor: Balance = deposit(0, 32); - pub const MaxSignatories: u32 = 100; -} - -impl pallet_multisig::Config for Runtime { - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = MaxSignatories; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_multisig::weights::SubstrateWeight; -} - -impl pallet_utility::Config for Runtime { - type PalletsOrigin = OriginCaller; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_utility::weights::SubstrateWeight; -} - #[frame_support::runtime] mod runtime { // Create the runtime by composing the FRAME pallets that were previously configured. @@ -593,10 +271,16 @@ mod runtime { pub type Balances = pallet_balances::Pallet; #[runtime::pallet_index(11)] pub type TransactionPayment = pallet_transaction_payment::Pallet; + #[runtime::pallet_index(12)] + pub type Treasury = pallet_treasury::Pallet; // Governance #[runtime::pallet_index(15)] pub type Sudo = pallet_sudo; + #[runtime::pallet_index(16)] + pub type Council = pallet_collective::Pallet; + #[runtime::pallet_index(18)] + pub type Motion = pallet_motion; // Collator support. The order of these 4 are important and shall not change. #[runtime::pallet_index(20)] @@ -631,6 +315,8 @@ mod runtime { // Contracts #[runtime::pallet_index(40)] pub type Contracts = pallet_contracts::Pallet; + #[runtime::pallet_index(60)] + pub type Revive = pallet_revive::Pallet; // Proxy #[runtime::pallet_index(41)] @@ -687,355 +373,6 @@ impl Runtime { } } -impl_runtime_apis! { - - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - Runtime::impl_slot_duration() - } - - fn authorities() -> Vec { - pallet_aura::Authorities::::get().into_inner() - } - } - - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block) - } - - fn initialize_block(header: &::Header) -> ExtrinsicInclusionMode{ - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - - fn metadata_at_version(version: u32) -> Option { - Runtime::metadata_at_version(version) - } - - fn metadata_versions() -> Vec { - Runtime::metadata_versions() - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Nonce { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi - for Runtime - { - fn query_call_info( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::RuntimeDispatchInfo { - TransactionPayment::query_call_info(call, len) - } - fn query_call_fee_details( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_call_fee_details(call, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl pallet_contracts::ContractsApi - for Runtime - { - fn call( - origin: AccountId, - dest: AccountId, - value: Balance, - gas_limit: Option, - storage_deposit_limit: Option, - input_data: Vec, - ) -> pallet_contracts::ContractExecResult { - let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); - Contracts::bare_call( - origin, - dest, - value, - gas_limit, - storage_deposit_limit, - input_data, - CONTRACTS_DEBUG_OUTPUT, - CONTRACTS_EVENTS, - pallet_contracts::Determinism::Enforced, - ) - } - - fn instantiate( - origin: AccountId, - value: Balance, - gas_limit: Option, - storage_deposit_limit: Option, - code: pallet_contracts::Code, - data: Vec, - salt: Vec, - ) -> pallet_contracts::ContractInstantiateResult - { - let gas_limit = gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block); - Contracts::bare_instantiate( - origin, - value, - gas_limit, - storage_deposit_limit, - code, - data, - salt, - CONTRACTS_DEBUG_OUTPUT, - CONTRACTS_EVENTS, - ) - } - - fn upload_code( - origin: AccountId, - code: Vec, - storage_deposit_limit: Option, - determinism: pallet_contracts::Determinism, - ) -> pallet_contracts::CodeUploadResult - { - Contracts::bare_upload_code(origin, code, storage_deposit_limit, determinism) - } - - fn get_storage( - address: AccountId, - key: Vec, - ) -> pallet_contracts::GetStorageResult { - Contracts::get_storage(address, key) - } - } - - impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { - fn can_build_upon( - included_hash: ::Hash, - slot: cumulus_primitives_aura::Slot, - ) -> bool { - Runtime::impl_can_build_upon(included_hash, slot) - } - } - - impl cumulus_primitives_core::CollectCollationInfo for Runtime { - fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { - ParachainSystem::collect_collation_info(header) - } - } - - impl pallet_nfts_runtime_api::NftsApi for Runtime { - fn owner(collection: u32, item: u32) -> Option { - >::owner(&collection, &item) - } - - fn collection_owner(collection: u32) -> Option { - >::collection_owner(&collection) - } - - fn attribute( - collection: u32, - item: u32, - key: Vec, - ) -> Option> { - >::attribute(&collection, &item, &key) - } - - fn custom_attribute( - account: AccountId, - collection: u32, - item: u32, - key: Vec, - ) -> Option> { - >::custom_attribute( - &account, - &collection, - &item, - &key, - ) - } - - fn system_attribute( - collection: u32, - item: Option, - key: Vec, - ) -> Option> { - >::system_attribute(&collection, item.as_ref(), &key) - } - - fn collection_attribute(collection: u32, key: Vec) -> Option> { - >::collection_attribute(&collection, &key) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - let weight = Executive::try_runtime_upgrade(checks).unwrap(); - (weight, RuntimeBlockWeights::get().max_block) - } - - fn execute_block( - block: Block, - state_root_check: bool, - signature_check: bool, - select: frame_try_runtime::TryStateSelect, - ) -> Weight { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. - Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap() - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, alloc::string::String> { - use frame_benchmarking::{BenchmarkError, Benchmarking, BenchmarkBatch}; - - use frame_system_benchmarking::Pallet as SystemBench; - impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &Vec) -> Result<(), BenchmarkError> { - ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); - Ok(()) - } - - fn verify_set_code() { - System::assert_last_event(cumulus_pallet_parachain_system::Event::::ValidationFunctionStored.into()); - } - } - - use cumulus_pallet_session_benchmarking::Pallet as SessionBench; - impl cumulus_pallet_session_benchmarking::Config for Runtime {} - - use frame_support::traits::WhitelistedStorageKeys; - let whitelist = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) } - Ok(batches) - } - } - - impl sp_genesis_builder::GenesisBuilder for Runtime { - fn build_state(config: Vec) -> sp_genesis_builder::Result { - build_state::(config) - } - - fn get_preset(id: &Option) -> Option> { - get_preset::(id, genesis::get_preset) - } - - fn preset_names() -> Vec { - genesis::presets() - } - } -} - #[docify::export(register_validate_block)] cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, From 906043430b9e7e5a6ad27b981e09e40cc6439fd7 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Sat, 1 Mar 2025 05:21:57 +0100 Subject: [PATCH 12/16] style: fmt --- runtime/testnet/src/config/mod.rs | 2 +- runtime/testnet/src/config/utility.rs | 80 ++++++++++++++------------- 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/runtime/testnet/src/config/mod.rs b/runtime/testnet/src/config/mod.rs index 0f384569..3cc06048 100644 --- a/runtime/testnet/src/config/mod.rs +++ b/runtime/testnet/src/config/mod.rs @@ -16,5 +16,5 @@ pub mod system; // Utility. mod utility; // Public due to integration tests crate. -pub mod xcm; mod utility; +pub mod xcm; diff --git a/runtime/testnet/src/config/utility.rs b/runtime/testnet/src/config/utility.rs index 53720632..c0abe520 100644 --- a/runtime/testnet/src/config/utility.rs +++ b/runtime/testnet/src/config/utility.rs @@ -1,13 +1,15 @@ use frame_support::{ - pallet_prelude::ConstU32, - parameter_types, - traits::{fungible::HoldConsideration, EqualPrivilegeOnly, LinearStoragePrice}, + pallet_prelude::ConstU32, + parameter_types, + traits::{fungible::HoldConsideration, EqualPrivilegeOnly, LinearStoragePrice}, }; use frame_system::EnsureRoot; use parachains_common::Balance; -use crate::{AccountId, Weight, deposit, Balances, OriginCaller, Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, RuntimeHoldReason, Perbill}; -use crate::config::system::RuntimeBlockWeights; +use crate::{ + config::system::RuntimeBlockWeights, deposit, AccountId, Balances, OriginCaller, Perbill, + Preimage, Runtime, RuntimeCall, RuntimeEvent, RuntimeHoldReason, RuntimeOrigin, Weight, +}; parameter_types! { // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. @@ -18,13 +20,13 @@ parameter_types! { } impl pallet_multisig::Config for Runtime { - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = MaxSignatories; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_multisig::weights::SubstrateWeight; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = MaxSignatories; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_multisig::weights::SubstrateWeight; } parameter_types! { @@ -34,16 +36,16 @@ parameter_types! { } impl pallet_preimage::Config for Runtime { - type Consideration = HoldConsideration< - AccountId, - Balances, - PreimageHoldReason, - LinearStoragePrice, - >; - type Currency = Balances; - type ManagerOrigin = EnsureRoot; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_preimage::weights::SubstrateWeight; + type Consideration = HoldConsideration< + AccountId, + Balances, + PreimageHoldReason, + LinearStoragePrice, + >; + type Currency = Balances; + type ManagerOrigin = EnsureRoot; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_preimage::weights::SubstrateWeight; } parameter_types! { @@ -52,24 +54,24 @@ parameter_types! { } impl pallet_scheduler::Config for Runtime { - #[cfg(feature = "runtime-benchmarks")] - type MaxScheduledPerBlock = ConstU32<512>; - #[cfg(not(feature = "runtime-benchmarks"))] - type MaxScheduledPerBlock = ConstU32<50>; - type MaximumWeight = MaximumSchedulerWeight; - type OriginPrivilegeCmp = EqualPrivilegeOnly; - type PalletsOrigin = OriginCaller; - type Preimages = Preimage; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type RuntimeOrigin = RuntimeOrigin; - type ScheduleOrigin = EnsureRoot; - type WeightInfo = pallet_scheduler::weights::SubstrateWeight; + #[cfg(feature = "runtime-benchmarks")] + type MaxScheduledPerBlock = ConstU32<512>; + #[cfg(not(feature = "runtime-benchmarks"))] + type MaxScheduledPerBlock = ConstU32<50>; + type MaximumWeight = MaximumSchedulerWeight; + type OriginPrivilegeCmp = EqualPrivilegeOnly; + type PalletsOrigin = OriginCaller; + type Preimages = Preimage; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeOrigin = RuntimeOrigin; + type ScheduleOrigin = EnsureRoot; + type WeightInfo = pallet_scheduler::weights::SubstrateWeight; } impl pallet_utility::Config for Runtime { - type PalletsOrigin = OriginCaller; - type RuntimeCall = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type WeightInfo = pallet_utility::weights::SubstrateWeight; + type PalletsOrigin = OriginCaller; + type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = pallet_utility::weights::SubstrateWeight; } From 72ff01e115be7aea42a8d4b3928fd3a600288e6d Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Mon, 3 Mar 2025 00:20:18 +0100 Subject: [PATCH 13/16] fix: duplicated utility mod --- runtime/testnet/src/config/mod.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/runtime/testnet/src/config/mod.rs b/runtime/testnet/src/config/mod.rs index 3cc06048..e86e2d11 100644 --- a/runtime/testnet/src/config/mod.rs +++ b/runtime/testnet/src/config/mod.rs @@ -16,5 +16,4 @@ pub mod system; // Utility. mod utility; // Public due to integration tests crate. -mod utility; pub mod xcm; From e7cdd3539b88e38f4318ed2ced26e5d29f22ab4f Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Mon, 3 Mar 2025 00:30:11 +0100 Subject: [PATCH 14/16] fix: wrong SS58Prefix import --- node/src/command.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/node/src/command.rs b/node/src/command.rs index 9a1db5a0..554544fe 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -398,7 +398,7 @@ pub fn run() -> Result<()> { #[cfg(not(feature = "ismp"))] { sp_core::crypto::set_default_ss58_version( - pop_runtime_testnet::SS58Prefix::get().into(), + pop_runtime_testnet::config::system::SS58Prefix::get().into(), ); crate::service::start_parachain_node::( config, From 1643ecefbc74f532ef56401df20468526835816d Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Mon, 3 Mar 2025 22:06:20 +0100 Subject: [PATCH 15/16] chore(testnet): bump minor version --- runtime/testnet/Cargo.toml | 2 +- runtime/testnet/src/lib.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/runtime/testnet/Cargo.toml b/runtime/testnet/Cargo.toml index 39cf4dab..8048f6f2 100644 --- a/runtime/testnet/Cargo.toml +++ b/runtime/testnet/Cargo.toml @@ -6,7 +6,7 @@ homepage.workspace = true license = "Unlicense" name = "pop-runtime-testnet" repository.workspace = true -version = "0.4.3" +version = "0.5.0" [package.metadata.docs.rs] targets = [ "x86_64-unknown-linux-gnu" ] diff --git a/runtime/testnet/src/lib.rs b/runtime/testnet/src/lib.rs index e57ce724..a5f5f64b 100644 --- a/runtime/testnet/src/lib.rs +++ b/runtime/testnet/src/lib.rs @@ -214,7 +214,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { impl_name: Cow::Borrowed("pop"), authoring_version: 1, #[allow(clippy::zero_prefixed_literal)] - spec_version: 00_04_03, + spec_version: 00_05_00, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, From 91aa0a1a5de8d2ff1fac1b252367fcf12472ea60 Mon Sep 17 00:00:00 2001 From: Alejandro Martinez Andres <11448715+al3mart@users.noreply.github.com> Date: Mon, 3 Mar 2025 23:09:26 +0100 Subject: [PATCH 16/16] chore: update Cargo.lock --- Cargo.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index cf852e88..40d7ff01 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -13808,7 +13808,7 @@ dependencies = [ [[package]] name = "pop-runtime-testnet" -version = "0.4.3" +version = "0.5.0" dependencies = [ "cumulus-pallet-aura-ext 0.18.0", "cumulus-pallet-parachain-system 0.18.0",