difftreelog
Inflation pallet block provider added. Setted up to relay chain.
in: master
3 files changed
pallets/inflation/src/lib.rsdiffbeforeafterboth--- a/pallets/inflation/src/lib.rs
+++ b/pallets/inflation/src/lib.rs
@@ -36,7 +36,7 @@
use sp_runtime::{
Perbill,
- traits::{Zero},
+ traits::{BlockNumberProvider, Zero},
};
use sp_std::convert::TryInto;
@@ -56,6 +56,9 @@
type Currency: Currency<Self::AccountId>;
type TreasuryAccountId: Get<Self::AccountId>;
type InflationBlockInterval: Get<Self::BlockNumber>;
+
+ // The block number provider
+ type BlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;
}
decl_storage! {
@@ -75,7 +78,7 @@
{
const InflationBlockInterval: T::BlockNumber = T::InflationBlockInterval::get();
- fn on_initialize(now: T::BlockNumber) -> Weight
+ fn on_initialize() -> Weight
{
let mut consumed_weight = 0;
let mut add_weight = |reads, writes, weight| {
@@ -84,13 +87,11 @@
};
let block_interval: u32 = T::InflationBlockInterval::get().try_into().unwrap_or(0);
-
- // TODO: Rewrite inflation to use block timestamp instead of block number
- // let _now = <timestamp::Module<T>>::get();
+ let _now = T::BlockNumberProvider::current_block_number();
// Recalculate inflation on the first block of the year (or if it is not initialized yet)
- if (now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {
- let current_year: u32 = (now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);
+ if (_now % T::BlockNumber::from(YEAR)).is_zero() || <BlockInflation<T>>::get().is_zero() {
+ let current_year: u32 = (_now / T::BlockNumber::from(YEAR)).try_into().unwrap_or(0);
let one_percent = Perbill::from_percent(1);
@@ -117,7 +118,7 @@
}
// Apply inflation every InflationBlockInterval blocks and in the 1st block to initialize Treasury account
- else if (now % T::BlockNumber::from(block_interval)).is_zero() {
+ else if (_now % T::BlockNumber::from(block_interval)).is_zero() {
T::Currency::deposit_into_existing(&T::TreasuryAccountId::get(), <BlockInflation<T>>::get()).ok();
add_weight(3, 2, 12_900_000);
pallets/inflation/src/tests.rsdiffbeforeafterboth--- a/pallets/inflation/src/tests.rs
+++ b/pallets/inflation/src/tests.rs
@@ -11,7 +11,7 @@
};
use sp_core::H256;
use sp_runtime::{
- traits::{BlakeTwo256, IdentityLookup},
+ traits::{BlakeTwo256, BlockNumberProvider, IdentityLookup},
testing::Header,
};
@@ -85,12 +85,22 @@
parameter_types! {
pub TreasuryAccountId: u64 = 1234;
pub const InflationBlockInterval: u32 = 100; // every time per how many blocks inflation is applied
+ pub static MockBlockNumberProvider: u64 = 0;
}
+impl BlockNumberProvider for MockBlockNumberProvider {
+ type BlockNumber = u64;
+
+ fn current_block_number() -> Self::BlockNumber {
+ Self::get()
+ }
+}
+
impl pallet_inflation::Config for Test {
type Currency = Balances;
type TreasuryAccountId = TreasuryAccountId;
type InflationBlockInterval = InflationBlockInterval;
+ type BlockNumberProvider = MockBlockNumberProvider;
}
pub fn new_test_ext() -> sp_io::TestExternalities {
@@ -110,7 +120,8 @@
// BlockInflation should be set after 1st block and
// first inflation deposit should be equal to BlockInflation
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Expected 100-block inflation for year 1 is 100 * 100_000_000 / YEAR = 3803
assert_eq!(Inflation::block_inflation(), 3803);
@@ -128,20 +139,23 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Next inflation deposit happens when block is multiple of InflationBlockInterval
let mut block: u32 = 2;
let balance_before: u64 = Balances::free_balance(1234);
while block % InflationBlockInterval::get() != 0 {
- Inflation::on_initialize(block as u64);
+ MockBlockNumberProvider::set(block as u64);
+ Inflation::on_initialize(0);
block += 1;
}
let balance_just_before: u64 = Balances::free_balance(1234);
assert_eq!(balance_before, balance_just_before);
// The block with inflation
- Inflation::on_initialize(block as u64);
+ MockBlockNumberProvider::set(block as u64);
+ Inflation::on_initialize(0);
let balance_after: u64 = Balances::free_balance(1234);
assert_eq!(
balance_after - balance_just_before,
@@ -157,19 +171,22 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
// Go through all the block inflations for year 1,
// total issuance will be updated accordingly
for block in (100..YEAR).step_by(100) {
- Inflation::on_initialize(block);
+ MockBlockNumberProvider::set(block);
+ Inflation::on_initialize(0);
}
assert_eq!(
initial_issuance + (3803 * (YEAR / 100)),
<Balances as Currency<_>>::total_issuance()
);
- Inflation::on_initialize(YEAR);
+ MockBlockNumberProvider::set(YEAR);
+ Inflation::on_initialize(0);
let block_inflation_year_1 = Inflation::block_inflation();
// Expected 100-block inflation for year 2: 100 * 9.33% * initial issuance * 110% / YEAR = 3904
assert_eq!(block_inflation_year_1, 3904);
@@ -181,13 +198,16 @@
new_test_ext().execute_with(|| {
// Total issuance = 1_000_000_000
let initial_issuance: u64 = 1_000_000_000;
+
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(1);
+ MockBlockNumberProvider::set(1);
+ Inflation::on_initialize(0);
for year in 1..=9 {
let block_inflation_year_before = Inflation::block_inflation();
- Inflation::on_initialize(YEAR * year);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let block_inflation_year_after = Inflation::block_inflation();
// SBP M2 review: this is actually not true (not for the first few years)
@@ -204,11 +224,13 @@
let initial_issuance: u64 = 1_000_000_000;
let _ = <Balances as Currency<_>>::deposit_creating(&1234, initial_issuance);
assert_eq!(Balances::free_balance(1234), initial_issuance);
- Inflation::on_initialize(YEAR * 9);
+ MockBlockNumberProvider::set(YEAR * 9);
+ Inflation::on_initialize(0);
for year in 10..=20 {
let block_inflation_year_before = Inflation::block_inflation();
- Inflation::on_initialize(YEAR * year);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let block_inflation_year_after = Inflation::block_inflation();
// Assert that next year inflation is equal to previous year inflation
@@ -233,22 +255,26 @@
for year in 0..=10 {
// Year first block
- Inflation::on_initialize(year * YEAR);
+ MockBlockNumberProvider::set(YEAR * year);
+ Inflation::on_initialize(0);
let mut actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year second block
- Inflation::on_initialize(year * YEAR + 1);
+ MockBlockNumberProvider::set(YEAR * year + 1);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year middle block
- Inflation::on_initialize(year * YEAR + YEAR / 2);
+ MockBlockNumberProvider::set(year * YEAR + YEAR / 2);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
// Year last block
- Inflation::on_initialize((year + 1) * YEAR - 1);
+ MockBlockNumberProvider::set((year + 1) * YEAR - 1);
+ Inflation::on_initialize(0);
actual_payout = Inflation::block_inflation();
assert_eq!(actual_payout, payout_by_year[year as usize]);
}
runtime/src/lib.rsdiffbeforeafterboth1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,26 },27 transaction_validity::{TransactionSource, TransactionValidity},28 ApplyExtrinsicResult, MultiSignature,29};3031use sp_std::prelude::*;3233#[cfg(feature = "std")]34use sp_version::NativeVersion;35use sp_version::RuntimeVersion;36pub use pallet_transaction_payment::{37 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,38};39// A few exports that help ease life for downstream crates.40pub use pallet_balances::Call as BalancesCall;41pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};42pub use frame_support::{43 construct_runtime, match_type,44 dispatch::DispatchResult,45 PalletId, parameter_types, StorageValue, ConsensusEngineId,46 traits::{47 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,48 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,49 },50 weights::{51 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,54 },55};56use up_data_structs::*;57// use pallet_contracts::weights::WeightInfo;58// #[cfg(any(feature = "std", test))]59use frame_system::{60 self as system, EnsureRoot, EnsureSigned,61 limits::{BlockWeights, BlockLength},62};63use sp_arithmetic::{64 traits::{BaseArithmetic, Unsigned},65};66use smallvec::smallvec;67use codec::{Encode, Decode};68use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use fp_rpc::TransactionStatus;70use sp_core::crypto::Public;71use sp_runtime::{72 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},73 transaction_validity::TransactionValidityError,74};7576// pub use pallet_timestamp::Call as TimestampCall;77pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7879// Polkadot imports80use pallet_xcm::XcmPassthrough;81use polkadot_parachain::primitives::Sibling;82use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};83use xcm_builder::{84 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};9192// mod chain_extension;93// use crate::chain_extension::{NFTExtension, Imbalance};9495/// An index to a block.96pub type BlockNumber = u32;9798/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.99pub type Signature = MultiSignature;100101/// Some way of identifying an account on the chain. We intentionally make it equivalent102/// to the public key of our transaction signing scheme.103pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104105pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know124/// the specifics of the runtime. They can then be made to be agnostic over specific formats125/// of data like extrinsics, allowing for them to continue syncing the network through upgrades126/// to even the core data structures.127pub mod opaque {128 use super::*;129130 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;131132 /// Opaque block type.133 pub type Block = generic::Block<Header, UncheckedExtrinsic>;134135 pub type SessionHandlers = ();136137 impl_opaque_keys! {138 pub struct SessionKeys {139 pub aura: Aura,140 }141 }142}143144/// This runtime version.145pub const VERSION: RuntimeVersion = RuntimeVersion {146 spec_name: create_runtime_str!("opal"),147 impl_name: create_runtime_str!("opal"),148 authoring_version: 1,149 spec_version: 912204,150 impl_version: 1,151 apis: RUNTIME_API_VERSIONS,152 transaction_version: 1,153};154155pub const MILLISECS_PER_BLOCK: u64 = 12000;156157pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;158159// These time units are defined in number of blocks.160pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);161pub const HOURS: BlockNumber = MINUTES * 60;162pub const DAYS: BlockNumber = HOURS * 24;163164parameter_types! {165 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;166}167168#[derive(codec::Encode, codec::Decode)]169pub enum XCMPMessage<XAccountId, XBalance> {170 /// Transfer tokens to the given account from the Parachain account.171 TransferToken(XAccountId, XBalance),172}173174/// The version information used to identify this runtime when compiled natively.175#[cfg(feature = "std")]176pub fn native_version() -> NativeVersion {177 NativeVersion {178 runtime_version: VERSION,179 can_author_with: Default::default(),180 }181}182183type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;184185pub struct DealWithFees;186impl OnUnbalanced<NegativeImbalance> for DealWithFees {187 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {188 if let Some(fees) = fees_then_tips.next() {189 // for fees, 100% to treasury190 let mut split = fees.ration(100, 0);191 if let Some(tips) = fees_then_tips.next() {192 // for tips, if any, 100% to treasury193 tips.ration_merge_into(100, 0, &mut split);194 }195 Treasury::on_unbalanced(split.0);196 // Author::on_unbalanced(split.1);197 }198 }199}200201/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.202/// This is used to limit the maximal weight of a single extrinsic.203const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);204/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used205/// by Operational extrinsics.206const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);207/// We allow for 2 seconds of compute with a 6 second average block time.208const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;209210parameter_types! {211 pub const BlockHashCount: BlockNumber = 2400;212 pub RuntimeBlockLength: BlockLength =213 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);214 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);215 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;216 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()217 .base_block(BlockExecutionWeight::get())218 .for_class(DispatchClass::all(), |weights| {219 weights.base_extrinsic = ExtrinsicBaseWeight::get();220 })221 .for_class(DispatchClass::Normal, |weights| {222 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);223 })224 .for_class(DispatchClass::Operational, |weights| {225 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);226 // Operational transactions have some extra reserved space, so that they227 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.228 weights.reserved = Some(229 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT230 );231 })232 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)233 .build_or_panic();234 pub const Version: RuntimeVersion = VERSION;235 pub const SS58Prefix: u8 = 42;236}237238parameter_types! {239 pub const ChainId: u64 = 8888;240}241242pub struct FixedFee;243impl FeeCalculator for FixedFee {244 fn min_gas_price() -> U256 {245 1.into()246 }247}248249impl pallet_evm::Config for Runtime {250 type BlockGasLimit = BlockGasLimit;251 type FeeCalculator = FixedFee;252 type GasWeightMapping = ();253 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;254 type CallOrigin = EnsureAddressTruncated;255 type WithdrawOrigin = EnsureAddressTruncated;256 type AddressMapping = HashedAddressMapping<Self::Hashing>;257 type Precompiles = ();258 type Currency = Balances;259 type Event = Event;260 type OnMethodCall = (261 pallet_evm_migration::OnMethodCall<Self>,262 pallet_unique::UniqueErcSupport<Self>,263 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,264 );265 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;266 type ChainId = ChainId;267 type Runner = pallet_evm::runner::stack::Runner<Self>;268 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;269 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;270 type FindAuthor = EthereumFindAuthor<Aura>;271}272273impl pallet_evm_migration::Config for Runtime {274 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;275}276277pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);278impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {279 fn find_author<'a, I>(digests: I) -> Option<H160>280 where281 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,282 {283 if let Some(author_index) = F::find_author(digests) {284 let authority_id = Aura::authorities()[author_index as usize].clone();285 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));286 }287 None288 }289}290291parameter_types! {292 pub BlockGasLimit: U256 = U256::from(u32::max_value());293}294295impl pallet_ethereum::Config for Runtime {296 type Event = Event;297 type StateRoot = pallet_ethereum::IntermediateStateRoot;298 type EvmSubmitLog = pallet_evm::Pallet<Self>;299}300301impl pallet_randomness_collective_flip::Config for Runtime {}302303impl system::Config for Runtime {304 /// The data to be stored in an account.305 type AccountData = pallet_balances::AccountData<Balance>;306 /// The identifier used to distinguish between accounts.307 type AccountId = AccountId;308 /// The basic call filter to use in dispatchable.309 type BaseCallFilter = Everything;310 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).311 type BlockHashCount = BlockHashCount;312 /// The maximum length of a block (in bytes).313 type BlockLength = RuntimeBlockLength;314 /// The index type for blocks.315 type BlockNumber = BlockNumber;316 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.317 type BlockWeights = RuntimeBlockWeights;318 /// The aggregated dispatch type that is available for extrinsics.319 type Call = Call;320 /// The weight of database operations that the runtime can invoke.321 type DbWeight = RocksDbWeight;322 /// The ubiquitous event type.323 type Event = Event;324 /// The type for hashing blocks and tries.325 type Hash = Hash;326 /// The hashing algorithm used.327 type Hashing = BlakeTwo256;328 /// The header type.329 type Header = generic::Header<BlockNumber, BlakeTwo256>;330 /// The index type for storing how many extrinsics an account has signed.331 type Index = Index;332 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.333 type Lookup = AccountIdLookup<AccountId, ()>;334 /// What to do if an account is fully reaped from the system.335 type OnKilledAccount = ();336 /// What to do if a new account is created.337 type OnNewAccount = ();338 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;339 /// The ubiquitous origin type.340 type Origin = Origin;341 /// This type is being generated by `construct_runtime!`.342 type PalletInfo = PalletInfo;343 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.344 type SS58Prefix = SS58Prefix;345 /// Weight information for the extrinsics of this pallet.346 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;347 /// Version of the runtime.348 type Version = Version;349}350351parameter_types! {352 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;353}354355impl pallet_timestamp::Config for Runtime {356 /// A timestamp: milliseconds since the unix epoch.357 type Moment = u64;358 type OnTimestampSet = ();359 type MinimumPeriod = MinimumPeriod;360 type WeightInfo = ();361}362363parameter_types! {364 // pub const ExistentialDeposit: u128 = 500;365 pub const ExistentialDeposit: u128 = 0;366 pub const MaxLocks: u32 = 50;367}368369impl pallet_balances::Config for Runtime {370 type MaxLocks = MaxLocks;371 type MaxReserves = ();372 type ReserveIdentifier = [u8; 8];373 /// The type for recording an account's balance.374 type Balance = Balance;375 /// The ubiquitous event type.376 type Event = Event;377 type DustRemoval = Treasury;378 type ExistentialDeposit = ExistentialDeposit;379 type AccountStore = System;380 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;381}382383pub const MICROUNIQUE: Balance = 1_000_000_000;384pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;385pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;386pub const UNIQUE: Balance = 100 * CENTIUNIQUE;387388pub const fn deposit(items: u32, bytes: u32) -> Balance {389 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE390}391392/*393parameter_types! {394 pub TombstoneDeposit: Balance = deposit(395 1,396 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,397 );398 pub DepositPerContract: Balance = TombstoneDeposit::get();399 pub const DepositPerStorageByte: Balance = deposit(0, 1);400 pub const DepositPerStorageItem: Balance = deposit(1, 0);401 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);402 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;403 pub const SignedClaimHandicap: u32 = 2;404 pub const MaxDepth: u32 = 32;405 pub const MaxValueSize: u32 = 16 * 1024;406 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb407 // The lazy deletion runs inside on_initialize.408 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *409 RuntimeBlockWeights::get().max_block;410 // The weight needed for decoding the queue should be less or equal than a fifth411 // of the overall weight dedicated to the lazy deletion.412 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (413 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)415 )) / 5) as u32;416 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();417}418419impl pallet_contracts::Config for Runtime {420 type Time = Timestamp;421 type Randomness = RandomnessCollectiveFlip;422 type Currency = Balances;423 type Event = Event;424 type RentPayment = ();425 type SignedClaimHandicap = SignedClaimHandicap;426 type TombstoneDeposit = TombstoneDeposit;427 type DepositPerContract = DepositPerContract;428 type DepositPerStorageByte = DepositPerStorageByte;429 type DepositPerStorageItem = DepositPerStorageItem;430 type RentFraction = RentFraction;431 type SurchargeReward = SurchargeReward;432 type WeightPrice = pallet_transaction_payment::Pallet<Self>;433 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;434 type ChainExtension = NFTExtension;435 type DeletionQueueDepth = DeletionQueueDepth;436 type DeletionWeightLimit = DeletionWeightLimit;437 type Schedule = Schedule;438 type CallStack = [pallet_contracts::Frame<Self>; 31];439}440*/441442parameter_types! {443 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer444 /// This value increases the priority of `Operational` transactions by adding445 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.446 pub const OperationalFeeMultiplier: u8 = 5;447}448449/// Linear implementor of `WeightToFeePolynomial`450pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);451452impl<T> WeightToFeePolynomial for LinearFee<T>453where454 T: BaseArithmetic + From<u32> + Copy + Unsigned,455{456 type Balance = T;457458 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {459 smallvec!(WeightToFeeCoefficient {460 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer461 coeff_frac: Perbill::zero(),462 negative: false,463 degree: 1,464 })465 }466}467468impl pallet_transaction_payment::Config for Runtime {469 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;470 type TransactionByteFee = TransactionByteFee;471 type OperationalFeeMultiplier = OperationalFeeMultiplier;472 type WeightToFee = LinearFee<Balance>;473 type FeeMultiplierUpdate = ();474}475476parameter_types! {477 pub const ProposalBond: Permill = Permill::from_percent(5);478 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;479 pub const SpendPeriod: BlockNumber = 5 * MINUTES;480 pub const Burn: Permill = Permill::from_percent(0);481 pub const TipCountdown: BlockNumber = 1 * DAYS;482 pub const TipFindersFee: Percent = Percent::from_percent(20);483 pub const TipReportDepositBase: Balance = 1 * UNIQUE;484 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;485 pub const BountyDepositBase: Balance = 1 * UNIQUE;486 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;487 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");488 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;489 pub const MaximumReasonLength: u32 = 16384;490 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);491 pub const BountyValueMinimum: Balance = 5 * UNIQUE;492 pub const MaxApprovals: u32 = 100;493}494495impl pallet_treasury::Config for Runtime {496 type PalletId = TreasuryModuleId;497 type Currency = Balances;498 type ApproveOrigin = EnsureRoot<AccountId>;499 type RejectOrigin = EnsureRoot<AccountId>;500 type Event = Event;501 type OnSlash = ();502 type ProposalBond = ProposalBond;503 type ProposalBondMinimum = ProposalBondMinimum;504 type SpendPeriod = SpendPeriod;505 type Burn = Burn;506 type BurnDestination = ();507 type SpendFunds = ();508 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;509 type MaxApprovals = MaxApprovals;510}511512impl pallet_sudo::Config for Runtime {513 type Event = Event;514 type Call = Call;515}516517pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);518519impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider520 for RelayChainBlockNumberProvider<T>521{522 type BlockNumber = BlockNumber;523524 fn current_block_number() -> Self::BlockNumber {525 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()526 .map(|d| d.relay_parent_number)527 .unwrap_or_default()528 }529}530531parameter_types! {532 pub const MinVestedTransfer: Balance = 10 * UNIQUE;533 pub const MaxVestingSchedules: u32 = 28;534}535536impl orml_vesting::Config for Runtime {537 type Event = Event;538 type Currency = pallet_balances::Pallet<Runtime>;539 type MinVestedTransfer = MinVestedTransfer;540 type VestedTransferOrigin = EnsureSigned<AccountId>;541 type WeightInfo = ();542 type MaxVestingSchedules = MaxVestingSchedules;543 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;544}545546parameter_types! {547 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;548 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;549}550551impl cumulus_pallet_parachain_system::Config for Runtime {552 type Event = Event;553 type OnValidationData = ();554 type SelfParaId = parachain_info::Pallet<Self>;555 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<556 // MaxDownwardMessageWeight,557 // XcmExecutor<XcmConfig>,558 // Call,559 // >;560 type OutboundXcmpMessageSource = XcmpQueue;561 type DmpMessageHandler = DmpQueue;562 type ReservedDmpWeight = ReservedDmpWeight;563 type ReservedXcmpWeight = ReservedXcmpWeight;564 type XcmpMessageHandler = XcmpQueue;565}566567impl parachain_info::Config for Runtime {}568569impl cumulus_pallet_aura_ext::Config for Runtime {}570571parameter_types! {572 pub const RelayLocation: MultiLocation = MultiLocation::parent();573 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;574 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();575 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();576}577578/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used579/// when determining ownership of accounts for asset transacting and when attempting to use XCM580/// `Transact` in order to determine the dispatch Origin.581pub type LocationToAccountId = (582 // The parent (Relay-chain) origin converts to the default `AccountId`.583 ParentIsDefault<AccountId>,584 // Sibling parachain origins convert to AccountId via the `ParaId::into`.585 SiblingParachainConvertsVia<Sibling, AccountId>,586 // Straight up local `AccountId32` origins just alias directly to `AccountId`.587 AccountId32Aliases<RelayNetwork, AccountId>,588);589590/// Means for transacting assets on this chain.591pub type LocalAssetTransactor = CurrencyAdapter<592 // Use this currency:593 Balances,594 // Use this currency when it is a fungible asset matching the given location or name:595 IsConcrete<RelayLocation>,596 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:597 LocationToAccountId,598 // Our chain's account ID type (we can't get away without mentioning it explicitly):599 AccountId,600 // We don't track any teleports.601 (),602>;603604/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,605/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can606/// biases the kind of local `Origin` it will become.607pub type XcmOriginToTransactDispatchOrigin = (608 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location609 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for610 // foreign chains who want to have a local sovereign account on this chain which they control.611 SovereignSignedViaLocation<LocationToAccountId, Origin>,612 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when613 // recognised.614 RelayChainAsNative<RelayOrigin, Origin>,615 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when616 // recognised.617 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,618 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a619 // transaction from the Root origin.620 ParentAsSuperuser<Origin>,621 // Native signed account converter; this just converts an `AccountId32` origin into a normal622 // `Origin::Signed` origin of the same 32-byte value.623 SignedAccountId32AsNative<RelayNetwork, Origin>,624 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.625 XcmPassthrough<Origin>,626);627628parameter_types! {629 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.630 pub UnitWeightCost: Weight = 1_000_000;631 // 1200 UNIQUEs buy 1 second of weight.632 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);633 pub const MaxInstructions: u32 = 100;634 pub const MaxAuthorities: u32 = 100_000;635}636637match_type! {638 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {639 MultiLocation { parents: 1, interior: Here } |640 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }641 };642}643644pub type Barrier = (645 TakeWeightCredit,646 AllowTopLevelPaidExecutionFrom<Everything>,647 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,648 // ^^^ Parent & its unit plurality gets free execution649);650651pub struct XcmConfig;652impl Config for XcmConfig {653 type Call = Call;654 type XcmSender = XcmRouter;655 // How to withdraw and deposit an asset.656 type AssetTransactor = LocalAssetTransactor;657 type OriginConverter = XcmOriginToTransactDispatchOrigin;658 type IsReserve = NativeAsset;659 type IsTeleporter = (); // Teleportation is disabled660 type LocationInverter = LocationInverter<Ancestry>;661 type Barrier = Barrier;662 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;663 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;664 type ResponseHandler = (); // Don't handle responses for now.665 type SubscriptionService = PolkadotXcm;666667 type AssetTrap = PolkadotXcm;668 type AssetClaims = PolkadotXcm;669}670671// parameter_types! {672// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;673// }674675/// No local origins on this chain are allowed to dispatch XCM sends/executions.676pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);677678/// The means for routing XCM messages which are not for local execution into the right message679/// queues.680pub type XcmRouter = (681 // Two routers - use UMP to communicate with the relay chain:682 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,683 // ..and XCMP to communicate with the sibling chains.684 XcmpQueue,685);686687impl pallet_evm_coder_substrate::Config for Runtime {688 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;689}690691impl pallet_xcm::Config for Runtime {692 type Event = Event;693 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;694 type XcmRouter = XcmRouter;695 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;696 type XcmExecuteFilter = Everything;697 type XcmExecutor = XcmExecutor<XcmConfig>;698 type XcmTeleportFilter = Everything;699 type XcmReserveTransferFilter = Everything;700 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;701 type LocationInverter = LocationInverter<Ancestry>;702 type Origin = Origin;703 type Call = Call;704 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;705 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;706}707708impl cumulus_pallet_xcm::Config for Runtime {709 type Event = Event;710 type XcmExecutor = XcmExecutor<XcmConfig>;711}712713impl cumulus_pallet_xcmp_queue::Config for Runtime {714 type Event = Event;715 type XcmExecutor = XcmExecutor<XcmConfig>;716 type ChannelInfo = ParachainSystem;717 type VersionWrapper = ();718}719720impl cumulus_pallet_dmp_queue::Config for Runtime {721 type Event = Event;722 type XcmExecutor = XcmExecutor<XcmConfig>;723 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;724}725726impl pallet_aura::Config for Runtime {727 type AuthorityId = AuraId;728 type DisabledValidators = ();729 type MaxAuthorities = MaxAuthorities;730}731732parameter_types! {733 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();734 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;735}736737impl pallet_common::Config for Runtime {738 type Event = Event;739 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;740 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;741 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;742743 type Currency = Balances;744 type CollectionCreationPrice = CollectionCreationPrice;745 type TreasuryAccountId = TreasuryAccountId;746}747748impl pallet_fungible::Config for Runtime {749 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;750}751impl pallet_refungible::Config for Runtime {752 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;753}754impl pallet_nonfungible::Config for Runtime {755 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;756}757758impl pallet_unique::Config for Runtime {759 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;760}761762parameter_types! {763 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied764}765766/// Used for the pallet inflation767impl pallet_inflation::Config for Runtime {768 type Currency = Balances;769 type TreasuryAccountId = TreasuryAccountId;770 type InflationBlockInterval = InflationBlockInterval;771}772773// parameter_types! {774// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *775// RuntimeBlockWeights::get().max_block;776// pub const MaxScheduledPerBlock: u32 = 50;777// }778779type EvmSponsorshipHandler = (780 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,781 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,782);783type SponsorshipHandler = (784 pallet_unique::UniqueSponsorshipHandler<Runtime>,785 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,786 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,787);788789// impl pallet_unq_scheduler::Config for Runtime {790// type Event = Event;791// type Origin = Origin;792// type PalletsOrigin = OriginCaller;793// type Call = Call;794// type MaximumWeight = MaximumSchedulerWeight;795// type ScheduleOrigin = EnsureSigned<AccountId>;796// type MaxScheduledPerBlock = MaxScheduledPerBlock;797// type SponsorshipHandler = SponsorshipHandler;798// type WeightInfo = ();799// }800801impl pallet_evm_transaction_payment::Config for Runtime {802 type EvmSponsorshipHandler = EvmSponsorshipHandler;803 type Currency = Balances;804 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;805 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;806}807808impl pallet_charge_transaction::Config for Runtime {809 type SponsorshipHandler = SponsorshipHandler;810}811812// impl pallet_contract_helpers::Config for Runtime {813// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;814// }815816parameter_types! {817 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049818 pub const HelpersContractAddress: H160 = H160([819 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,820 ]);821}822823impl pallet_evm_contract_helpers::Config for Runtime {824 type ContractAddress = HelpersContractAddress;825 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;826}827828construct_runtime!(829 pub enum Runtime where830 Block = Block,831 NodeBlock = opaque::Block,832 UncheckedExtrinsic = UncheckedExtrinsic833 {834 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,835 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,836837 Aura: pallet_aura::{Pallet, Config<T>} = 22,838 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,839840 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,841 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,842 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,843 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,844 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,845 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,846 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,847 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,848 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,849 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,850851 // XCM helpers.852 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,853 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,854 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,855 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,856857 // Unique Pallets858 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,859 Unique: pallet_unique::{Pallet, Call, Storage} = 61,860 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,861 // free = 63862 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,863 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,864 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,865 Fungible: pallet_fungible::{Pallet, Storage} = 67,866 Refungible: pallet_refungible::{Pallet, Storage} = 68,867 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,868869 // Frontier870 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,871 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,872873 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,874 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,875 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,876 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,877 }878);879880pub struct TransactionConverter;881882impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {883 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {884 UncheckedExtrinsic::new_unsigned(885 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),886 )887 }888}889890impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {891 fn convert_transaction(892 &self,893 transaction: pallet_ethereum::Transaction,894 ) -> opaque::UncheckedExtrinsic {895 let extrinsic = UncheckedExtrinsic::new_unsigned(896 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),897 );898 let encoded = extrinsic.encode();899 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])900 .expect("Encoded extrinsic is always valid")901 }902}903904/// The address format for describing accounts.905pub type Address = sp_runtime::MultiAddress<AccountId, ()>;906/// Block header type as expected by this runtime.907pub type Header = generic::Header<BlockNumber, BlakeTwo256>;908/// Block type as expected by this runtime.909pub type Block = generic::Block<Header, UncheckedExtrinsic>;910/// A Block signed with a Justification911pub type SignedBlock = generic::SignedBlock<Block>;912/// BlockId type as expected by this runtime.913pub type BlockId = generic::BlockId<Block>;914/// The SignedExtension to the basic transaction logic.915pub type SignedExtra = (916 system::CheckSpecVersion<Runtime>,917 // system::CheckTxVersion<Runtime>,918 system::CheckGenesis<Runtime>,919 system::CheckEra<Runtime>,920 system::CheckNonce<Runtime>,921 system::CheckWeight<Runtime>,922 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,923 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,924);925/// Unchecked extrinsic type as expected by this runtime.926pub type UncheckedExtrinsic =927 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;928/// Extrinsic type that has already been checked.929pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;930/// Executive: handles dispatch to the various modules.931pub type Executive = frame_executive::Executive<932 Runtime,933 Block,934 frame_system::ChainContext<Runtime>,935 Runtime,936 AllPallets,937>;938939impl_opaque_keys! {940 pub struct SessionKeys {941 pub aura: Aura,942 }943}944945impl fp_self_contained::SelfContainedCall for Call {946 type SignedInfo = H160;947948 fn is_self_contained(&self) -> bool {949 match self {950 Call::Ethereum(call) => call.is_self_contained(),951 _ => false,952 }953 }954955 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {956 match self {957 Call::Ethereum(call) => call.check_self_contained(),958 _ => None,959 }960 }961962 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {963 match self {964 Call::Ethereum(call) => call.validate_self_contained(info),965 _ => None,966 }967 }968969 fn pre_dispatch_self_contained(970 &self,971 info: &Self::SignedInfo,972 ) -> Option<Result<(), TransactionValidityError>> {973 match self {974 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),975 _ => None,976 }977 }978979 fn apply_self_contained(980 self,981 info: Self::SignedInfo,982 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {983 match self {984 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(985 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),986 )),987 _ => None,988 }989 }990}991992macro_rules! dispatch_unique_runtime {993 ($collection:ident.$method:ident($($name:ident),*)) => {{994 use pallet_unique::dispatch::Dispatched;995996 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());997 let dispatch = collection.as_dyn();998999 dispatch.$method($($name),*)1000 }};1001}1002impl_runtime_apis! {1003 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1004 for Runtime1005 {1006 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1007 dispatch_unique_runtime!(collection.account_tokens(account))1008 }1009 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1010 dispatch_unique_runtime!(collection.token_exists(token))1011 }10121013 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1014 dispatch_unique_runtime!(collection.token_owner(token))1015 }1016 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1017 dispatch_unique_runtime!(collection.const_metadata(token))1018 }1019 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1020 dispatch_unique_runtime!(collection.variable_metadata(token))1021 }10221023 fn collection_tokens(collection: CollectionId) -> u32 {1024 dispatch_unique_runtime!(collection.collection_tokens())1025 }1026 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1027 dispatch_unique_runtime!(collection.account_balance(account))1028 }1029 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1030 dispatch_unique_runtime!(collection.balance(account, token))1031 }1032 fn allowance(1033 collection: CollectionId,1034 sender: CrossAccountId,1035 spender: CrossAccountId,1036 token: TokenId,1037 ) -> u128 {1038 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1039 }10401041 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1042 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1043 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1044 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1045 }1046 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1047 <pallet_common::Pallet<Runtime>>::adminlist(collection)1048 }1049 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1050 <pallet_common::Pallet<Runtime>>::allowlist(collection)1051 }1052 fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {1053 <pallet_common::Pallet<Runtime>>::allowed(collection, user)1054 }1055 fn last_token_id(collection: CollectionId) -> TokenId {1056 dispatch_unique_runtime!(collection.last_token_id())1057 }1058 fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {1059 <pallet_common::CollectionById<Runtime>>::get(collection)1060 }1061 fn collection_stats() -> CollectionStats {1062 <pallet_common::Pallet<Runtime>>::collection_stats()1063 }1064 }10651066 impl sp_api::Core<Block> for Runtime {1067 fn version() -> RuntimeVersion {1068 VERSION1069 }10701071 fn execute_block(block: Block) {1072 Executive::execute_block(block)1073 }10741075 fn initialize_block(header: &<Block as BlockT>::Header) {1076 Executive::initialize_block(header)1077 }1078 }10791080 impl sp_api::Metadata<Block> for Runtime {1081 fn metadata() -> OpaqueMetadata {1082 OpaqueMetadata::new(Runtime::metadata().into())1083 }1084 }10851086 impl sp_block_builder::BlockBuilder<Block> for Runtime {1087 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1088 Executive::apply_extrinsic(extrinsic)1089 }10901091 fn finalize_block() -> <Block as BlockT>::Header {1092 Executive::finalize_block()1093 }10941095 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1096 data.create_extrinsics()1097 }10981099 fn check_inherents(1100 block: Block,1101 data: sp_inherents::InherentData,1102 ) -> sp_inherents::CheckInherentsResult {1103 data.check_extrinsics(&block)1104 }11051106 // fn random_seed() -> <Block as BlockT>::Hash {1107 // RandomnessCollectiveFlip::random_seed().01108 // }1109 }11101111 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1112 fn validate_transaction(1113 source: TransactionSource,1114 tx: <Block as BlockT>::Extrinsic,1115 hash: <Block as BlockT>::Hash,1116 ) -> TransactionValidity {1117 Executive::validate_transaction(source, tx, hash)1118 }1119 }11201121 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1122 fn offchain_worker(header: &<Block as BlockT>::Header) {1123 Executive::offchain_worker(header)1124 }1125 }11261127 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1128 fn chain_id() -> u64 {1129 <Runtime as pallet_evm::Config>::ChainId::get()1130 }11311132 fn account_basic(address: H160) -> EVMAccount {1133 EVM::account_basic(&address)1134 }11351136 fn gas_price() -> U256 {1137 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1138 }11391140 fn account_code_at(address: H160) -> Vec<u8> {1141 EVM::account_codes(address)1142 }11431144 fn author() -> H160 {1145 <pallet_evm::Pallet<Runtime>>::find_author()1146 }11471148 fn storage_at(address: H160, index: U256) -> H256 {1149 let mut tmp = [0u8; 32];1150 index.to_big_endian(&mut tmp);1151 EVM::account_storages(address, H256::from_slice(&tmp[..]))1152 }11531154 fn call(1155 from: H160,1156 to: H160,1157 data: Vec<u8>,1158 value: U256,1159 gas_limit: U256,1160 gas_price: Option<U256>,1161 nonce: Option<U256>,1162 estimate: bool,1163 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1164 let config = if estimate {1165 let mut config = <Runtime as pallet_evm::Config>::config().clone();1166 config.estimate = true;1167 Some(config)1168 } else {1169 None1170 };11711172 <Runtime as pallet_evm::Config>::Runner::call(1173 from,1174 to,1175 data,1176 value,1177 gas_limit.low_u64(),1178 gas_price,1179 nonce,1180 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1181 ).map_err(|err| err.into())1182 }11831184 fn create(1185 from: H160,1186 data: Vec<u8>,1187 value: U256,1188 gas_limit: U256,1189 gas_price: Option<U256>,1190 nonce: Option<U256>,1191 estimate: bool,1192 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1193 let config = if estimate {1194 let mut config = <Runtime as pallet_evm::Config>::config().clone();1195 config.estimate = true;1196 Some(config)1197 } else {1198 None1199 };12001201 <Runtime as pallet_evm::Config>::Runner::create(1202 from,1203 data,1204 value,1205 gas_limit.low_u64(),1206 gas_price,1207 nonce,1208 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1209 ).map_err(|err| err.into())1210 }12111212 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1213 Ethereum::current_transaction_statuses()1214 }12151216 fn current_block() -> Option<pallet_ethereum::Block> {1217 Ethereum::current_block()1218 }12191220 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1221 Ethereum::current_receipts()1222 }12231224 fn current_all() -> (1225 Option<pallet_ethereum::Block>,1226 Option<Vec<pallet_ethereum::Receipt>>,1227 Option<Vec<TransactionStatus>>1228 ) {1229 (1230 Ethereum::current_block(),1231 Ethereum::current_receipts(),1232 Ethereum::current_transaction_statuses()1233 )1234 }12351236 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1237 xts.into_iter().filter_map(|xt| match xt.0.function {1238 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1239 _ => None1240 }).collect()1241 }1242 }12431244 impl sp_session::SessionKeys<Block> for Runtime {1245 fn decode_session_keys(1246 encoded: Vec<u8>,1247 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1248 SessionKeys::decode_into_raw_public_keys(&encoded)1249 }12501251 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1252 SessionKeys::generate(seed)1253 }1254 }12551256 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1257 fn slot_duration() -> sp_consensus_aura::SlotDuration {1258 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1259 }12601261 fn authorities() -> Vec<AuraId> {1262 Aura::authorities().to_vec()1263 }1264 }12651266 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1267 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1268 ParachainSystem::collect_collation_info()1269 }1270 }12711272 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1273 fn account_nonce(account: AccountId) -> Index {1274 System::account_nonce(account)1275 }1276 }12771278 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1279 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1280 TransactionPayment::query_info(uxt, len)1281 }1282 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1283 TransactionPayment::query_fee_details(uxt, len)1284 }1285 }12861287 /*1288 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1289 for Runtime1290 {1291 fn call(1292 origin: AccountId,1293 dest: AccountId,1294 value: Balance,1295 gas_limit: u64,1296 input_data: Vec<u8>,1297 ) -> pallet_contracts_primitives::ContractExecResult {1298 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1299 }13001301 fn instantiate(1302 origin: AccountId,1303 endowment: Balance,1304 gas_limit: u64,1305 code: pallet_contracts_primitives::Code<Hash>,1306 data: Vec<u8>,1307 salt: Vec<u8>,1308 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1309 {1310 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1311 }13121313 fn get_storage(1314 address: AccountId,1315 key: [u8; 32],1316 ) -> pallet_contracts_primitives::GetStorageResult {1317 Contracts::get_storage(address, key)1318 }13191320 fn rent_projection(1321 address: AccountId,1322 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1323 Contracts::rent_projection(address)1324 }1325 }1326 */13271328 #[cfg(feature = "runtime-benchmarks")]1329 impl frame_benchmarking::Benchmark<Block> for Runtime {1330 fn benchmark_metadata(extra: bool) -> (1331 Vec<frame_benchmarking::BenchmarkList>,1332 Vec<frame_support::traits::StorageInfo>,1333 ) {1334 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1335 use frame_support::traits::StorageInfoTrait;13361337 let mut list = Vec::<BenchmarkList>::new();13381339 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1340 list_benchmark!(list, extra, pallet_unique, Unique);1341 list_benchmark!(list, extra, pallet_inflation, Inflation);1342 list_benchmark!(list, extra, pallet_fungible, Fungible);1343 list_benchmark!(list, extra, pallet_refungible, Refungible);1344 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13451346 let storage_info = AllPalletsWithSystem::storage_info();13471348 return (list, storage_info)1349 }13501351 fn dispatch_benchmark(1352 config: frame_benchmarking::BenchmarkConfig1353 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1354 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13551356 let allowlist: Vec<TrackedStorageKey> = vec![1357 // Block Number1358 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1359 // Total Issuance1360 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1361 // Execution Phase1362 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1363 // Event Count1364 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1365 // System Events1366 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1367 ];13681369 let mut batches = Vec::<BenchmarkBatch>::new();1370 let params = (&config, &allowlist);13711372 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1373 add_benchmark!(params, batches, pallet_unique, Unique);1374 add_benchmark!(params, batches, pallet_inflation, Inflation);1375 add_benchmark!(params, batches, pallet_fungible, Fungible);1376 add_benchmark!(params, batches, pallet_refungible, Refungible);1377 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13781379 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1380 Ok(batches)1381 }1382 }1383}13841385struct CheckInherents;13861387impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1388 fn check_inherents(1389 block: &Block,1390 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1391 ) -> sp_inherents::CheckInherentsResult {1392 let relay_chain_slot = relay_state_proof1393 .read_slot()1394 .expect("Could not read the relay chain slot from the proof");13951396 let inherent_data =1397 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1398 relay_chain_slot,1399 sp_std::time::Duration::from_secs(6),1400 )1401 .create_inherent_data()1402 .expect("Could not create the timestamp inherent data");14031404 inherent_data.check_extrinsics(block)1405 }1406}14071408cumulus_pallet_parachain_system::register_validate_block!(1409 Runtime = Runtime,1410 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1411 CheckInherents = CheckInherents,1412);1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "1024"]11#![allow(clippy::from_over_into, clippy::identity_op)]12#![allow(clippy::fn_to_numeric_cast_with_truncation)]13// Make the WASM binary available.14#[cfg(feature = "std")]15include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1617use sp_api::impl_runtime_apis;18use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};19// #[cfg(any(feature = "std", test))]20// pub use sp_runtime::BuildStorage;2122use sp_runtime::{23 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,24 traits::{25 AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify, AccountIdConversion,26 },27 transaction_validity::{TransactionSource, TransactionValidity},28 ApplyExtrinsicResult, MultiSignature,29};3031use sp_std::prelude::*;3233#[cfg(feature = "std")]34use sp_version::NativeVersion;35use sp_version::RuntimeVersion;36pub use pallet_transaction_payment::{37 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,38};39// A few exports that help ease life for downstream crates.40pub use pallet_balances::Call as BalancesCall;41pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};42pub use frame_support::{43 construct_runtime, match_type,44 dispatch::DispatchResult,45 PalletId, parameter_types, StorageValue, ConsensusEngineId,46 traits::{47 Everything, Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem,48 LockIdentifier, OnUnbalanced, Randomness, FindAuthor,49 },50 weights::{51 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},52 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,53 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,54 },55};56use up_data_structs::*;57// use pallet_contracts::weights::WeightInfo;58// #[cfg(any(feature = "std", test))]59use frame_system::{60 self as system, EnsureRoot, EnsureSigned,61 limits::{BlockWeights, BlockLength},62};63use sp_arithmetic::{64 traits::{BaseArithmetic, Unsigned},65};66use smallvec::smallvec;67use codec::{Encode, Decode};68use pallet_evm::{Account as EVMAccount, FeeCalculator, OnMethodCall};69use fp_rpc::TransactionStatus;70use sp_core::crypto::Public;71use sp_runtime::{72 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},73 transaction_validity::TransactionValidityError,74};7576// pub use pallet_timestamp::Call as TimestampCall;77pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;7879// Polkadot imports80use pallet_xcm::XcmPassthrough;81use polkadot_parachain::primitives::Sibling;82use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};83use xcm_builder::{84 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,85 EnsureXcmOrigin, FixedWeightBounds, IsConcrete, LocationInverter, NativeAsset,86 ParentAsSuperuser, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative,87 SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,88 SovereignSignedViaLocation, TakeWeightCredit, UsingComponents,89};90use xcm_executor::{Config, XcmExecutor};9192// mod chain_extension;93// use crate::chain_extension::{NFTExtension, Imbalance};9495/// An index to a block.96pub type BlockNumber = u32;9798/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.99pub type Signature = MultiSignature;100101/// Some way of identifying an account on the chain. We intentionally make it equivalent102/// to the public key of our transaction signing scheme.103pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;104105pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;106107/// The type for looking up accounts. We don't expect more than 4 billion of them, but you108/// never know...109pub type AccountIndex = u32;110111/// Balance of an account.112pub type Balance = u128;113114/// Index of a transaction in the chain.115pub type Index = u32;116117/// A hash of some data used by the chain.118pub type Hash = sp_core::H256;119120/// Digest item type.121pub type DigestItem = generic::DigestItem<Hash>;122123/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know124/// the specifics of the runtime. They can then be made to be agnostic over specific formats125/// of data like extrinsics, allowing for them to continue syncing the network through upgrades126/// to even the core data structures.127pub mod opaque {128 use super::*;129130 pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;131132 /// Opaque block type.133 pub type Block = generic::Block<Header, UncheckedExtrinsic>;134135 pub type SessionHandlers = ();136137 impl_opaque_keys! {138 pub struct SessionKeys {139 pub aura: Aura,140 }141 }142}143144/// This runtime version.145pub const VERSION: RuntimeVersion = RuntimeVersion {146 spec_name: create_runtime_str!("opal"),147 impl_name: create_runtime_str!("opal"),148 authoring_version: 1,149 spec_version: 912204,150 impl_version: 1,151 apis: RUNTIME_API_VERSIONS,152 transaction_version: 1,153};154155pub const MILLISECS_PER_BLOCK: u64 = 12000;156157pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;158159// These time units are defined in number of blocks.160pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);161pub const HOURS: BlockNumber = MINUTES * 60;162pub const DAYS: BlockNumber = HOURS * 24;163164parameter_types! {165 pub const DefaultSponsoringRateLimit: BlockNumber = 1 * DAYS;166}167168#[derive(codec::Encode, codec::Decode)]169pub enum XCMPMessage<XAccountId, XBalance> {170 /// Transfer tokens to the given account from the Parachain account.171 TransferToken(XAccountId, XBalance),172}173174/// The version information used to identify this runtime when compiled natively.175#[cfg(feature = "std")]176pub fn native_version() -> NativeVersion {177 NativeVersion {178 runtime_version: VERSION,179 can_author_with: Default::default(),180 }181}182183type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;184185pub struct DealWithFees;186impl OnUnbalanced<NegativeImbalance> for DealWithFees {187 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {188 if let Some(fees) = fees_then_tips.next() {189 // for fees, 100% to treasury190 let mut split = fees.ration(100, 0);191 if let Some(tips) = fees_then_tips.next() {192 // for tips, if any, 100% to treasury193 tips.ration_merge_into(100, 0, &mut split);194 }195 Treasury::on_unbalanced(split.0);196 // Author::on_unbalanced(split.1);197 }198 }199}200201/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.202/// This is used to limit the maximal weight of a single extrinsic.203const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);204/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used205/// by Operational extrinsics.206const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);207/// We allow for 2 seconds of compute with a 6 second average block time.208const MAXIMUM_BLOCK_WEIGHT: Weight = WEIGHT_PER_SECOND / 2;209210parameter_types! {211 pub const BlockHashCount: BlockNumber = 2400;212 pub RuntimeBlockLength: BlockLength =213 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);214 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);215 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;216 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()217 .base_block(BlockExecutionWeight::get())218 .for_class(DispatchClass::all(), |weights| {219 weights.base_extrinsic = ExtrinsicBaseWeight::get();220 })221 .for_class(DispatchClass::Normal, |weights| {222 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);223 })224 .for_class(DispatchClass::Operational, |weights| {225 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);226 // Operational transactions have some extra reserved space, so that they227 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.228 weights.reserved = Some(229 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT230 );231 })232 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)233 .build_or_panic();234 pub const Version: RuntimeVersion = VERSION;235 pub const SS58Prefix: u8 = 42;236}237238parameter_types! {239 pub const ChainId: u64 = 8888;240}241242pub struct FixedFee;243impl FeeCalculator for FixedFee {244 fn min_gas_price() -> U256 {245 1.into()246 }247}248249impl pallet_evm::Config for Runtime {250 type BlockGasLimit = BlockGasLimit;251 type FeeCalculator = FixedFee;252 type GasWeightMapping = ();253 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;254 type CallOrigin = EnsureAddressTruncated;255 type WithdrawOrigin = EnsureAddressTruncated;256 type AddressMapping = HashedAddressMapping<Self::Hashing>;257 type Precompiles = ();258 type Currency = Balances;259 type Event = Event;260 type OnMethodCall = (261 pallet_evm_migration::OnMethodCall<Self>,262 pallet_unique::UniqueErcSupport<Self>,263 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,264 );265 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;266 type ChainId = ChainId;267 type Runner = pallet_evm::runner::stack::Runner<Self>;268 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;269 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;270 type FindAuthor = EthereumFindAuthor<Aura>;271}272273impl pallet_evm_migration::Config for Runtime {274 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;275}276277pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);278impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {279 fn find_author<'a, I>(digests: I) -> Option<H160>280 where281 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,282 {283 if let Some(author_index) = F::find_author(digests) {284 let authority_id = Aura::authorities()[author_index as usize].clone();285 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));286 }287 None288 }289}290291parameter_types! {292 pub BlockGasLimit: U256 = U256::from(u32::max_value());293}294295impl pallet_ethereum::Config for Runtime {296 type Event = Event;297 type StateRoot = pallet_ethereum::IntermediateStateRoot;298 type EvmSubmitLog = pallet_evm::Pallet<Self>;299}300301impl pallet_randomness_collective_flip::Config for Runtime {}302303impl system::Config for Runtime {304 /// The data to be stored in an account.305 type AccountData = pallet_balances::AccountData<Balance>;306 /// The identifier used to distinguish between accounts.307 type AccountId = AccountId;308 /// The basic call filter to use in dispatchable.309 type BaseCallFilter = Everything;310 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).311 type BlockHashCount = BlockHashCount;312 /// The maximum length of a block (in bytes).313 type BlockLength = RuntimeBlockLength;314 /// The index type for blocks.315 type BlockNumber = BlockNumber;316 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.317 type BlockWeights = RuntimeBlockWeights;318 /// The aggregated dispatch type that is available for extrinsics.319 type Call = Call;320 /// The weight of database operations that the runtime can invoke.321 type DbWeight = RocksDbWeight;322 /// The ubiquitous event type.323 type Event = Event;324 /// The type for hashing blocks and tries.325 type Hash = Hash;326 /// The hashing algorithm used.327 type Hashing = BlakeTwo256;328 /// The header type.329 type Header = generic::Header<BlockNumber, BlakeTwo256>;330 /// The index type for storing how many extrinsics an account has signed.331 type Index = Index;332 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.333 type Lookup = AccountIdLookup<AccountId, ()>;334 /// What to do if an account is fully reaped from the system.335 type OnKilledAccount = ();336 /// What to do if a new account is created.337 type OnNewAccount = ();338 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;339 /// The ubiquitous origin type.340 type Origin = Origin;341 /// This type is being generated by `construct_runtime!`.342 type PalletInfo = PalletInfo;343 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.344 type SS58Prefix = SS58Prefix;345 /// Weight information for the extrinsics of this pallet.346 type SystemWeightInfo = system::weights::SubstrateWeight<Self>;347 /// Version of the runtime.348 type Version = Version;349}350351parameter_types! {352 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;353}354355impl pallet_timestamp::Config for Runtime {356 /// A timestamp: milliseconds since the unix epoch.357 type Moment = u64;358 type OnTimestampSet = ();359 type MinimumPeriod = MinimumPeriod;360 type WeightInfo = ();361}362363parameter_types! {364 // pub const ExistentialDeposit: u128 = 500;365 pub const ExistentialDeposit: u128 = 0;366 pub const MaxLocks: u32 = 50;367}368369impl pallet_balances::Config for Runtime {370 type MaxLocks = MaxLocks;371 type MaxReserves = ();372 type ReserveIdentifier = [u8; 8];373 /// The type for recording an account's balance.374 type Balance = Balance;375 /// The ubiquitous event type.376 type Event = Event;377 type DustRemoval = Treasury;378 type ExistentialDeposit = ExistentialDeposit;379 type AccountStore = System;380 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;381}382383pub const MICROUNIQUE: Balance = 1_000_000_000;384pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;385pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;386pub const UNIQUE: Balance = 100 * CENTIUNIQUE;387388pub const fn deposit(items: u32, bytes: u32) -> Balance {389 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE390}391392/*393parameter_types! {394 pub TombstoneDeposit: Balance = deposit(395 1,396 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,397 );398 pub DepositPerContract: Balance = TombstoneDeposit::get();399 pub const DepositPerStorageByte: Balance = deposit(0, 1);400 pub const DepositPerStorageItem: Balance = deposit(1, 0);401 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);402 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;403 pub const SignedClaimHandicap: u32 = 2;404 pub const MaxDepth: u32 = 32;405 pub const MaxValueSize: u32 = 16 * 1024;406 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb407 // The lazy deletion runs inside on_initialize.408 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *409 RuntimeBlockWeights::get().max_block;410 // The weight needed for decoding the queue should be less or equal than a fifth411 // of the overall weight dedicated to the lazy deletion.412 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (413 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)415 )) / 5) as u32;416 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();417}418419impl pallet_contracts::Config for Runtime {420 type Time = Timestamp;421 type Randomness = RandomnessCollectiveFlip;422 type Currency = Balances;423 type Event = Event;424 type RentPayment = ();425 type SignedClaimHandicap = SignedClaimHandicap;426 type TombstoneDeposit = TombstoneDeposit;427 type DepositPerContract = DepositPerContract;428 type DepositPerStorageByte = DepositPerStorageByte;429 type DepositPerStorageItem = DepositPerStorageItem;430 type RentFraction = RentFraction;431 type SurchargeReward = SurchargeReward;432 type WeightPrice = pallet_transaction_payment::Pallet<Self>;433 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;434 type ChainExtension = NFTExtension;435 type DeletionQueueDepth = DeletionQueueDepth;436 type DeletionWeightLimit = DeletionWeightLimit;437 type Schedule = Schedule;438 type CallStack = [pallet_contracts::Frame<Self>; 31];439}440*/441442parameter_types! {443 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer444 /// This value increases the priority of `Operational` transactions by adding445 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.446 pub const OperationalFeeMultiplier: u8 = 5;447}448449/// Linear implementor of `WeightToFeePolynomial`450pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);451452impl<T> WeightToFeePolynomial for LinearFee<T>453where454 T: BaseArithmetic + From<u32> + Copy + Unsigned,455{456 type Balance = T;457458 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {459 smallvec!(WeightToFeeCoefficient {460 coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer461 coeff_frac: Perbill::zero(),462 negative: false,463 degree: 1,464 })465 }466}467468impl pallet_transaction_payment::Config for Runtime {469 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;470 type TransactionByteFee = TransactionByteFee;471 type OperationalFeeMultiplier = OperationalFeeMultiplier;472 type WeightToFee = LinearFee<Balance>;473 type FeeMultiplierUpdate = ();474}475476parameter_types! {477 pub const ProposalBond: Permill = Permill::from_percent(5);478 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;479 pub const SpendPeriod: BlockNumber = 5 * MINUTES;480 pub const Burn: Permill = Permill::from_percent(0);481 pub const TipCountdown: BlockNumber = 1 * DAYS;482 pub const TipFindersFee: Percent = Percent::from_percent(20);483 pub const TipReportDepositBase: Balance = 1 * UNIQUE;484 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;485 pub const BountyDepositBase: Balance = 1 * UNIQUE;486 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;487 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");488 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;489 pub const MaximumReasonLength: u32 = 16384;490 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);491 pub const BountyValueMinimum: Balance = 5 * UNIQUE;492 pub const MaxApprovals: u32 = 100;493}494495impl pallet_treasury::Config for Runtime {496 type PalletId = TreasuryModuleId;497 type Currency = Balances;498 type ApproveOrigin = EnsureRoot<AccountId>;499 type RejectOrigin = EnsureRoot<AccountId>;500 type Event = Event;501 type OnSlash = ();502 type ProposalBond = ProposalBond;503 type ProposalBondMinimum = ProposalBondMinimum;504 type SpendPeriod = SpendPeriod;505 type Burn = Burn;506 type BurnDestination = ();507 type SpendFunds = ();508 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;509 type MaxApprovals = MaxApprovals;510}511512impl pallet_sudo::Config for Runtime {513 type Event = Event;514 type Call = Call;515}516517pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);518519impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider520 for RelayChainBlockNumberProvider<T>521{522 type BlockNumber = BlockNumber;523524 fn current_block_number() -> Self::BlockNumber {525 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()526 .map(|d| d.relay_parent_number)527 .unwrap_or_default()528 }529}530531parameter_types! {532 pub const MinVestedTransfer: Balance = 10 * UNIQUE;533 pub const MaxVestingSchedules: u32 = 28;534}535536impl orml_vesting::Config for Runtime {537 type Event = Event;538 type Currency = pallet_balances::Pallet<Runtime>;539 type MinVestedTransfer = MinVestedTransfer;540 type VestedTransferOrigin = EnsureSigned<AccountId>;541 type WeightInfo = ();542 type MaxVestingSchedules = MaxVestingSchedules;543 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;544}545546parameter_types! {547 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;548 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;549}550551impl cumulus_pallet_parachain_system::Config for Runtime {552 type Event = Event;553 type OnValidationData = ();554 type SelfParaId = parachain_info::Pallet<Self>;555 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<556 // MaxDownwardMessageWeight,557 // XcmExecutor<XcmConfig>,558 // Call,559 // >;560 type OutboundXcmpMessageSource = XcmpQueue;561 type DmpMessageHandler = DmpQueue;562 type ReservedDmpWeight = ReservedDmpWeight;563 type ReservedXcmpWeight = ReservedXcmpWeight;564 type XcmpMessageHandler = XcmpQueue;565}566567impl parachain_info::Config for Runtime {}568569impl cumulus_pallet_aura_ext::Config for Runtime {}570571parameter_types! {572 pub const RelayLocation: MultiLocation = MultiLocation::parent();573 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;574 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();575 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();576}577578/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used579/// when determining ownership of accounts for asset transacting and when attempting to use XCM580/// `Transact` in order to determine the dispatch Origin.581pub type LocationToAccountId = (582 // The parent (Relay-chain) origin converts to the default `AccountId`.583 ParentIsDefault<AccountId>,584 // Sibling parachain origins convert to AccountId via the `ParaId::into`.585 SiblingParachainConvertsVia<Sibling, AccountId>,586 // Straight up local `AccountId32` origins just alias directly to `AccountId`.587 AccountId32Aliases<RelayNetwork, AccountId>,588);589590/// Means for transacting assets on this chain.591pub type LocalAssetTransactor = CurrencyAdapter<592 // Use this currency:593 Balances,594 // Use this currency when it is a fungible asset matching the given location or name:595 IsConcrete<RelayLocation>,596 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:597 LocationToAccountId,598 // Our chain's account ID type (we can't get away without mentioning it explicitly):599 AccountId,600 // We don't track any teleports.601 (),602>;603604/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,605/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can606/// biases the kind of local `Origin` it will become.607pub type XcmOriginToTransactDispatchOrigin = (608 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location609 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for610 // foreign chains who want to have a local sovereign account on this chain which they control.611 SovereignSignedViaLocation<LocationToAccountId, Origin>,612 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when613 // recognised.614 RelayChainAsNative<RelayOrigin, Origin>,615 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when616 // recognised.617 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,618 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a619 // transaction from the Root origin.620 ParentAsSuperuser<Origin>,621 // Native signed account converter; this just converts an `AccountId32` origin into a normal622 // `Origin::Signed` origin of the same 32-byte value.623 SignedAccountId32AsNative<RelayNetwork, Origin>,624 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.625 XcmPassthrough<Origin>,626);627628parameter_types! {629 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.630 pub UnitWeightCost: Weight = 1_000_000;631 // 1200 UNIQUEs buy 1 second of weight.632 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);633 pub const MaxInstructions: u32 = 100;634 pub const MaxAuthorities: u32 = 100_000;635}636637match_type! {638 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {639 MultiLocation { parents: 1, interior: Here } |640 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }641 };642}643644pub type Barrier = (645 TakeWeightCredit,646 AllowTopLevelPaidExecutionFrom<Everything>,647 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,648 // ^^^ Parent & its unit plurality gets free execution649);650651pub struct XcmConfig;652impl Config for XcmConfig {653 type Call = Call;654 type XcmSender = XcmRouter;655 // How to withdraw and deposit an asset.656 type AssetTransactor = LocalAssetTransactor;657 type OriginConverter = XcmOriginToTransactDispatchOrigin;658 type IsReserve = NativeAsset;659 type IsTeleporter = (); // Teleportation is disabled660 type LocationInverter = LocationInverter<Ancestry>;661 type Barrier = Barrier;662 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;663 type Trader = UsingComponents<IdentityFee<Balance>, RelayLocation, AccountId, Balances, ()>;664 type ResponseHandler = (); // Don't handle responses for now.665 type SubscriptionService = PolkadotXcm;666667 type AssetTrap = PolkadotXcm;668 type AssetClaims = PolkadotXcm;669}670671// parameter_types! {672// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;673// }674675/// No local origins on this chain are allowed to dispatch XCM sends/executions.676pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);677678/// The means for routing XCM messages which are not for local execution into the right message679/// queues.680pub type XcmRouter = (681 // Two routers - use UMP to communicate with the relay chain:682 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,683 // ..and XCMP to communicate with the sibling chains.684 XcmpQueue,685);686687impl pallet_evm_coder_substrate::Config for Runtime {688 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;689}690691impl pallet_xcm::Config for Runtime {692 type Event = Event;693 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;694 type XcmRouter = XcmRouter;695 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;696 type XcmExecuteFilter = Everything;697 type XcmExecutor = XcmExecutor<XcmConfig>;698 type XcmTeleportFilter = Everything;699 type XcmReserveTransferFilter = Everything;700 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;701 type LocationInverter = LocationInverter<Ancestry>;702 type Origin = Origin;703 type Call = Call;704 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;705 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;706}707708impl cumulus_pallet_xcm::Config for Runtime {709 type Event = Event;710 type XcmExecutor = XcmExecutor<XcmConfig>;711}712713impl cumulus_pallet_xcmp_queue::Config for Runtime {714 type Event = Event;715 type XcmExecutor = XcmExecutor<XcmConfig>;716 type ChannelInfo = ParachainSystem;717 type VersionWrapper = ();718}719720impl cumulus_pallet_dmp_queue::Config for Runtime {721 type Event = Event;722 type XcmExecutor = XcmExecutor<XcmConfig>;723 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;724}725726impl pallet_aura::Config for Runtime {727 type AuthorityId = AuraId;728 type DisabledValidators = ();729 type MaxAuthorities = MaxAuthorities;730}731732parameter_types! {733 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();734 pub const CollectionCreationPrice: Balance = 100 * UNIQUE;735}736737impl pallet_common::Config for Runtime {738 type Event = Event;739 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;740 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;741 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;742743 type Currency = Balances;744 type CollectionCreationPrice = CollectionCreationPrice;745 type TreasuryAccountId = TreasuryAccountId;746}747748impl pallet_fungible::Config for Runtime {749 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;750}751impl pallet_refungible::Config for Runtime {752 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;753}754impl pallet_nonfungible::Config for Runtime {755 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;756}757758impl pallet_unique::Config for Runtime {759 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;760}761762parameter_types! {763 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied764}765766/// Used for the pallet inflation767impl pallet_inflation::Config for Runtime {768 type Currency = Balances;769 type TreasuryAccountId = TreasuryAccountId;770 type InflationBlockInterval = InflationBlockInterval;771 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;772}773774// parameter_types! {775// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *776// RuntimeBlockWeights::get().max_block;777// pub const MaxScheduledPerBlock: u32 = 50;778// }779780type EvmSponsorshipHandler = (781 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,782 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,783);784type SponsorshipHandler = (785 pallet_unique::UniqueSponsorshipHandler<Runtime>,786 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,787 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,788);789790// impl pallet_unq_scheduler::Config for Runtime {791// type Event = Event;792// type Origin = Origin;793// type PalletsOrigin = OriginCaller;794// type Call = Call;795// type MaximumWeight = MaximumSchedulerWeight;796// type ScheduleOrigin = EnsureSigned<AccountId>;797// type MaxScheduledPerBlock = MaxScheduledPerBlock;798// type SponsorshipHandler = SponsorshipHandler;799// type WeightInfo = ();800// }801802impl pallet_evm_transaction_payment::Config for Runtime {803 type EvmSponsorshipHandler = EvmSponsorshipHandler;804 type Currency = Balances;805 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;806 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;807}808809impl pallet_charge_transaction::Config for Runtime {810 type SponsorshipHandler = SponsorshipHandler;811}812813// impl pallet_contract_helpers::Config for Runtime {814// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;815// }816817parameter_types! {818 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049819 pub const HelpersContractAddress: H160 = H160([820 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,821 ]);822}823824impl pallet_evm_contract_helpers::Config for Runtime {825 type ContractAddress = HelpersContractAddress;826 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;827}828829construct_runtime!(830 pub enum Runtime where831 Block = Block,832 NodeBlock = opaque::Block,833 UncheckedExtrinsic = UncheckedExtrinsic834 {835 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,836 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,837838 Aura: pallet_aura::{Pallet, Config<T>} = 22,839 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,840841 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,842 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,843 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,844 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,845 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,846 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,847 System: system::{Pallet, Call, Storage, Config, Event<T>} = 36,848 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,849 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,850 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,851852 // XCM helpers.853 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,854 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,855 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,856 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,857858 // Unique Pallets859 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,860 Unique: pallet_unique::{Pallet, Call, Storage} = 61,861 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,862 // free = 63863 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,864 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,865 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,866 Fungible: pallet_fungible::{Pallet, Storage} = 67,867 Refungible: pallet_refungible::{Pallet, Storage} = 68,868 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,869870 // Frontier871 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,872 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,873874 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,875 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,876 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,877 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,878 }879);880881pub struct TransactionConverter;882883impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {884 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {885 UncheckedExtrinsic::new_unsigned(886 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),887 )888 }889}890891impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {892 fn convert_transaction(893 &self,894 transaction: pallet_ethereum::Transaction,895 ) -> opaque::UncheckedExtrinsic {896 let extrinsic = UncheckedExtrinsic::new_unsigned(897 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),898 );899 let encoded = extrinsic.encode();900 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])901 .expect("Encoded extrinsic is always valid")902 }903}904905/// The address format for describing accounts.906pub type Address = sp_runtime::MultiAddress<AccountId, ()>;907/// Block header type as expected by this runtime.908pub type Header = generic::Header<BlockNumber, BlakeTwo256>;909/// Block type as expected by this runtime.910pub type Block = generic::Block<Header, UncheckedExtrinsic>;911/// A Block signed with a Justification912pub type SignedBlock = generic::SignedBlock<Block>;913/// BlockId type as expected by this runtime.914pub type BlockId = generic::BlockId<Block>;915/// The SignedExtension to the basic transaction logic.916pub type SignedExtra = (917 system::CheckSpecVersion<Runtime>,918 // system::CheckTxVersion<Runtime>,919 system::CheckGenesis<Runtime>,920 system::CheckEra<Runtime>,921 system::CheckNonce<Runtime>,922 system::CheckWeight<Runtime>,923 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,924 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,925);926/// Unchecked extrinsic type as expected by this runtime.927pub type UncheckedExtrinsic =928 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;929/// Extrinsic type that has already been checked.930pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;931/// Executive: handles dispatch to the various modules.932pub type Executive = frame_executive::Executive<933 Runtime,934 Block,935 frame_system::ChainContext<Runtime>,936 Runtime,937 AllPallets,938>;939940impl_opaque_keys! {941 pub struct SessionKeys {942 pub aura: Aura,943 }944}945946impl fp_self_contained::SelfContainedCall for Call {947 type SignedInfo = H160;948949 fn is_self_contained(&self) -> bool {950 match self {951 Call::Ethereum(call) => call.is_self_contained(),952 _ => false,953 }954 }955956 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {957 match self {958 Call::Ethereum(call) => call.check_self_contained(),959 _ => None,960 }961 }962963 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {964 match self {965 Call::Ethereum(call) => call.validate_self_contained(info),966 _ => None,967 }968 }969970 fn pre_dispatch_self_contained(971 &self,972 info: &Self::SignedInfo,973 ) -> Option<Result<(), TransactionValidityError>> {974 match self {975 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),976 _ => None,977 }978 }979980 fn apply_self_contained(981 self,982 info: Self::SignedInfo,983 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {984 match self {985 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(986 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),987 )),988 _ => None,989 }990 }991}992993macro_rules! dispatch_unique_runtime {994 ($collection:ident.$method:ident($($name:ident),*)) => {{995 use pallet_unique::dispatch::Dispatched;996997 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::new($collection).unwrap());998 let dispatch = collection.as_dyn();9991000 dispatch.$method($($name),*)1001 }};1002}1003impl_runtime_apis! {1004 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1005 for Runtime1006 {1007 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Vec<TokenId> {1008 dispatch_unique_runtime!(collection.account_tokens(account))1009 }1010 fn token_exists(collection: CollectionId, token: TokenId) -> bool {1011 dispatch_unique_runtime!(collection.token_exists(token))1012 }10131014 fn token_owner(collection: CollectionId, token: TokenId) -> CrossAccountId {1015 dispatch_unique_runtime!(collection.token_owner(token))1016 }1017 fn const_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1018 dispatch_unique_runtime!(collection.const_metadata(token))1019 }1020 fn variable_metadata(collection: CollectionId, token: TokenId) -> Vec<u8> {1021 dispatch_unique_runtime!(collection.variable_metadata(token))1022 }10231024 fn collection_tokens(collection: CollectionId) -> u32 {1025 dispatch_unique_runtime!(collection.collection_tokens())1026 }1027 fn account_balance(collection: CollectionId, account: CrossAccountId) -> u32 {1028 dispatch_unique_runtime!(collection.account_balance(account))1029 }1030 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> u128 {1031 dispatch_unique_runtime!(collection.balance(account, token))1032 }1033 fn allowance(1034 collection: CollectionId,1035 sender: CrossAccountId,1036 spender: CrossAccountId,1037 token: TokenId,1038 ) -> u128 {1039 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1040 }10411042 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1043 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1044 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1045 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1046 }1047 fn adminlist(collection: CollectionId) -> Vec<CrossAccountId> {1048 <pallet_common::Pallet<Runtime>>::adminlist(collection)1049 }1050 fn allowlist(collection: CollectionId) -> Vec<CrossAccountId> {1051 <pallet_common::Pallet<Runtime>>::allowlist(collection)1052 }1053 fn allowed(collection: CollectionId, user: CrossAccountId) -> bool {1054 <pallet_common::Pallet<Runtime>>::allowed(collection, user)1055 }1056 fn last_token_id(collection: CollectionId) -> TokenId {1057 dispatch_unique_runtime!(collection.last_token_id())1058 }1059 fn collection_by_id(collection: CollectionId) -> Option<Collection<AccountId>> {1060 <pallet_common::CollectionById<Runtime>>::get(collection)1061 }1062 fn collection_stats() -> CollectionStats {1063 <pallet_common::Pallet<Runtime>>::collection_stats()1064 }1065 }10661067 impl sp_api::Core<Block> for Runtime {1068 fn version() -> RuntimeVersion {1069 VERSION1070 }10711072 fn execute_block(block: Block) {1073 Executive::execute_block(block)1074 }10751076 fn initialize_block(header: &<Block as BlockT>::Header) {1077 Executive::initialize_block(header)1078 }1079 }10801081 impl sp_api::Metadata<Block> for Runtime {1082 fn metadata() -> OpaqueMetadata {1083 OpaqueMetadata::new(Runtime::metadata().into())1084 }1085 }10861087 impl sp_block_builder::BlockBuilder<Block> for Runtime {1088 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1089 Executive::apply_extrinsic(extrinsic)1090 }10911092 fn finalize_block() -> <Block as BlockT>::Header {1093 Executive::finalize_block()1094 }10951096 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1097 data.create_extrinsics()1098 }10991100 fn check_inherents(1101 block: Block,1102 data: sp_inherents::InherentData,1103 ) -> sp_inherents::CheckInherentsResult {1104 data.check_extrinsics(&block)1105 }11061107 // fn random_seed() -> <Block as BlockT>::Hash {1108 // RandomnessCollectiveFlip::random_seed().01109 // }1110 }11111112 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1113 fn validate_transaction(1114 source: TransactionSource,1115 tx: <Block as BlockT>::Extrinsic,1116 hash: <Block as BlockT>::Hash,1117 ) -> TransactionValidity {1118 Executive::validate_transaction(source, tx, hash)1119 }1120 }11211122 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1123 fn offchain_worker(header: &<Block as BlockT>::Header) {1124 Executive::offchain_worker(header)1125 }1126 }11271128 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1129 fn chain_id() -> u64 {1130 <Runtime as pallet_evm::Config>::ChainId::get()1131 }11321133 fn account_basic(address: H160) -> EVMAccount {1134 EVM::account_basic(&address)1135 }11361137 fn gas_price() -> U256 {1138 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1139 }11401141 fn account_code_at(address: H160) -> Vec<u8> {1142 EVM::account_codes(address)1143 }11441145 fn author() -> H160 {1146 <pallet_evm::Pallet<Runtime>>::find_author()1147 }11481149 fn storage_at(address: H160, index: U256) -> H256 {1150 let mut tmp = [0u8; 32];1151 index.to_big_endian(&mut tmp);1152 EVM::account_storages(address, H256::from_slice(&tmp[..]))1153 }11541155 fn call(1156 from: H160,1157 to: H160,1158 data: Vec<u8>,1159 value: U256,1160 gas_limit: U256,1161 gas_price: Option<U256>,1162 nonce: Option<U256>,1163 estimate: bool,1164 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1165 let config = if estimate {1166 let mut config = <Runtime as pallet_evm::Config>::config().clone();1167 config.estimate = true;1168 Some(config)1169 } else {1170 None1171 };11721173 <Runtime as pallet_evm::Config>::Runner::call(1174 from,1175 to,1176 data,1177 value,1178 gas_limit.low_u64(),1179 gas_price,1180 nonce,1181 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1182 ).map_err(|err| err.into())1183 }11841185 fn create(1186 from: H160,1187 data: Vec<u8>,1188 value: U256,1189 gas_limit: U256,1190 gas_price: Option<U256>,1191 nonce: Option<U256>,1192 estimate: bool,1193 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1194 let config = if estimate {1195 let mut config = <Runtime as pallet_evm::Config>::config().clone();1196 config.estimate = true;1197 Some(config)1198 } else {1199 None1200 };12011202 <Runtime as pallet_evm::Config>::Runner::create(1203 from,1204 data,1205 value,1206 gas_limit.low_u64(),1207 gas_price,1208 nonce,1209 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1210 ).map_err(|err| err.into())1211 }12121213 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1214 Ethereum::current_transaction_statuses()1215 }12161217 fn current_block() -> Option<pallet_ethereum::Block> {1218 Ethereum::current_block()1219 }12201221 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1222 Ethereum::current_receipts()1223 }12241225 fn current_all() -> (1226 Option<pallet_ethereum::Block>,1227 Option<Vec<pallet_ethereum::Receipt>>,1228 Option<Vec<TransactionStatus>>1229 ) {1230 (1231 Ethereum::current_block(),1232 Ethereum::current_receipts(),1233 Ethereum::current_transaction_statuses()1234 )1235 }12361237 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1238 xts.into_iter().filter_map(|xt| match xt.0.function {1239 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1240 _ => None1241 }).collect()1242 }1243 }12441245 impl sp_session::SessionKeys<Block> for Runtime {1246 fn decode_session_keys(1247 encoded: Vec<u8>,1248 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1249 SessionKeys::decode_into_raw_public_keys(&encoded)1250 }12511252 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1253 SessionKeys::generate(seed)1254 }1255 }12561257 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1258 fn slot_duration() -> sp_consensus_aura::SlotDuration {1259 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1260 }12611262 fn authorities() -> Vec<AuraId> {1263 Aura::authorities().to_vec()1264 }1265 }12661267 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1268 fn collect_collation_info() -> cumulus_primitives_core::CollationInfo {1269 ParachainSystem::collect_collation_info()1270 }1271 }12721273 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1274 fn account_nonce(account: AccountId) -> Index {1275 System::account_nonce(account)1276 }1277 }12781279 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1280 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1281 TransactionPayment::query_info(uxt, len)1282 }1283 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1284 TransactionPayment::query_fee_details(uxt, len)1285 }1286 }12871288 /*1289 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1290 for Runtime1291 {1292 fn call(1293 origin: AccountId,1294 dest: AccountId,1295 value: Balance,1296 gas_limit: u64,1297 input_data: Vec<u8>,1298 ) -> pallet_contracts_primitives::ContractExecResult {1299 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1300 }13011302 fn instantiate(1303 origin: AccountId,1304 endowment: Balance,1305 gas_limit: u64,1306 code: pallet_contracts_primitives::Code<Hash>,1307 data: Vec<u8>,1308 salt: Vec<u8>,1309 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1310 {1311 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1312 }13131314 fn get_storage(1315 address: AccountId,1316 key: [u8; 32],1317 ) -> pallet_contracts_primitives::GetStorageResult {1318 Contracts::get_storage(address, key)1319 }13201321 fn rent_projection(1322 address: AccountId,1323 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1324 Contracts::rent_projection(address)1325 }1326 }1327 */13281329 #[cfg(feature = "runtime-benchmarks")]1330 impl frame_benchmarking::Benchmark<Block> for Runtime {1331 fn benchmark_metadata(extra: bool) -> (1332 Vec<frame_benchmarking::BenchmarkList>,1333 Vec<frame_support::traits::StorageInfo>,1334 ) {1335 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1336 use frame_support::traits::StorageInfoTrait;13371338 let mut list = Vec::<BenchmarkList>::new();13391340 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1341 list_benchmark!(list, extra, pallet_unique, Unique);1342 list_benchmark!(list, extra, pallet_inflation, Inflation);1343 list_benchmark!(list, extra, pallet_fungible, Fungible);1344 list_benchmark!(list, extra, pallet_refungible, Refungible);1345 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);13461347 let storage_info = AllPalletsWithSystem::storage_info();13481349 return (list, storage_info)1350 }13511352 fn dispatch_benchmark(1353 config: frame_benchmarking::BenchmarkConfig1354 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1355 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};13561357 let allowlist: Vec<TrackedStorageKey> = vec![1358 // Block Number1359 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1360 // Total Issuance1361 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1362 // Execution Phase1363 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1364 // Event Count1365 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1366 // System Events1367 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1368 ];13691370 let mut batches = Vec::<BenchmarkBatch>::new();1371 let params = (&config, &allowlist);13721373 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1374 add_benchmark!(params, batches, pallet_unique, Unique);1375 add_benchmark!(params, batches, pallet_inflation, Inflation);1376 add_benchmark!(params, batches, pallet_fungible, Fungible);1377 add_benchmark!(params, batches, pallet_refungible, Refungible);1378 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);13791380 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1381 Ok(batches)1382 }1383 }1384}13851386struct CheckInherents;13871388impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1389 fn check_inherents(1390 block: &Block,1391 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1392 ) -> sp_inherents::CheckInherentsResult {1393 let relay_chain_slot = relay_state_proof1394 .read_slot()1395 .expect("Could not read the relay chain slot from the proof");13961397 let inherent_data =1398 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1399 relay_chain_slot,1400 sp_std::time::Duration::from_secs(6),1401 )1402 .create_inherent_data()1403 .expect("Could not create the timestamp inherent data");14041405 inherent_data.check_extrinsics(block)1406 }1407}14081409cumulus_pallet_parachain_system::register_validate_block!(1410 Runtime = Runtime,1411 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1412 CheckInherents = CheckInherents,1413);