// This file is part of Astar. // Copyright (C) Stake Technologies Pte.Ltd. // SPDX-License-Identifier: GPL-3.0-or-later // Astar is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Astar is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Astar. If not, see . //! The Astar Network runtime. This can be compiled with ``#[no_std]`, ready for Wasm. #![cfg_attr(not(feature = "std"), no_std)] // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 512. #![recursion_limit = "512"] extern crate alloc; extern crate core; #[cfg(feature = "runtime-benchmarks")] #[macro_use] extern crate frame_benchmarking; use alloc::{borrow::Cow, collections::btree_map::BTreeMap, vec, vec::Vec}; use core::marker::PhantomData; use cumulus_primitives_core::AggregateMessageOrigin; use ethereum::AuthorizationList; use frame_support::{ dispatch::DispatchClass, genesis_builder_helper, parameter_types, traits::{ fungible::{Balanced, Credit, HoldConsideration}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, EqualPrivilegeOnly, FindAuthor, Get, Imbalance, InsideBoth, InstanceFilter, LinearStoragePrice, Nothing, OnFinalize, OnUnbalanced, Randomness, WithdrawReasons, }, weights::{ constants::{RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND}, ConstantMultiplier, Weight, WeightToFee as WeightToFeeT, WeightToFeeCoefficient, WeightToFeeCoefficients, WeightToFeePolynomial, }, ConsensusEngineId, PalletId, }; use frame_system::{ limits::{BlockLength, BlockWeights}, EnsureNever, EnsureRoot, EnsureSigned, EnsureWithSuccess, }; use pallet_ethereum::PostLogContent; use pallet_evm::{FeeCalculator, GasWeightMapping, Runner}; use pallet_evm_precompile_assets_erc20::AddressToAssetId; use pallet_identity::legacy::IdentityInfo; use pallet_transaction_payment::{ FeeDetails, Multiplier, RuntimeDispatchInfo, TargetedFeeAdjustment, }; use pallet_tx_pause::RuntimeCallNameOf; use parity_scale_codec::{Compact, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen}; use polkadot_runtime_common::BlockHashCount; use sp_api::impl_runtime_apis; use sp_core::{sr25519, OpaqueMetadata, H160, H256, U256}; use sp_inherents::{CheckInherentsResult, InherentData}; use sp_runtime::{ generic, impl_opaque_keys, traits::{ AccountIdConversion, AccountIdLookup, BlakeTwo256, Block as BlockT, ConvertInto, DispatchInfoOf, Dispatchable, OpaqueKeys, PostDispatchInfoOf, UniqueSaturatedInto, Zero, }, transaction_validity::{TransactionSource, TransactionValidity, TransactionValidityError}, ApplyExtrinsicResult, FixedPointNumber, Perbill, Permill, Perquintill, RuntimeDebug, }; use xcm::{ v5::{AssetId as XcmAssetId, Location as XcmLocation}, IntoVersion, Version as XcmVersion, VersionedAsset, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm, }; use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; use astar_primitives::{ dapp_staking::{ AccountCheck as DappStakingAccountCheck, CycleConfiguration, DAppId, EraNumber, PeriodNumber, RankedTier, SmartContract, FIXED_NUMBER_OF_TIER_SLOTS, }, evm::{EVMFungibleAdapterWrapper, EvmRevertCodeHandler, TX_MAX_GAS_LIMIT}, governance::{ CommunityCouncilCollectiveInst, CommunityCouncilMembershipInst, CommunityTreasuryInst, EnsureRootOrAllMainCouncil, EnsureRootOrAllTechnicalCommittee, EnsureRootOrFourFifthsCommunityCouncil, EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil, EnsureRootOrThreeFourthMainCouncil, EnsureRootOrTwoThirdsCommunityCouncil, EnsureRootOrTwoThirdsMainCouncil, EnsureRootOrTwoThirdsTechnicalCommittee, MainCouncilCollectiveInst, MainCouncilMembershipInst, MainTreasuryInst, TechnicalCommitteeCollectiveInst, TechnicalCommitteeMembershipInst, }, xcm::AssetLocationIdConverter, Address, AssetId, BlockNumber, Hash, Header, Nonce, UnfreezeChainOnFailedMigration, }; pub use astar_primitives::{AccountId, Balance, Signature}; pub use pallet_dapp_staking::TierThreshold; pub use pallet_inflation::InflationParameters; pub use crate::precompiles::WhitelistedCalls; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; pub use frame_system::Call as SystemCall; pub use pallet_balances::Call as BalancesCall; use parachains_common::message_queue::NarrowOriginToSibling; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub mod genesis_config; mod precompiles; pub mod xcm_config; mod weights; use weights::{BlockExecutionWeight, ExtrinsicBaseWeight}; pub type AstarAssetLocationIdConverter = AssetLocationIdConverter; pub use precompiles::{AstarPrecompiles, ASSET_PRECOMPILE_ADDRESS_PREFIX}; pub type Precompiles = AstarPrecompiles; /// Constant values used within the runtime. pub const MICROASTR: Balance = 1_000_000_000_000; pub const MILLIASTR: Balance = 1_000 * MICROASTR; pub const ASTR: Balance = 1_000 * MILLIASTR; pub const STORAGE_BYTE_FEE: Balance = 20 * MICROASTR; /// Charge fee for stored bytes and items. pub const fn deposit(items: u32, bytes: u32) -> Balance { items as Balance * 100 * MILLIASTR + (bytes as Balance) * STORAGE_BYTE_FEE } /// Charge fee for stored bytes and items as part of `pallet-contracts`. /// /// The slight difference to general `deposit` function is because there is fixed bound on how large the DB /// key can grow so it doesn't make sense to have as high deposit per item as in the general approach. pub const fn contracts_deposit(items: u32, bytes: u32) -> Balance { items as Balance * 4 * MILLIASTR + (bytes as Balance) * STORAGE_BYTE_FEE } /// Change this to adjust the block time. pub const MILLISECS_PER_BLOCK: u64 = 6000; pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK; // Time is measured by number of blocks. pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber); pub const HOURS: BlockNumber = MINUTES * 60; pub const DAYS: BlockNumber = HOURS * 24; /// Maximum number of blocks simultaneously accepted by the Runtime, not yet included into the /// relay chain. pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = (2 + RELAY_PARENT_OFFSET) * BLOCK_PROCESSING_VELOCITY + 1; /// How many parachain blocks are processed by the relay chain per parent. Limits the number of /// blocks authored per slot. pub const BLOCK_PROCESSING_VELOCITY: u32 = 1; /// Relay chain slot duration, in milliseconds. pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000; /// Relay chain best block offset to build blocks on. const RELAY_PARENT_OFFSET: u32 = 0; // Make the WASM binary available. #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); #[cfg(feature = "std")] /// Wasm binary unwrapped. If built with `BUILD_DUMMY_WASM_BINARY`, the function panics. pub fn wasm_binary_unwrap() -> &'static [u8] { WASM_BINARY.expect( "Development wasm binary is not available. This means the client is \ built with `BUILD_DUMMY_WASM_BINARY` flag and it is only usable for \ production chains. Please rebuild with the flag disabled.", ) } /// Runtime version. #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: Cow::Borrowed("astar"), impl_name: Cow::Borrowed("astar"), authoring_version: 1, spec_version: 2400, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 3, system_version: 1, }; /// Native version. #[cfg(any(feature = "std", test))] pub fn native_version() -> NativeVersion { NativeVersion { runtime_version: VERSION, can_author_with: Default::default(), } } impl_opaque_keys! { pub struct SessionKeys { pub aura: Aura, } } /// We assume that ~10% of the block weight is consumed by `on_initalize` handlers. /// This is used to limit the maximal weight of a single extrinsic. const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10); /// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used /// by Operational extrinsics. const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); /// We allow for 2 seconds of compute with a 6 second average block time. const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts( WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2), polkadot_primitives::MAX_POV_SIZE as u64, ); parameter_types! { pub const Version: RuntimeVersion = VERSION; 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 SS58Prefix: u8 = 5; } pub struct BaseFilter; impl Contains for BaseFilter { fn contains(call: &RuntimeCall) -> bool { match call { // Wasm (ink!) smart contracts are being decommissioned. RuntimeCall::Contracts(..) => false, // Filter permission-less assets creation/destroying. // Custom asset's `id` should fit in `u32` as not to mix with service assets. RuntimeCall::Assets(method) => match method { pallet_assets::Call::create { id, .. } => *id < (u32::MAX as AssetId).into(), _ => true, }, // These modules are not allowed to be called by transactions: // To leave collator just shutdown it, next session funds will be released // Other modules should works: _ => true, } } } type SafeModeTxPauseFilter = InsideBoth; type BaseCallFilter = InsideBoth; impl frame_system::Config for Runtime { /// The identifier used to distinguish between accounts. type AccountId = AccountId; /// The aggregated dispatch type that is available for extrinsics. type RuntimeCall = RuntimeCall; /// The lookup mechanism to get account ID from whatever is passed in dispatchers. type Lookup = AccountIdLookup; /// The nonce type for storing how many extrinsics an account has signed. type Nonce = Nonce; /// The type for blocks. type Block = Block; /// The type for hashing blocks and tries. type Hash = Hash; /// The hashing algorithm used. type Hashing = BlakeTwo256; /// The ubiquitous event type. type RuntimeEvent = RuntimeEvent; /// The ubiquitous origin type. type RuntimeOrigin = RuntimeOrigin; /// The aggregated RuntimeTask type. type RuntimeTask = RuntimeTask; /// Maximum number of block number to block hash mappings to keep (oldest pruned first). type BlockHashCount = BlockHashCount; /// Runtime version. type Version = Version; /// Converts a module to an index of this module in the runtime. type PalletInfo = PalletInfo; type AccountData = pallet_balances::AccountData; type OnNewAccount = (); type OnKilledAccount = (); type DbWeight = RocksDbWeight; type BaseCallFilter = BaseCallFilter; type SystemWeightInfo = frame_system::weights::SubstrateWeight; type BlockWeights = RuntimeBlockWeights; type BlockLength = RuntimeBlockLength; type SS58Prefix = SS58Prefix; type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; type MaxConsumers = frame_support::traits::ConstU32<16>; type SingleBlockMigrations = (); type MultiBlockMigrator = MultiBlockMigrations; type PreInherents = (); type PostInherents = (); type PostTransactions = (); type ExtensionsWeightInfo = weights::frame_system_extensions::SubstrateWeight; } impl pallet_timestamp::Config for Runtime { /// A timestamp: milliseconds since the unix epoch. type Moment = u64; type OnTimestampSet = Aura; type MinimumPeriod = ConstU64<0>; type WeightInfo = pallet_timestamp::weights::SubstrateWeight; } parameter_types! { pub const BasicDeposit: Balance = deposit(1, 258); // 258 bytes on-chain pub const ByteDeposit: Balance = deposit(0, 1); pub const SubAccountDeposit: Balance = deposit(1, 53); // 53 bytes on-chain pub const UsernameDeposit: Balance = deposit(0, 32); pub const MaxSubAccounts: u32 = 100; pub const MaxAdditionalFields: u32 = 100; pub const MaxRegistrars: u32 = 20; } impl pallet_identity::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BasicDeposit = BasicDeposit; type ByteDeposit = ByteDeposit; type SubAccountDeposit = SubAccountDeposit; type MaxSubAccounts = MaxSubAccounts; type IdentityInformation = IdentityInfo; type MaxRegistrars = MaxRegistrars; type Slashed = (); type ForceOrigin = EnsureRoot<::AccountId>; type RegistrarOrigin = EnsureRoot<::AccountId>; type OffchainSignature = Signature; type SigningPublicKey = ::Signer; type UsernameAuthorityOrigin = EnsureRoot<::AccountId>; type PendingUsernameExpiration = ConstU32<{ 7 * DAYS }>; type MaxSuffixLength = ConstU32<7>; type MaxUsernameLength = ConstU32<32>; type WeightInfo = pallet_identity::weights::SubstrateWeight; type UsernameDeposit = UsernameDeposit; type UsernameGracePeriod = ConstU32<{ 7 * DAYS }>; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = (); } 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); } impl pallet_multisig::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type DepositBase = DepositBase; type DepositFactor = DepositFactor; type MaxSignatories = ConstU32<100>; type BlockNumberProvider = System; type WeightInfo = pallet_multisig::weights::SubstrateWeight; } parameter_types! { pub MaximumSchedulerWeight: Weight = NORMAL_DISPATCH_RATIO * RuntimeBlockWeights::get().max_block; } impl pallet_scheduler::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeOrigin = RuntimeOrigin; type PalletsOrigin = OriginCaller; type RuntimeCall = RuntimeCall; type BlockNumberProvider = System; type MaximumWeight = MaximumSchedulerWeight; type ScheduleOrigin = EnsureRoot; type MaxScheduledPerBlock = ConstU32<32>; // TODO: re-bench pallet_scheduler weights or use default weights. type WeightInfo = weights::pallet_scheduler::SubstrateWeight; type OriginPrivilegeCmp = EqualPrivilegeOnly; type Preimages = Preimage; } parameter_types! { pub const PreimageBaseDeposit: Balance = deposit(1, 0); pub const PreimageByteDeposit: Balance = deposit(0, 1); pub const PreimageHoldReason: RuntimeHoldReason = RuntimeHoldReason::Preimage(pallet_preimage::HoldReason::Preimage); } impl pallet_preimage::Config for Runtime { type WeightInfo = pallet_preimage::weights::SubstrateWeight; type RuntimeEvent = RuntimeEvent; type Currency = Balances; type ManagerOrigin = EnsureRoot; type Consideration = HoldConsideration< AccountId, Balances, PreimageHoldReason, LinearStoragePrice, >; } parameter_types! { pub const MinimumStakingAmount: Balance = 500 * ASTR; } #[cfg(feature = "runtime-benchmarks")] pub struct DAppStakingBenchmarkHelper(PhantomData<(SC, ACC)>); #[cfg(feature = "runtime-benchmarks")] impl pallet_dapp_staking::BenchmarkHelper, AccountId> for DAppStakingBenchmarkHelper, AccountId> { fn get_smart_contract(id: u32) -> SmartContract { let id_bytes = id.to_le_bytes(); let mut account = [0u8; 32]; account[..id_bytes.len()].copy_from_slice(&id_bytes); SmartContract::Wasm(AccountId::from(account)) } fn set_balance(account: &AccountId, amount: Balance) { use frame_support::traits::fungible::Unbalanced as FunUnbalanced; Balances::write_balance(account, amount) .expect("Must succeed in test/benchmark environment."); } } pub struct AccountCheck; impl DappStakingAccountCheck for AccountCheck { fn allowed_to_stake(account: &AccountId) -> bool { !CollatorSelection::is_account_candidate(account) } } impl pallet_dapp_staking::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeFreezeReason = RuntimeFreezeReason; type Currency = Balances; type SmartContract = SmartContract; type ContractRegisterOrigin = EnsureRootOrTwoThirdsCommunityCouncil; type ContractUnregisterOrigin = EnsureRootOrFourFifthsCommunityCouncil; type ManagerOrigin = EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil; type StakingRewardHandler = Inflation; type CycleConfiguration = InflationCycleConfig; type Observers = Inflation; type AccountCheck = AccountCheck; type EraRewardSpanLength = ConstU32<16>; type RewardRetentionInPeriods = ConstU32<4>; type MaxNumberOfContracts = ConstU32<{ FIXED_NUMBER_OF_TIER_SLOTS as u32 }>; type MaxUnlockingChunks = ConstU32<8>; type MinimumLockedAmount = MinimumStakingAmount; type UnlockingPeriod = ConstU32<9>; type MaxNumberOfStakedContracts = ConstU32<16>; type MinimumStakeAmount = MinimumStakingAmount; type NumberOfTiers = ConstU32<4>; type RankingEnabled = ConstBool; type MaxBonusSafeMovesPerPeriod = ConstU8<2>; type WeightInfo = weights::pallet_dapp_staking::SubstrateWeight; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = DAppStakingBenchmarkHelper, AccountId>; } pub struct InflationPayoutPerBlock; impl pallet_inflation::PayoutPerBlock> for InflationPayoutPerBlock { fn treasury(reward: Credit) { let _ = Balances::resolve(&TreasuryPalletId::get().into_account_truncating(), reward); } fn collators(reward: Credit) { CollatorRewardPot::on_unbalanced(reward); } } pub struct InflationCycleConfig; impl CycleConfiguration for InflationCycleConfig { fn periods_per_cycle() -> u32 { 1 } fn eras_per_voting_subperiod() -> u32 { 1 } fn eras_per_build_and_earn_subperiod() -> u32 { 364 } fn blocks_per_era() -> BlockNumber { 24 * HOURS } } impl pallet_inflation::Config for Runtime { type Currency = Balances; type PayoutPerBlock = InflationPayoutPerBlock; type CycleConfiguration = InflationCycleConfig; type WeightInfo = weights::pallet_inflation::SubstrateWeight; } impl pallet_utility::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type PalletsOrigin = OriginCaller; type WeightInfo = pallet_utility::weights::SubstrateWeight; } 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; pub const RelayParentOffset: u32 = RELAY_PARENT_OFFSET; } impl cumulus_pallet_parachain_system::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnSystemEvent = (); type SelfParaId = parachain_info::Pallet; type OutboundXcmpMessageSource = XcmpQueue; type DmpQueue = frame_support::traits::EnqueueWithOrigin; type ReservedDmpWeight = ReservedDmpWeight; type XcmpMessageHandler = XcmpQueue; type ReservedXcmpWeight = ReservedXcmpWeight; type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; type ConsensusHook = ConsensusHook; type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight; type RelayParentOffset = RelayParentOffset; } type ConsensusHook = cumulus_pallet_aura_ext::FixedVelocityConsensusHook< Runtime, RELAY_CHAIN_SLOT_DURATION_MILLIS, BLOCK_PROCESSING_VELOCITY, UNINCLUDED_SEGMENT_CAPACITY, >; impl parachain_info::Config for Runtime {} impl pallet_aura::Config for Runtime { type AuthorityId = AuraId; type DisabledValidators = (); type MaxAuthorities = ConstU32<250>; type AllowMultipleBlocksPerSlot = ConstBool; type SlotDuration = ConstU64; } impl cumulus_pallet_aura_ext::Config for Runtime {} impl pallet_authorship::Config for Runtime { type FindAuthor = pallet_session::FindAccountFromAuthorIndex; type EventHandler = (CollatorSelection,); } parameter_types! { pub const SessionPeriod: BlockNumber = HOURS; pub const SessionOffset: BlockNumber = 0; } impl pallet_session::Config for Runtime { type RuntimeEvent = RuntimeEvent; type ValidatorId = ::AccountId; type ValidatorIdOf = pallet_collator_selection::IdentityCollator; type ShouldEndSession = pallet_session::PeriodicSessions; type NextSessionRotation = pallet_session::PeriodicSessions; type SessionManager = CollatorSelection; type SessionHandler = ::KeyTypeIdProviders; type Keys = SessionKeys; type DisablingStrategy = (); type WeightInfo = pallet_session::weights::SubstrateWeight; type Currency = Balances; type KeyDeposit = (); } parameter_types! { pub const PotId: PalletId = PalletId(*b"PotStake"); pub const MaxCandidates: u32 = 148; pub const MinCandidates: u32 = 1; pub const MaxInvulnerables: u32 = 48; pub const SlashRatio: Perbill = Perbill::from_percent(1); pub const KickThreshold: BlockNumber = 2 * HOURS; // 2 SessionPeriod } pub struct CollatorSelectionAccountCheck; impl pallet_collator_selection::AccountCheck for CollatorSelectionAccountCheck { fn allowed_candidacy(account: &AccountId) -> bool { !DappStaking::is_staker(account) } } impl pallet_collator_selection::Config for Runtime { type Currency = Balances; type UpdateOrigin = EnsureRoot; type ForceRemovalOrigin = EnsureRootOrThreeFourthMainCouncil; type GovernanceOrigin = EnsureRootOrTwoThirdsMainCouncil; type PotId = PotId; type MaxCandidates = MaxCandidates; type MinCandidates = MinCandidates; type MaxInvulnerables = MaxInvulnerables; // should be a multiple of session or things will get inconsistent type KickThreshold = KickThreshold; type ValidatorId = ::AccountId; type ValidatorIdOf = pallet_collator_selection::IdentityCollator; type ValidatorRegistration = Session; type ValidatorSet = Session; type SlashRatio = SlashRatio; type AccountCheck = CollatorSelectionAccountCheck; type WeightInfo = pallet_collator_selection::weights::SubstrateWeight; } parameter_types! { pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const DappsStakingPalletId: PalletId = PalletId(*b"py/dpsst"); pub TreasuryAccountId: AccountId = TreasuryPalletId::get().into_account_truncating(); } pub struct CollatorRewardPot; impl OnUnbalanced> for CollatorRewardPot { fn on_nonzero_unbalanced(amount: Credit) { let staking_pot = PotId::get().into_account_truncating(); let _ = Balances::resolve(&staking_pot, amount); } } parameter_types! { pub const ExistentialDeposit: Balance = 1_000_000; pub const MaxLocks: u32 = 50; pub const MaxReserves: u32 = 50; } impl pallet_balances::Config for Runtime { type Balance = Balance; type DustRemoval = (); type RuntimeEvent = RuntimeEvent; type MaxLocks = MaxLocks; type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; type ExistentialDeposit = ExistentialDeposit; type AccountStore = frame_system::Pallet; type WeightInfo = pallet_balances::weights::SubstrateWeight; type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = RuntimeFreezeReason; type MaxFreezes = ConstU32<1>; type DoneSlashHandler = (); } impl AddressToAssetId for Runtime { fn address_to_asset_id(address: H160) -> Option { let mut data = [0u8; 16]; let address_bytes: [u8; 20] = address.into(); if ASSET_PRECOMPILE_ADDRESS_PREFIX.eq(&address_bytes[0..4]) { data.copy_from_slice(&address_bytes[4..20]); Some(u128::from_be_bytes(data)) } else { None } } fn asset_id_to_address(asset_id: AssetId) -> H160 { let mut data = [0u8; 20]; data[0..4].copy_from_slice(ASSET_PRECOMPILE_ADDRESS_PREFIX); data[4..20].copy_from_slice(&asset_id.to_be_bytes()); H160::from(data) } } parameter_types! { pub const AssetDeposit: Balance = 1000 * ASTR; pub const AssetsStringLimit: u32 = 50; /// Key = 32 bytes, Value = 36 bytes (32+1+1+1+1) // https://github.com/paritytech/substrate/blob/069917b/frame/assets/src/lib.rs#L257L271 pub const MetadataDepositBase: Balance = deposit(1, 68); pub const MetadataDepositPerByte: Balance = deposit(0, 1); pub const AssetAccountDeposit: Balance = deposit(1, 18); } impl pallet_assets::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Balance = Balance; type AssetId = AssetId; type Currency = Balances; type CreateOrigin = AsEnsureOriginWithArg>; type ForceOrigin = EnsureRoot; type AssetDeposit = AssetDeposit; type MetadataDepositBase = MetadataDepositBase; type MetadataDepositPerByte = MetadataDepositPerByte; type AssetAccountDeposit = AssetAccountDeposit; type ApprovalDeposit = ExistentialDeposit; type StringLimit = AssetsStringLimit; type Freezer = (); type Extra = (); type Holder = (); type WeightInfo = weights::pallet_assets::SubstrateWeight; type RemoveItemsLimit = ConstU32<1000>; type AssetIdParameter = Compact; type ReserveData = (); type CallbackHandle = EvmRevertCodeHandler; #[cfg(feature = "runtime-benchmarks")] type BenchmarkHelper = astar_primitives::benchmarks::AssetsBenchmarkHelper; } parameter_types! { pub const MinVestedTransfer: Balance = 100 * ASTR; pub UnvestedFundsAllowedWithdrawReasons: WithdrawReasons = WithdrawReasons::except(WithdrawReasons::TRANSFER | WithdrawReasons::RESERVE); } impl pallet_vesting::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type BlockNumberToBalance = ConvertInto; type MinVestedTransfer = MinVestedTransfer; type WeightInfo = pallet_vesting::weights::SubstrateWeight; type UnvestedFundsAllowedWithdrawReasons = UnvestedFundsAllowedWithdrawReasons; type BlockNumberProvider = System; // `VestingInfo` encode length is 36bytes. 28 schedules gets encoded as 1009 bytes, which is the // highest number of schedules that encodes less than 2^10. const MAX_VESTING_SCHEDULES: u32 = 28; } parameter_types! { pub const DepositPerItem: Balance = contracts_deposit(1, 0); pub const DepositPerByte: Balance = contracts_deposit(0, 1); // Fallback value if storage deposit limit not set by the user pub const DefaultDepositLimit: Balance = contracts_deposit(16, 16 * 1024); pub const MaxDelegateDependencies: u32 = 32; pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(10); pub Schedule: pallet_contracts::Schedule = Default::default(); } /// Codes using the randomness functionality cannot be uploaded. Neither can contracts /// be instantiated from existing codes that use this deprecated functionality. /// /// But since some `Randomness` config type is still required for `pallet-contracts`, we provide this dummy type. pub struct DummyDeprecatedRandomness; impl Randomness for DummyDeprecatedRandomness { fn random(_: &[u8]) -> (Hash, BlockNumber) { (Default::default(), Zero::zero()) } } impl pallet_contracts::Config for Runtime { type Time = Timestamp; type Randomness = DummyDeprecatedRandomness; type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type RuntimeHoldReason = RuntimeHoldReason; /// The safest default is to allow no calls at all. /// /// Runtimes should whitelist dispatchables that are allowed to be called from contracts /// and make sure they are stable. Dispatchables exposed to contracts are not allowed to /// change because that would break already deployed contracts. The `Call` structure itself /// is not allowed to change the indices of existing pallets, too. type CallFilter = Nothing; type DepositPerItem = DepositPerItem; type DepositPerByte = DepositPerByte; type DefaultDepositLimit = DefaultDepositLimit; type CallStack = [pallet_contracts::Frame; 5]; type WeightPrice = pallet_transaction_payment::Pallet; type WeightInfo = pallet_contracts::weights::SubstrateWeight; type ChainExtension = (); type Schedule = Schedule; type AddressGenerator = pallet_contracts::DefaultAddressGenerator; type MaxCodeLen = ConstU32<{ 123 * 1024 }>; type MaxStorageKeyLen = ConstU32<128>; type UnsafeUnstableInterface = ConstBool; type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; type MaxDelegateDependencies = MaxDelegateDependencies; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type Debug = (); type Environment = (); type Migrations = (); type Xcm = (); type UploadOrigin = EnsureNever<::AccountId>; type InstantiateOrigin = EnsureNever<::AccountId>; type ApiVersion = (); type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; } // These values are based on the Astar 2.0 Tokenomics Modeling report. parameter_types! { pub const TransactionLengthFeeFactor: Balance = 23_500_000_000_000; // 0.0000235 ASTR per byte pub const WeightFeeFactor: Balance = 30_855_000_000_000_000; // Around 0.03 ASTR per unit of ref time. pub const TargetBlockFullness: Perquintill = Perquintill::from_percent(25); pub const OperationalFeeMultiplier: u8 = 5; pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(000_015, 1_000_000); // 0.000_015 pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 10); // 0.1 pub MaximumMultiplier: Multiplier = Multiplier::saturating_from_integer(10); // 10 } /// Handles converting a weight scalar to a fee value, based on the scale and granularity of the /// node's balance type. /// /// This should typically create a mapping between the following ranges: /// - [0, MAXIMUM_BLOCK_WEIGHT] /// - [Balance::min, Balance::max] /// /// Yet, it can be used for any other sort of change to weight-fee. Some examples being: /// - Setting it to `0` will essentially disable the weight fee. /// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged. pub struct WeightToFee; impl WeightToFeePolynomial for WeightToFee { type Balance = Balance; fn polynomial() -> WeightToFeeCoefficients { #[cfg(feature = "runtime-benchmarks")] let (p, q) = (Balance::from(1u128), Balance::from(1u128)); #[cfg(not(feature = "runtime-benchmarks"))] let (p, q) = ( WeightFeeFactor::get(), Balance::from(ExtrinsicBaseWeight::get().ref_time()), ); smallvec::smallvec![WeightToFeeCoefficient { degree: 1, negative: false, coeff_frac: Perbill::from_rational(p % q, q), coeff_integer: p / q, }] } } /// Handles coverting weight consumed by XCM into native currency fee. /// /// Similar to standard `WeightToFee` handler, but force uses the minimum multiplier. pub struct XcmWeightToFee; impl WeightToFeeT for XcmWeightToFee { type Balance = Balance; fn weight_to_fee(n: &Weight) -> Self::Balance { MinimumMultiplier::get().saturating_mul_int(WeightToFee::weight_to_fee(&n)) } } pub struct DealWithFees; impl OnUnbalanced> for DealWithFees { fn on_unbalanceds(mut fees_then_tips: impl Iterator>) { if let Some(fees) = fees_then_tips.next() { // Burn 80% of fees, rest goes to collator, including 100% of the tips. let (to_burn, mut collator) = fees.ration(80, 20); if let Some(tips) = fees_then_tips.next() { tips.merge_into(&mut collator); } // burn part of the fees drop(to_burn); // pay fees to collator >::on_unbalanced(collator); } } fn on_unbalanced(amount: Credit) { Self::on_unbalanceds(Some(amount).into_iter()); } } impl pallet_transaction_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter; type WeightToFee = WeightToFee; type OperationalFeeMultiplier = OperationalFeeMultiplier; type FeeMultiplierUpdate = TargetedFeeAdjustment< Self, TargetBlockFullness, AdjustmentVariable, MinimumMultiplier, MaximumMultiplier, >; #[cfg(not(feature = "runtime-benchmarks"))] type LengthToFee = ConstantMultiplier; #[cfg(feature = "runtime-benchmarks")] type LengthToFee = ConstantMultiplier>; type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight; } parameter_types! { pub DefaultBaseFeePerGas: U256 = U256::from(1_470_000_000_000_u128); pub MinBaseFeePerGas: U256 = U256::from(800_000_000_000_u128); pub MaxBaseFeePerGas: U256 = U256::from(80_000_000_000_000_u128); pub StepLimitRatio: Perquintill = Perquintill::from_rational(93_u128, 1_000_000); } /// Simple wrapper for fetching current native transaction fee weight fee multiplier. pub struct AdjustmentFactorGetter; impl Get for AdjustmentFactorGetter { fn get() -> Multiplier { pallet_transaction_payment::NextFeeMultiplier::::get() } } impl pallet_dynamic_evm_base_fee::Config for Runtime { type DefaultBaseFeePerGas = DefaultBaseFeePerGas; type MinBaseFeePerGas = MinBaseFeePerGas; type MaxBaseFeePerGas = MaxBaseFeePerGas; type AdjustmentFactor = AdjustmentFactorGetter; type WeightFactor = WeightFeeFactor; type StepLimitRatio = StepLimitRatio; type WeightInfo = pallet_dynamic_evm_base_fee::weights::SubstrateWeight; } /// Current approximation of the gas/s consumption considering /// EVM execution over compiled WASM (on 4.4Ghz CPU). /// Given the 500ms Weight, from which 75% only are used for transactions, /// the total EVM execution gas limit is: GAS_PER_SECOND * 0.500 * 0.75 ~= 15_000_000. pub const GAS_PER_SECOND: u64 = 40_000_000; /// Approximate ratio of the amount of Weight per Gas. /// u64 works for approximations because Weight is a very small unit compared to gas. pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND.saturating_div(GAS_PER_SECOND); pub struct FindAuthorTruncated(PhantomData); impl> FindAuthor for FindAuthorTruncated { fn find_author<'a, I>(digests: I) -> Option where I: 'a + IntoIterator, { if let Some(author_index) = F::find_author(digests) { let authority_id = pallet_aura::Authorities::::get()[author_index as usize].clone(); return Some(H160::from_slice(&authority_id.encode()[4..24])); } None } } parameter_types! { /// Ethereum-compatible chain_id: /// * Dusty: 80 /// * Shibuya: 81 /// * Shiden: 336 /// * Astar: 592 pub ChainId: u64 = 0x250; /// EVM gas limit pub BlockGasLimit: U256 = U256::from( NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS ); pub PrecompilesValue: Precompiles = AstarPrecompiles::<_, _>::new(); pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0); /// The amount of gas per PoV size. Value is calculated as: /// /// max_gas_limit = max_tx_ref_time / WEIGHT_PER_GAS = max_pov_size * gas_limit_pov_size_ratio /// gas_limit_pov_size_ratio = ceil((max_tx_ref_time / WEIGHT_PER_GAS) / max_pov_size) pub const GasLimitPovSizeRatio: u64 = 8; /// Maximum gas allowed per transaction (EIP-7825). Set above the EIP-7825 default /// of 16,777,216 to accommodate large contract deployments and complex calls. pub TransactionGasLimit: Option = Some(U256::from(TX_MAX_GAS_LIMIT)); } impl pallet_evm::Config for Runtime { type FeeCalculator = DynamicEvmBaseFee; type GasWeightMapping = pallet_evm::FixedGasWeightMapping; type WeightPerGas = WeightPerGas; type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping; type CallOrigin = pallet_evm::EnsureAddressRoot; type WithdrawOrigin = pallet_evm::EnsureAddressTruncated; type AddressMapping = pallet_evm::HashedAddressMapping; type Currency = Balances; type Runner = pallet_evm::runner::stack::Runner; type PrecompilesType = Precompiles; type PrecompilesValue = PrecompilesValue; type ChainId = ChainId; type OnChargeTransaction = EVMFungibleAdapterWrapper; type BlockGasLimit = BlockGasLimit; type Timestamp = Timestamp; type OnCreate = (); type FindAuthor = FindAuthorTruncated; type GasLimitPovSizeRatio = GasLimitPovSizeRatio; type AccountProvider = pallet_evm::FrameSystemAccountProvider; // gas based storage limit not enabled type GasLimitStorageGrowthRatio = ConstU64<0>; type TransactionGasLimit = TransactionGasLimit; type WeightInfo = pallet_evm::weights::SubstrateWeight; type CreateOriginFilter = (); type CreateInnerOriginFilter = (); } parameter_types! { pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes; } impl pallet_ethereum::Config for Runtime { type StateRoot = pallet_ethereum::IntermediateStateRoot<::Version>; type PostLogContent = PostBlockAndTxnHashes; // Maximum length (in bytes) of revert message to include in Executed event type ExtraDataLength = ConstU32<30>; type AllowUnprotectedTxs = ConstBool; } #[cfg(feature = "astar-sudo")] impl pallet_sudo::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type WeightInfo = pallet_sudo::weights::SubstrateWeight; } impl pallet_xc_asset_config::Config for Runtime { type AssetId = AssetId; type ManagerOrigin = EnsureRoot; type WeightInfo = pallet_xc_asset_config::weights::SubstrateWeight; } parameter_types! { pub MessageQueueServiceWeight: Weight = Perbill::from_percent(25) * RuntimeBlockWeights::get().max_block; } impl pallet_message_queue::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = pallet_message_queue::weights::SubstrateWeight; #[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, >; type Size = u32; type QueueChangeHandler = NarrowOriginToSibling; type QueuePausedQuery = NarrowOriginToSibling; type HeapSize = ConstU32<{ 128 * 1048 }>; type MaxStale = ConstU32<8>; type ServiceWeight = MessageQueueServiceWeight; type IdleMaxServiceWeight = MessageQueueServiceWeight; } /// The type used to represent the kinds of proxying allowed. #[derive( Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, DecodeWithMemTracking, RuntimeDebug, MaxEncodedLen, scale_info::TypeInfo, )] pub enum ProxyType { /// Allows all runtime calls for proxy account Any, /// Allows only NonTransfer runtime calls for proxy account /// To know exact calls check InstanceFilter implementation for ProxyTypes NonTransfer, /// All Runtime calls from Pallet Balances allowed for proxy account Balances, /// All Runtime calls from Pallet Assets allowed for proxy account Assets, /// Only provide_judgement call from pallet identity allowed for proxy account IdentityJudgement, /// Only reject_announcement call from pallet proxy allowed for proxy account CancelProxy, /// All runtime calls from pallet DappStaking allowed for proxy account DappStaking, /// Only claim_staker call from pallet DappStaking allowed for proxy account StakerRewardClaim, /// All governance related calls allowed for proxy account Governance, } impl Default for ProxyType { fn default() -> Self { Self::Any } } impl InstanceFilter for ProxyType { fn filter(&self, c: &RuntimeCall) -> bool { match self { // Always allowed RuntimeCall::Utility no matter type. // Only transactions allowed by Proxy.filter can be executed _ if matches!(c, RuntimeCall::Utility(..)) => true, ProxyType::Any => true, ProxyType::NonTransfer => { matches!( c, RuntimeCall::System(..) | RuntimeCall::Identity(..) | RuntimeCall::Multisig(..) | RuntimeCall::Proxy(..) | RuntimeCall::Vesting( pallet_vesting::Call::vest { .. } | pallet_vesting::Call::vest_other { .. } ) | RuntimeCall::DappStaking(..) | RuntimeCall::CollatorSelection(..) | RuntimeCall::XcAssetConfig(..) | RuntimeCall::Session(..) ) } ProxyType::Balances => { matches!(c, RuntimeCall::Balances(..)) } ProxyType::Assets => { matches!(c, RuntimeCall::Assets(..)) } ProxyType::IdentityJudgement => { matches!( c, RuntimeCall::Identity(pallet_identity::Call::provide_judgement { .. }) ) } ProxyType::CancelProxy => { matches!( c, RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. }) ) } ProxyType::DappStaking => { matches!(c, RuntimeCall::DappStaking(..)) } ProxyType::StakerRewardClaim => { matches!( c, RuntimeCall::DappStaking( pallet_dapp_staking::Call::claim_staker_rewards { .. } ) ) } ProxyType::Governance => { matches!( c, RuntimeCall::Democracy(..) | RuntimeCall::Council(..) | RuntimeCall::TechnicalCommittee(..) | RuntimeCall::CommunityCouncil(..) ) } } } fn is_superset(&self, o: &Self) -> bool { match (self, o) { (x, y) if x == y => true, (ProxyType::Any, _) => true, (_, ProxyType::Any) => false, (ProxyType::DappStaking, ProxyType::StakerRewardClaim) => true, _ => false, } } } parameter_types! { // One storage item; key size 32, value size 8; . pub const ProxyDepositBase: Balance = deposit(1, 8); // Additional storage item size of 33 bytes. pub const ProxyDepositFactor: Balance = deposit(0, 33); pub const MaxProxies: u16 = 32; pub const MaxPending: u16 = 32; pub const AnnouncementDepositBase: Balance = deposit(1, 8); pub const AnnouncementDepositFactor: Balance = deposit(0, 66); } impl pallet_proxy::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type Currency = Balances; type ProxyType = ProxyType; type ProxyDepositBase = ProxyDepositBase; type ProxyDepositFactor = ProxyDepositFactor; type MaxProxies = MaxProxies; type BlockNumberProvider = System; type WeightInfo = pallet_proxy::weights::SubstrateWeight; type MaxPending = MaxPending; type CallHasher = BlakeTwo256; type AnnouncementDepositBase = AnnouncementDepositBase; type AnnouncementDepositFactor = AnnouncementDepositFactor; } parameter_types! { pub const CouncilMaxMembers: u32 = 16; pub const TechnicalCommitteeMaxMembers: u32 = 8; pub const CommunityCouncilMaxMembers: u32 = 32; } impl pallet_membership::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; type MembershipInitialized = Council; type MembershipChanged = Council; type MaxMembers = CouncilMaxMembers; type WeightInfo = pallet_membership::weights::SubstrateWeight; } impl pallet_membership::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; type MembershipInitialized = TechnicalCommittee; type MembershipChanged = TechnicalCommittee; type MaxMembers = TechnicalCommitteeMaxMembers; type WeightInfo = pallet_membership::weights::SubstrateWeight; } impl pallet_membership::Config for Runtime { type RuntimeEvent = RuntimeEvent; type AddOrigin = EnsureRootOrTwoThirdsMainCouncil; type RemoveOrigin = EnsureRootOrTwoThirdsMainCouncil; type SwapOrigin = EnsureRootOrTwoThirdsMainCouncil; type ResetOrigin = EnsureRootOrTwoThirdsMainCouncil; type PrimeOrigin = EnsureRootOrTwoThirdsMainCouncil; type MembershipInitialized = CommunityCouncil; type MembershipChanged = CommunityCouncil; type MaxMembers = CommunityCouncilMaxMembers; type WeightInfo = pallet_membership::weights::SubstrateWeight; } parameter_types! { pub MaxProposalWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; } impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU32<{ 5 * DAYS }>; type MaxProposals = ConstU32<16>; type MaxMembers = CouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type SetMembersOrigin = EnsureRoot; type MaxProposalWeight = MaxProposalWeight; type KillOrigin = EnsureRoot; type DisapproveOrigin = EnsureRoot; type Consideration = (); type WeightInfo = pallet_collective::weights::SubstrateWeight; } impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU32<{ 5 * DAYS }>; type MaxProposals = ConstU32<16>; type MaxMembers = TechnicalCommitteeMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type SetMembersOrigin = EnsureRoot; type MaxProposalWeight = MaxProposalWeight; type KillOrigin = EnsureRoot; type DisapproveOrigin = EnsureRoot; type Consideration = (); type WeightInfo = pallet_collective::weights::SubstrateWeight; } impl pallet_collective::Config for Runtime { type RuntimeOrigin = RuntimeOrigin; type Proposal = RuntimeCall; type RuntimeEvent = RuntimeEvent; type MotionDuration = ConstU32<{ 5 * DAYS }>; type MaxProposals = ConstU32<16>; type MaxMembers = CommunityCouncilMaxMembers; type DefaultVote = pallet_collective::PrimeDefaultVote; type SetMembersOrigin = EnsureRoot; type MaxProposalWeight = MaxProposalWeight; type KillOrigin = EnsureRoot; type DisapproveOrigin = EnsureRoot; type Consideration = (); type WeightInfo = pallet_collective::weights::SubstrateWeight; } impl pallet_democracy::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type EnactmentPeriod = ConstU32<{ 2 * DAYS }>; type LaunchPeriod = ConstU32<{ 7 * DAYS }>; type VotingPeriod = ConstU32<{ 7 * DAYS }>; // Match with dApp staking unlocking period type VoteLockingPeriod = ConstU32<{ 9 * DAYS }>; type MinimumDeposit = ConstU128<{ 1000 * ASTR }>; type FastTrackVotingPeriod = ConstU32<{ 2 * HOURS }>; type CooloffPeriod = ConstU32<{ 7 * DAYS }>; type MaxVotes = ConstU32<128>; type MaxProposals = ConstU32<128>; type MaxDeposits = ConstU32<128>; type MaxBlacklisted = ConstU32<128>; /// A two third majority of the Council can choose the next external "super majority approve" proposal. type ExternalOrigin = EnsureRootOrTwoThirdsMainCouncil; /// A two third majority of the Council can choose the next external "majority approve" proposal. Also bypasses blacklist filter. type ExternalMajorityOrigin = EnsureRootOrTwoThirdsMainCouncil; /// Unanimous approval of the Council can choose the next external "super majority against" proposal. type ExternalDefaultOrigin = EnsureRootOrAllMainCouncil; /// A two third majority of the Technical Committee can have an external proposal tabled immediately /// for a _fast track_ vote, and a custom enactment period. type FastTrackOrigin = EnsureRootOrTwoThirdsTechnicalCommittee; /// Unanimous approval of the Technical Committee can have an external proposal tabled immediately /// for a completely custom _voting period length_ vote, and a custom enactment period. type InstantOrigin = EnsureRootOrAllTechnicalCommittee; type InstantAllowed = ConstBool; /// A two third majority of the Council can cancel a passed proposal. Can happen only once per unique proposal. type CancellationOrigin = EnsureRootOrTwoThirdsMainCouncil; /// Only a passed public referendum can permanently blacklist a proposal. type BlacklistOrigin = EnsureRoot; /// An unanimous Technical Committee can cancel a public proposal, slashing the deposit(s). type CancelProposalOrigin = EnsureRootOrAllTechnicalCommittee; /// Any member of the Technical Committee can veto Council's proposal. This can be only done once per proposal, and _veto_ lasts for a _cooloff_ period. type VetoOrigin = pallet_collective::EnsureMember; type SubmitOrigin = EnsureSigned; type PalletsOrigin = OriginCaller; type Preimages = Preimage; type Scheduler = Scheduler; type Slash = Treasury; type WeightInfo = pallet_democracy::weights::SubstrateWeight; } parameter_types! { pub const ProposalBond: Permill = Permill::from_percent(5); pub MainTreasuryAccount: AccountId = Treasury::account_id(); } impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; type RuntimeEvent = RuntimeEvent; // Two origins which can either approve or reject the spending proposal type ApproveOrigin = EnsureRootOrTwoThirdsMainCouncil; type RejectOrigin = EnsureRootOrTwoThirdsMainCouncil; type OnSlash = Treasury; type ProposalBond = ProposalBond; type ProposalBondMinimum = ConstU128<{ 100 * ASTR }>; type ProposalBondMaximum = ConstU128<{ 1000 * ASTR }>; type SpendPeriod = ConstU32<{ 7 * DAYS }>; // We don't do periodic burns of the treasury type Burn = (); type BurnDestination = (); type SpendFunds = (); type MaxApprovals = ConstU32<64>; type WeightInfo = pallet_treasury::weights::SubstrateWeight; } parameter_types! { pub const CommunityTreasuryPalletId: PalletId = PalletId(*b"py/comtr"); } impl pallet_treasury::Config for Runtime { type PalletId = CommunityTreasuryPalletId; type Currency = Balances; type RuntimeEvent = RuntimeEvent; // Two origins which can either approve or reject the spending proposal type ApproveOrigin = EnsureRootOrTwoThirdsCommunityCouncil; type RejectOrigin = EnsureRootOrTwoThirdsCommunityCouncil; type OnSlash = CommunityTreasury; type ProposalBond = ProposalBond; type ProposalBondMinimum = ConstU128<{ 100 * ASTR }>; type ProposalBondMaximum = ConstU128<{ 1000 * ASTR }>; type SpendPeriod = ConstU32<{ 7 * DAYS }>; // We don't do periodic burns of the community treasury type Burn = (); type BurnDestination = (); type SpendFunds = (); type MaxApprovals = ConstU32<64>; type WeightInfo = pallet_treasury::weights::SubstrateWeight; } parameter_types! { pub CommunityTreasuryAccountId: AccountId = CommunityTreasuryPalletId::get().into_account_truncating(); } #[derive(Default)] pub struct CommunityCouncilCallFilter; impl InstanceFilter for CommunityCouncilCallFilter { fn filter(&self, c: &RuntimeCall) -> bool { matches!( c, RuntimeCall::DappStaking(..) | RuntimeCall::System(frame_system::Call::remark { .. }) | RuntimeCall::Utility(pallet_utility::Call::batch { .. }) | RuntimeCall::Utility(pallet_utility::Call::batch_all { .. }) ) } } impl pallet_collective_proxy::Config for Runtime { type RuntimeCall = RuntimeCall; type CollectiveProxy = EnsureRootOrTwoThirdsCommunityCouncil; type ProxyAccountId = CommunityTreasuryAccountId; type CallFilter = CommunityCouncilCallFilter; type WeightInfo = pallet_collective_proxy::weights::SubstrateWeight; } parameter_types! { pub MbmServiceWeight: Weight = Perbill::from_percent(50) * RuntimeBlockWeights::get().max_block; pub ContractsCodeDeposit: RuntimeHoldReason = pallet_contracts::HoldReason::CodeUploadDepositReserve.into(); pub ContractsStorageDeposit: RuntimeHoldReason = pallet_contracts::HoldReason::StorageDepositReserve.into(); /// Foundation controlled account collecting the settled `pallet-contracts` deposits. /// `XPDSbfc3fcoVWEtPsxQXFDvWqnZgQfsxXv6MW8dd7G3GkZt` pub ContractsDepositEscrow: AccountId = AccountId::from(hex_literal::hex!( "400048a4f3672511dfcf2ddfcb34bafb80ee2f28bbec8cbe0283e90573e93474" )); } /// Multi-block migrations executed by `pallet-migrations`. /// /// Step one of decommissioning Wasm (ink!) smart contracts: settle every balance /// `pallet-contracts` still owns. pub type MultiBlockMigrationsList = ( contracts_mbm::ReleaseContractsDeposits< Runtime, ContractsCodeDeposit, ContractsStorageDeposit, ContractsDepositEscrow, contracts_mbm::weights::SubstrateWeight, >, ); impl pallet_migrations::Config for Runtime { type RuntimeEvent = RuntimeEvent; #[cfg(not(feature = "runtime-benchmarks"))] type Migrations = MultiBlockMigrationsList; // Benchmarks need mocked migrations to guarantee that they succeed. #[cfg(feature = "runtime-benchmarks")] type Migrations = pallet_migrations::mock_helpers::MockedMigrations; type CursorMaxLen = ConstU32<65_536>; type IdentifierMaxLen = ConstU32<256>; type MigrationStatusHandler = (); type FailedMigrationHandler = UnfreezeChainOnFailedMigration; type MaxServiceWeight = MbmServiceWeight; type WeightInfo = pallet_migrations::weights::SubstrateWeight; } #[cfg(feature = "runtime-benchmarks")] impl contracts_mbm::Config for Runtime { type BenchmarkHoldReason = ContractsStorageDeposit; } /// Calls that can bypass the safe-mode pallet. pub struct SafeModeWhitelistedCalls; impl Contains for SafeModeWhitelistedCalls { fn contains(call: &RuntimeCall) -> bool { match call { // System and Timestamp are required for block production RuntimeCall::System(_) | RuntimeCall::Timestamp(_) | RuntimeCall::ParachainSystem(_) | RuntimeCall::Council(_) | RuntimeCall::TechnicalCommittee(_) | RuntimeCall::Democracy( pallet_democracy::Call::external_propose_majority { .. } | pallet_democracy::Call::external_propose_default { .. } | pallet_democracy::Call::fast_track { .. } | pallet_democracy::Call::emergency_cancel { .. } | pallet_democracy::Call::cancel_referendum { .. } | pallet_democracy::Call::vote { .. } | pallet_democracy::Call::remove_vote { .. } | pallet_democracy::Call::veto_external { .. }, ) | RuntimeCall::Proxy(_) | RuntimeCall::Multisig(_) | RuntimeCall::Preimage(_) | RuntimeCall::Utility(_) | RuntimeCall::TxPause(_) | RuntimeCall::SafeMode(_) => true, #[cfg(feature = "astar-sudo")] RuntimeCall::Sudo(_) => true, _ => false, } } } /// Calls that cannot be paused by the tx-pause pallet. pub struct TxPauseWhitelistedCalls; impl frame_support::traits::Contains> for TxPauseWhitelistedCalls { fn contains(full_name: &RuntimeCallNameOf) -> bool { let pallet_name = full_name.0.as_slice(); pallet_name == b"System" || pallet_name == b"Timestamp" || pallet_name == b"ParachainSystem" || pallet_name == b"Council" || pallet_name == b"TechnicalCommittee" || pallet_name == b"TxPause" || pallet_name == b"SafeMode" || cfg!(feature = "astar-sudo") && pallet_name == b"Sudo" } } parameter_types! { // Should be sufficient for the team to react & come up with longer term solution. pub const EnterDuration: BlockNumber = 12 * HOURS; // Extension in case previous time isn't enough. pub const ExtendDuration: BlockNumber = 2 * HOURS; // Permisonless safe mode entry isn't allowed yet. pub const NoPermisionlessEntry: Option = None; pub const NoPermisionlessExtension: Option = None; } impl pallet_safe_mode::Config for Runtime { type RuntimeEvent = RuntimeEvent; type Currency = Balances; type RuntimeHoldReason = RuntimeHoldReason; type WhitelistedCalls = SafeModeWhitelistedCalls; type EnterDuration = EnterDuration; type EnterDepositAmount = NoPermisionlessEntry; type ExtendDuration = ExtendDuration; type ExtendDepositAmount = NoPermisionlessExtension; type ForceEnterOrigin = EnsureWithSuccess; type ForceExtendOrigin = EnsureWithSuccess< EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil, AccountId, ExtendDuration, >; type ForceExitOrigin = EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil; type ForceDepositOrigin = EnsureRoot; type ReleaseDelay = (); type Notify = DappStaking; type WeightInfo = pallet_safe_mode::weights::SubstrateWeight; } impl pallet_tx_pause::Config for Runtime { type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type PauseOrigin = EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil; type UnpauseOrigin = EnsureRootOrHalfTechCommitteeOrTwoThirdCouncil; type WhitelistedCalls = TxPauseWhitelistedCalls; type MaxNameLen = ConstU32<256>; type WeightInfo = pallet_tx_pause::weights::SubstrateWeight; } #[frame_support::runtime] mod runtime { #[runtime::runtime] #[runtime::derive( RuntimeCall, RuntimeEvent, RuntimeError, RuntimeOrigin, RuntimeFreezeReason, RuntimeHoldReason, RuntimeSlashReason, RuntimeLockId, RuntimeTask )] pub struct Runtime; // System support #[runtime::pallet_index(10)] pub type System = frame_system; #[runtime::pallet_index(11)] pub type Utility = pallet_utility; #[runtime::pallet_index(12)] pub type Identity = pallet_identity; #[runtime::pallet_index(13)] pub type Timestamp = pallet_timestamp; #[runtime::pallet_index(14)] pub type Multisig = pallet_multisig; #[runtime::pallet_index(15)] pub type Proxy = pallet_proxy; #[runtime::pallet_index(17)] pub type Scheduler = pallet_scheduler; // Parachain #[runtime::pallet_index(20)] pub type ParachainSystem = cumulus_pallet_parachain_system; #[runtime::pallet_index(21)] pub type ParachainInfo = parachain_info; #[runtime::pallet_index(30)] pub type TransactionPayment = pallet_transaction_payment; #[runtime::pallet_index(31)] pub type Balances = pallet_balances; #[runtime::pallet_index(32)] pub type Vesting = pallet_vesting; // Inflation needs to execute `on_initialize` as soon as possible, and `on_finalize` as late as possible. // However, we need to execute Balance genesis before Inflation genesis, otherwise we'll have zero issuance when Inflation // logic is executed. // TODO: Address this later. It would be best if Inflation was first pallet. #[runtime::pallet_index(33)] pub type Inflation = pallet_inflation; #[runtime::pallet_index(34)] pub type DappStaking = pallet_dapp_staking; #[runtime::pallet_index(36)] pub type Assets = pallet_assets; // skip 37 - price_aggregator previously // skip 38/39 - oracle and oracle_membership previously // Collator support #[runtime::pallet_index(40)] pub type Authorship = pallet_authorship; #[runtime::pallet_index(41)] pub type CollatorSelection = pallet_collator_selection; #[runtime::pallet_index(42)] pub type Session = pallet_session; #[runtime::pallet_index(43)] pub type Aura = pallet_aura; #[runtime::pallet_index(44)] pub type AuraExt = cumulus_pallet_aura_ext; // XCM helpers #[runtime::pallet_index(50)] pub type XcmpQueue = cumulus_pallet_xcmp_queue; #[runtime::pallet_index(51)] pub type PolkadotXcm = pallet_xcm; #[runtime::pallet_index(52)] pub type CumulusXcm = cumulus_pallet_xcm; #[runtime::pallet_index(54)] pub type XcAssetConfig = pallet_xc_asset_config; #[runtime::pallet_index(55)] pub type XTokens = orml_xtokens; #[runtime::pallet_index(56)] pub type MessageQueue = pallet_message_queue; // EVM #[runtime::pallet_index(60)] pub type EVM = pallet_evm; #[runtime::pallet_index(61)] pub type Ethereum = pallet_ethereum; #[runtime::pallet_index(63)] pub type DynamicEvmBaseFee = pallet_dynamic_evm_base_fee; #[runtime::pallet_index(70)] pub type Contracts = pallet_contracts; #[runtime::pallet_index(84)] pub type Preimage = pallet_preimage; // Governance #[runtime::pallet_index(100)] pub type CouncilMembership = pallet_membership; #[runtime::pallet_index(101)] pub type TechnicalCommitteeMembership = pallet_membership; #[runtime::pallet_index(102)] pub type CommunityCouncilMembership = pallet_membership; #[runtime::pallet_index(103)] pub type Council = pallet_collective; #[runtime::pallet_index(104)] pub type TechnicalCommittee = pallet_collective; #[runtime::pallet_index(105)] pub type CommunityCouncil = pallet_collective; #[runtime::pallet_index(106)] pub type Democracy = pallet_democracy; #[runtime::pallet_index(107)] pub type Treasury = pallet_treasury; #[runtime::pallet_index(108)] pub type CommunityTreasury = pallet_treasury; #[runtime::pallet_index(109)] pub type CollectiveProxy = pallet_collective_proxy; #[runtime::pallet_index(110)] pub type SafeMode = pallet_safe_mode; #[runtime::pallet_index(111)] pub type TxPause = pallet_tx_pause; #[runtime::pallet_index(120)] pub type MultiBlockMigrations = pallet_migrations; #[runtime::pallet_index(250)] #[cfg(feature = "runtime-benchmarks")] pub type ContractsMBM = contracts_mbm; #[runtime::pallet_index(99)] #[cfg(feature = "astar-sudo")] pub type Sudo = pallet_sudo + Pallet + Call + Event + Error + Config; } /// Block type as expected by this runtime. pub type Block = generic::Block; /// A Block signed with a Justification pub type SignedBlock = generic::SignedBlock; /// BlockId type as expected by this runtime. pub type BlockId = generic::BlockId; /// The SignedExtension to the basic transaction logic. pub type SignedExtra = ( frame_system::CheckSpecVersion, frame_system::CheckTxVersion, frame_system::CheckGenesis, frame_system::CheckEra, frame_system::CheckNonce, frame_system::CheckWeight, pallet_transaction_payment::ChargeTransactionPayment, frame_metadata_hash_extension::CheckMetadataHash, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = fp_self_contained::UncheckedExtrinsic; /// The payload being signed in transactions. pub type SignedPayload = generic::SignedPayload; /// Extrinsic type that has already been checked. pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic; /// Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< Runtime, Block, frame_system::ChainContext, Runtime, AllPalletsWithSystem, Migrations, >; /// All migrations that will run on the next runtime upgrade. /// /// __NOTE:__ THE ORDER IS IMPORTANT. pub type Migrations = (Unreleased, Permanent); /// Unreleased migrations. Add new ones here: pub type Unreleased = (); /// Migrations/checks that do not need to be versioned and can run on every upgrade. pub type Permanent = (pallet_xcm::migration::MigrateToLatestXcmVersion,); type EventRecord = frame_system::EventRecord< ::RuntimeEvent, ::Hash, >; impl fp_self_contained::SelfContainedCall for RuntimeCall { type SignedInfo = H160; fn is_self_contained(&self) -> bool { match self { RuntimeCall::Ethereum(call) => call.is_self_contained(), _ => false, } } fn check_self_contained(&self) -> Option> { match self { RuntimeCall::Ethereum(call) => call.check_self_contained(), _ => None, } } fn validate_self_contained( &self, info: &Self::SignedInfo, dispatch_info: &DispatchInfoOf, len: usize, ) -> Option { match self { RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len), _ => None, } } fn pre_dispatch_self_contained( &self, info: &Self::SignedInfo, dispatch_info: &DispatchInfoOf, len: usize, ) -> Option> { match self { RuntimeCall::Ethereum(call) => { call.pre_dispatch_self_contained(info, dispatch_info, len) } _ => None, } } fn apply_self_contained( self, info: Self::SignedInfo, ) -> Option>> { match self { call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => { Some(call.dispatch(RuntimeOrigin::from( pallet_ethereum::RawOrigin::EthereumTransaction(info), ))) } _ => None, } } } #[cfg(feature = "runtime-benchmarks")] mod benches { define_benchmarks!( [frame_benchmarking, BaselineBench::] [frame_system, SystemBench::] [frame_system_extensions, SystemExtensionsBench::] [pallet_assets, pallet_assets::Pallet::] [pallet_balances, Balances] [pallet_timestamp, Timestamp] [pallet_transaction_payment, TransactionPayment] [pallet_dapp_staking, DappStaking] [pallet_inflation, Inflation] [pallet_migrations, MultiBlockMigrations] [contracts_mbm, ContractsMBM] [pallet_xc_asset_config, XcAssetConfig] [pallet_collator_selection, CollatorSelection] [pallet_xcm, PalletXcmExtrinsicsBenchmark::] [pallet_dynamic_evm_base_fee, DynamicEvmBaseFee] [xcm_benchmarks_generic, XcmGeneric] [xcm_benchmarks_fungible, XcmFungible] [pallet_tx_pause, TxPause] [pallet_safe_mode, SafeMode] ); } impl_runtime_apis! { impl sp_api::Core for Runtime { fn version() -> RuntimeVersion { VERSION } fn execute_block(block: ::LazyBlock) { Executive::execute_block(block) } fn initialize_block(header: &::Header) -> sp_runtime::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_consensus_aura::AuraApi for Runtime { fn slot_duration() -> sp_consensus_aura::SlotDuration { sp_consensus_aura::SlotDuration::from_millis(SLOT_DURATION) } fn authorities() -> Vec { pallet_aura::Authorities::::get().into_inner() } } impl cumulus_primitives_aura::AuraUnincludedSegmentApi for Runtime { fn can_build_upon( included_hash: ::Hash, slot: cumulus_primitives_aura::Slot, ) -> bool { ConsensusHook::can_build_upon(included_hash, slot) } } 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: InherentData) -> Vec<::Extrinsic> { data.create_extrinsics() } fn check_inherents(block: ::LazyBlock, data: InherentData) -> 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 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< Block, Balance, > for Runtime { fn query_info(uxt: ::Extrinsic, len: u32) -> RuntimeDispatchInfo { TransactionPayment::query_info(uxt, len) } fn query_fee_details(uxt: ::Extrinsic, len: u32) -> 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 sp_session::SessionKeys for Runtime { fn generate_session_keys(seed: Option>) -> Vec { SessionKeys::generate(seed) } fn decode_session_keys( encoded: Vec, ) -> Option, sp_core::crypto::KeyTypeId)>> { SessionKeys::decode_into_raw_public_keys(&encoded) } } impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) } } impl cumulus_primitives_core::RelayParentOffsetApi for Runtime { fn relay_parent_offset() -> u32 { RelayParentOffset::get() } } impl fp_rpc::EthereumRuntimeRPCApi for Runtime { fn chain_id() -> u64 { ChainId::get() } fn account_basic(address: H160) -> pallet_evm::Account { let (account, _) = EVM::account_basic(&address); account } fn gas_price() -> U256 { let (gas_price, _) = ::FeeCalculator::min_gas_price(); gas_price } fn account_code_at(address: H160) -> Vec { pallet_evm::AccountCodes::::get(address) } fn author() -> H160 { >::find_author() } fn storage_at(address: H160, index: U256) -> H256 { let tmp: [u8; 32] = index.to_big_endian(); pallet_evm::AccountStorages::::get(address, H256::from_slice(&tmp[..])) } fn call( from: H160, to: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, estimate: bool, access_list: Option)>>, authorization_list: Option, ) -> Result { let config = if estimate { let mut config = ::config().clone(); config.estimate = true; Some(config) } else { None }; let is_transactional = false; let validate = true; // Reused approach from Moonbeam since Frontier implementation doesn't support this let mut estimated_transaction_len = data.len() + // to: 20 // from: 20 // value: 32 // gas_limit: 32 // nonce: 32 // 1 byte transaction action variant // chain id 8 bytes // 65 bytes signature 210; if max_fee_per_gas.is_some() { estimated_transaction_len += 32; } if max_priority_fee_per_gas.is_some() { estimated_transaction_len += 32; } if access_list.is_some() { estimated_transaction_len += access_list.encoded_size(); } let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let without_base_extrinsic_weight = true; let (weight_limit, proof_size_base_cost) = match ::GasWeightMapping::gas_to_weight( gas_limit, without_base_extrinsic_weight ) { weight_limit if weight_limit.proof_size() > 0 => { (Some(weight_limit), Some(estimated_transaction_len as u64)) } _ => (None, None), }; ::Runner::call( from, to, data, value, gas_limit.unique_saturated_into(), max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), authorization_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, config .as_ref() .unwrap_or_else(|| ::config()), ) .map_err(|err| err.error.into()) } fn create( from: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, estimate: bool, access_list: Option)>>, authorization_list: Option, ) -> Result { let config = if estimate { let mut config = ::config().clone(); config.estimate = true; Some(config) } else { None }; let is_transactional = false; let validate = true; // Reused approach from Moonbeam since Frontier implementation doesn't support this let mut estimated_transaction_len = data.len() + // to: 20 // from: 20 // value: 32 // gas_limit: 32 // nonce: 32 // 1 byte transaction action variant // chain id 8 bytes // 65 bytes signature 210; if max_fee_per_gas.is_some() { estimated_transaction_len += 32; } if max_priority_fee_per_gas.is_some() { estimated_transaction_len += 32; } if access_list.is_some() { estimated_transaction_len += access_list.encoded_size(); } let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let without_base_extrinsic_weight = true; let (weight_limit, proof_size_base_cost) = match ::GasWeightMapping::gas_to_weight( gas_limit, without_base_extrinsic_weight ) { weight_limit if weight_limit.proof_size() > 0 => { (Some(weight_limit), Some(estimated_transaction_len as u64)) } _ => (None, None), }; #[allow(clippy::or_fun_call)] // suggestion not helpful here ::Runner::create( from, data, value, gas_limit.unique_saturated_into(), max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), authorization_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, config .as_ref() .unwrap_or(::config()), ) .map_err(|err| err.error.into()) } fn current_transaction_statuses() -> Option> { pallet_ethereum::CurrentTransactionStatuses::::get() } fn current_block() -> Option { pallet_ethereum::CurrentBlock::::get() } fn current_receipts() -> Option> { pallet_ethereum::CurrentReceipts::::get() } fn current_all() -> ( Option, Option>, Option>, ) { ( pallet_ethereum::CurrentBlock::::get(), pallet_ethereum::CurrentReceipts::::get(), pallet_ethereum::CurrentTransactionStatuses::::get() ) } fn extrinsic_filter( xts: Vec<::Extrinsic>, ) -> Vec { xts.into_iter().filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction), _ => None }).collect::>() } fn elasticity() -> Option { Some(Permill::zero()) } fn gas_limit_multiplier_support() {} fn pending_block( xts: Vec<::Extrinsic>, ) -> (Option, Option>) { for ext in xts.into_iter() { let _ = Executive::apply_extrinsic(ext); } Ethereum::on_finalize(System::block_number() + 1); ( pallet_ethereum::CurrentBlock::::get(), pallet_ethereum::CurrentTransactionStatuses::::get() ) } fn initialize_pending_block(header: &::Header) { Executive::initialize_block(header); } } impl fp_rpc::ConvertTransactionRuntimeApi for Runtime { fn convert_transaction( transaction: pallet_ethereum::Transaction ) -> ::Extrinsic { UncheckedExtrinsic::new_bare( pallet_ethereum::Call::::transact { transaction }.into(), ) } } 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, pallet_contracts::DebugInfo::UnsafeDebug, pallet_contracts::CollectEvents::UnsafeCollect, 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, pallet_contracts::DebugInfo::UnsafeDebug, pallet_contracts::CollectEvents::UnsafeCollect, ) } 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 dapp_staking_runtime_api::DappStakingApi for Runtime { fn periods_per_cycle() -> PeriodNumber { InflationCycleConfig::periods_per_cycle() } fn eras_per_voting_subperiod() -> EraNumber { InflationCycleConfig::eras_per_voting_subperiod() } fn eras_per_build_and_earn_subperiod() -> EraNumber { InflationCycleConfig::eras_per_build_and_earn_subperiod() } fn blocks_per_era() -> BlockNumber { InflationCycleConfig::blocks_per_era() } fn get_dapp_tier_assignment() -> BTreeMap { DappStaking::get_dapp_tier_assignment() } } impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { if !matches!(xcm_version, xcm::v3::VERSION | xcm::v4::VERSION | xcm::v5::VERSION) { return Err(XcmPaymentApiError::UnhandledXcmVersion); } // Native asset is always supported let mut acceptable_assets = vec![XcmAssetId::from(xcm_config::AstarLocation::get())]; // Add foreign assets that have 'units per second' configured acceptable_assets.extend( pallet_xc_asset_config::AssetLocationUnitsPerSecond::::iter_keys().filter_map( |asset_location| match XcmLocation::try_from(asset_location) { Ok(location) => Some(XcmAssetId::from(location)), Err(_) => None, }, ), ); PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) } fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result { let asset = asset.into_version(xcm::v5::VERSION).map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?; let asset_id: XcmAssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?; // for native token if asset_id.0 == xcm_config::AstarLocation::get() { Ok(XcmWeightToFee::weight_to_fee(&weight)) } // for foreign assets with “units per second” configurations else { let versioned_location = VersionedLocation::V5(asset_id.0); match pallet_xc_asset_config::AssetLocationUnitsPerSecond::::get(versioned_location) { Some(units_per_sec) => { Ok(pallet_xc_asset_config::Pallet::::weight_to_fee(weight, units_per_sec)) } None => Err(XcmPaymentApiError::AssetNotFound), } } } fn query_xcm_weight(message: VersionedXcm<()>) -> Result { PolkadotXcm::query_xcm_weight(message) } fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>, asset_id: VersionedAssetId) -> Result { type AssetExchanger = ::AssetExchanger; PolkadotXcm::query_delivery_fees::(destination, message, asset_id) } } impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call, result_xcms_version) } fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_xcm::(origin_location, xcm) } } impl xcm_runtime_apis::trusted_query::TrustedQueryApi for Runtime { fn is_trusted_reserve(asset: VersionedAsset, location: VersionedLocation) -> Result { PolkadotXcm::is_trusted_reserve(asset, location) } fn is_trusted_teleporter(asset: VersionedAsset, location: VersionedLocation) -> Result { PolkadotXcm::is_trusted_teleporter(asset, location) } } impl sp_genesis_builder::GenesisBuilder for Runtime { fn build_state(config: Vec) -> sp_genesis_builder::Result { genesis_builder_helper::build_state::(config) } fn get_preset(id: &Option) -> Option> { genesis_builder_helper::get_preset::(id, &genesis_config::get_preset) } fn preset_names() -> Vec { vec![ sp_genesis_builder::PresetId::from("development"), ] } } #[cfg(feature = "runtime-benchmarks")] impl frame_benchmarking::Benchmark for Runtime { fn benchmark_metadata(extra: bool) -> ( Vec, Vec, ) { use frame_benchmarking::{baseline, BenchmarkList}; use frame_support::traits::StorageInfoTrait; use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; pub use frame_system_benchmarking::{ extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench }; use baseline::Pallet as BaselineBench; // This is defined once again in dispatch_benchmark, because list_benchmarks! // and add_benchmarks! are macros exported by define_benchmarks! macros and those types // are referenced in that call. type XcmFungible = astar_xcm_benchmarks::fungible::benchmarking::XcmFungibleBenchmarks::; type XcmGeneric = astar_xcm_benchmarks::generic::benchmarking::XcmGenericBenchmarks::; let mut list = Vec::::new(); list_benchmarks!(list, extra); let storage_info = AllPalletsWithSystem::storage_info(); (list, storage_info) } #[allow(non_local_definitions)] fn dispatch_benchmark( config: frame_benchmarking::BenchmarkConfig ) -> Result, alloc::string::String> { use alloc::boxed::Box; use frame_benchmarking::{baseline, BenchmarkBatch, BenchmarkError}; pub use frame_system_benchmarking::{ extensions::Pallet as SystemExtensionsBench, Pallet as SystemBench }; use frame_support::{traits::{WhitelistedStorageKeys, TrackedStorageKey, tokens::fungible::{ItemOf}}, assert_ok}; use baseline::Pallet as BaselineBench; use xcm::latest::prelude::*; use xcm_builder::MintLocation; use astar_primitives::{benchmarks::XcmBenchmarkHelper, xcm::ASSET_HUB_PARA_ID}; use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark; pub struct TestDeliveryHelper; impl xcm_builder::EnsureDelivery for TestDeliveryHelper { fn ensure_successful_delivery( origin_ref: &Location, dest: &Location, _fee_reason: xcm_executor::traits::FeeReason, ) -> (Option, Option) { use xcm_executor::traits::ConvertLocation; // This sets up the necessary infrastructure (HostConfiguration) for sending XCM messages ::ensure_successful_delivery( Some(dest.clone()) ); // Open HRMP channel for sibling parachain destinations if let Some(Parachain(para_id)) = dest.interior().first() { ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( (*para_id).into() ); } if let Some(account) = xcm_config::LocationToAccountId::convert_location(origin_ref) { // Give the account some balance to ensure delivery let balance = ExistentialDeposit::get() * 1000u128; // Give more than just ED let _ = >:: make_free_balance_be(&account.into(), balance); } (None, None) } } impl pallet_xcm::benchmarking::Config for Runtime { type DeliveryHelper = TestDeliveryHelper; fn reachable_dest() -> Option { Some(AssetHubLocation::get()) } fn teleportable_asset_and_dest() -> Option<(Asset, Location)> { None } fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> { let random_para_id = 43211234; ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( random_para_id.into() ); Some(( Asset { fun: Fungible(ExistentialDeposit::get()), id: Here.into() }, ParentThen(Parachain(random_para_id).into()).into(), )) } fn set_up_complex_asset_transfer( ) -> Option<(Assets, u32, Location, Box)> { XcmBenchmarkHelper::::set_up_complex_asset_transfer() } fn get_asset() -> Asset { Asset { id: AssetId(Here.into()), fun: Fungible(ExistentialDeposit::get()), } } } // Needed to run `set_code` and `apply_authorized_upgrade` frame_system benchmarks // https://github.com/paritytech/cumulus/pull/2766 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()); } } impl baseline::Config for Runtime {} // XCM Benchmarks impl astar_xcm_benchmarks::Config for Runtime {} impl astar_xcm_benchmarks::generic::Config for Runtime {} impl astar_xcm_benchmarks::fungible::Config for Runtime {} impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; type DeliveryHelper = TestDeliveryHelper; // destination location to be used in benchmarks fn valid_destination() -> Result { let asset_hub = AssetHubLocation::get(); assert_ok!(PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(asset_hub.clone()), xcm::v5::VERSION)); // This sets up the necessary infrastructure (HostConfiguration) for sending XCM messages ::ensure_successful_delivery( Some(asset_hub.clone()) ); // Open HRMP channel for sibling parachain destinations ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests( AssetHubParaId::get().into() ); Ok(asset_hub) } fn worst_case_holding(_depositable_count: u32) -> Assets { XcmBenchmarkHelper::::worst_case_holding() } } impl pallet_xcm_benchmarks::generic::Config for Runtime { type RuntimeCall = RuntimeCall; type TransactAsset = Balances; fn worst_case_response() -> (u64, Response) { (0u64, Response::Version(Default::default())) } fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> { Err(BenchmarkError::Skip) } fn universal_alias() -> Result<(Location, Junction), BenchmarkError> { Err(BenchmarkError::Skip) } fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> { assert_ok!(PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(Location::parent()), xcm::v5::VERSION)); Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into())) } fn subscribe_origin() -> Result { assert_ok!(PolkadotXcm::force_xcm_version(RuntimeOrigin::root(), Box::new(Location::parent()), xcm::v5::VERSION)); Ok(Location::parent()) } fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> { let origin = Location::parent(); let assets: Assets = (AssetId(Location::parent()), 1_000u128) .into(); let ticket = Location { parents: 0, interior: Here }; Ok((origin, ticket, assets)) } fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> { Err(BenchmarkError::Skip) } fn export_message_origin_and_destination( ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> { Err(BenchmarkError::Skip) } fn alias_origin() -> Result<(Location, Location), BenchmarkError> { Err(BenchmarkError::Skip) } fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> { Ok(( (AssetId(Here.into()), 1_000_000_000_000_000_000u128).into(), Limited(Weight::from_parts(5000, 5000)), )) } } parameter_types! { pub const NoCheckingAccount: Option<(AccountId, MintLocation)> = None; pub const NoTeleporter: Option<(Location, Asset)> = None; pub const TransactAssetId: u128 = 1001; pub TransactAssetLocation: Location = Location { parents: 0, interior: [GeneralIndex(TransactAssetId::get())].into() }; pub const AssetHubParaId: u32 = ASSET_HUB_PARA_ID; pub AssetHubLocation: Location = Location::new(1, [Parachain(AssetHubParaId::get())]); pub TrustedReserveLocation: Location = AssetHubLocation::get(); pub TrustedReserveAsset: Asset = Asset { id: AssetId(TrustedReserveLocation::get()), fun: Fungible(1_000_000) }; pub TrustedReserve: Option<(Location, Asset)> = Some((TrustedReserveLocation::get(), TrustedReserveAsset::get())); } impl pallet_xcm_benchmarks::fungible::Config for Runtime { type TransactAsset = ItemOf, TransactAssetId, AccountId>; type CheckedAccount = NoCheckingAccount; type TrustedTeleporter = NoTeleporter; type TrustedReserve = TrustedReserve; fn get_asset() -> Asset { let min_balance = 100u128; // create the transact asset and make it sufficient assert_ok!(pallet_assets::Pallet::::force_create( RuntimeOrigin::root(), TransactAssetId::get().into(), Address::Id([0u8; 32].into()), true, // min balance min_balance )); // convert mapping for asset id assert_ok!( XcAssetConfig::register_asset_location( RuntimeOrigin::root(), Box::new(TransactAssetLocation::get().into_versioned()), TransactAssetId::get(), ) ); Asset { id: AssetId(TransactAssetLocation::get()), fun: Fungible(min_balance * 100), } } } type XcmFungible = astar_xcm_benchmarks::fungible::benchmarking::XcmFungibleBenchmarks::; type XcmGeneric = astar_xcm_benchmarks::generic::benchmarking::XcmGenericBenchmarks::; let whitelist: Vec = 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) } } #[cfg(feature = "evm-tracing")] impl moonbeam_rpc_primitives_debug::DebugRuntimeApi for Runtime { fn trace_transaction( extrinsics: Vec<::Extrinsic>, traced_transaction: &pallet_ethereum::Transaction, header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { use moonbeam_evm_tracer::tracer::EvmTracer; // We need to follow the order when replaying the transactions. // Block initialize happens first then apply_extrinsic. Executive::initialize_block(header); // Apply the a subset of extrinsics: all the substrate-specific or ethereum // transactions that preceded the requested transaction. for ext in extrinsics.into_iter() { let _ = match &ext.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { if transaction == traced_transaction { EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); return Ok(()); } else { Executive::apply_extrinsic(ext) } } _ => Executive::apply_extrinsic(ext), }; } Err(sp_runtime::DispatchError::Other( "Failed to find Ethereum transaction among the extrinsics.", )) } fn trace_block( extrinsics: Vec<::Extrinsic>, known_transactions: Vec, header: &::Header, ) -> Result< (), sp_runtime::DispatchError, > { use moonbeam_evm_tracer::tracer::EvmTracer; // We need to follow the order when replaying the transactions. // Block initialize happens first then apply_extrinsic. Executive::initialize_block(header); // Apply all extrinsics. Ethereum extrinsics are traced. for ext in extrinsics.into_iter() { match &ext.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => { if known_transactions.contains(&transaction.hash()) { // Each known extrinsic is a new call stack. EvmTracer::emit_new(); EvmTracer::new().trace(|| Executive::apply_extrinsic(ext)); } else { let _ = Executive::apply_extrinsic(ext); } } _ => { let _ = Executive::apply_extrinsic(ext); } }; } Ok(()) } fn trace_call( header: &::Header, from: H160, to: H160, data: Vec, value: U256, gas_limit: U256, max_fee_per_gas: Option, max_priority_fee_per_gas: Option, nonce: Option, access_list: Option)>>, authorization_list: Option, ) -> Result<(), sp_runtime::DispatchError> { use moonbeam_evm_tracer::tracer::EvmTracer; // Initialize block: calls the "on_initialize" hook on every pallet // in AllPalletsWithSystem. Executive::initialize_block(header); EvmTracer::new().trace(|| { let is_transactional = false; let validate = true; let without_base_extrinsic_weight = true; // Estimated encoded transaction size must be based on the heaviest transaction // type (EIP1559Transaction) to be compatible with all transaction types. let mut estimated_transaction_len = data.len() + // pallet ethereum index: 1 // transact call index: 1 // Transaction enum variant: 1 // chain_id 8 bytes // nonce: 32 // max_priority_fee_per_gas: 32 // max_fee_per_gas: 32 // gas_limit: 32 // action: 21 (enum varianrt + call address) // value: 32 // access_list: 1 (empty vec size) // 65 bytes signature 258; if access_list.is_some() { estimated_transaction_len += access_list.encoded_size(); } let gas_limit = gas_limit.min(u64::MAX.into()).low_u64(); let (weight_limit, proof_size_base_cost) = match ::GasWeightMapping::gas_to_weight( gas_limit, without_base_extrinsic_weight ) { weight_limit if weight_limit.proof_size() > 0 => { (Some(weight_limit), Some(estimated_transaction_len as u64)) } _ => (None, None), }; let _ = ::Runner::call( from, to, data, value, gas_limit, max_fee_per_gas, max_priority_fee_per_gas, nonce, access_list.unwrap_or_default(), authorization_list.unwrap_or_default(), is_transactional, validate, weight_limit, proof_size_base_cost, ::config(), ); }); Ok(()) } } #[cfg(feature = "evm-tracing")] impl moonbeam_rpc_primitives_txpool::TxPoolRuntimeApi for Runtime { fn extrinsic_filter( xts_ready: Vec<::Extrinsic>, xts_future: Vec<::Extrinsic>, ) -> moonbeam_rpc_primitives_txpool::TxPoolResponse { moonbeam_rpc_primitives_txpool::TxPoolResponse { ready: xts_ready .into_iter() .filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction), _ => None, }) .collect(), future: xts_future .into_iter() .filter_map(|xt| match xt.0.function { RuntimeCall::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction), _ => None, }) .collect(), } } } #[cfg(feature = "try-runtime")] impl frame_try_runtime::TryRuntime for Runtime { fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { log::info!("try-runtime::on_runtime_upgrade"); let weight = Executive::try_runtime_upgrade(checks).unwrap(); (weight, RuntimeBlockWeights::get().max_block) } fn execute_block( block: ::LazyBlock, state_root_check: bool, signature_check: bool, select: frame_try_runtime::TryStateSelect ) -> Weight { log::info!( "try-runtime: executing block #{} ({:?}) / root checks: {:?} / sanity-checks: {:?}", block.header.number, block.header.hash(), state_root_check, select, ); Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed") } } } cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, }