difftreelog
Adjust node name according to used runtime
in: master
4 files changed
node/cli/src/command.rsdiffbeforeafterboth--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -79,7 +79,7 @@
impl SubstrateCli for Cli {
// TODO use args
fn impl_name() -> String {
- "Opal Node".into()
+ format!("{} Node", runtime::RUNTIME_NAME)
}
fn impl_version() -> String {
@@ -88,10 +88,11 @@
// TODO use args
fn description() -> String {
format!(
- "Opal Node\n\nThe command-line arguments provided first will be \
+ "{} Node\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
{} [parachain-args] -- [relaychain-args]",
+ runtime::RUNTIME_NAME,
Self::executable_name()
)
}
@@ -121,7 +122,7 @@
impl SubstrateCli for RelayChainCli {
// TODO use args
fn impl_name() -> String {
- "Opal Node".into()
+ format!("{} Node", runtime::RUNTIME_NAME)
}
fn impl_version() -> String {
@@ -129,11 +130,13 @@
}
// TODO use args
fn description() -> String {
- "Opal Node\n\nThe command-line arguments provided first will be \
+ format!(
+ "{} Node\n\nThe command-line arguments provided first will be \
passed to the parachain node, while the arguments provided after -- will be passed \
to the relaychain node.\n\n\
- parachain-collator [parachain-args] -- [relaychain-args]"
- .into()
+ parachain-collator [parachain-args] -- [relaychain-args]",
+ runtime::RUNTIME_NAME
+ )
}
fn author() -> String {
runtime/opal/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{37 AccountIdLookup, BlakeTwo256, Block as BlockT,38 AccountIdConversion, Zero,39 },40 transaction_validity::{TransactionSource, TransactionValidity},41 ApplyExtrinsicResult, RuntimeAppPublic,42};4344use sp_std::prelude::*;4546#[cfg(feature = "std")]47use sp_version::NativeVersion;48use sp_version::RuntimeVersion;49pub use pallet_transaction_payment::{50 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,51};52// A few exports that help ease life for downstream crates.53pub use pallet_balances::Call as BalancesCall;54pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};55pub use frame_support::{56 construct_runtime, match_type,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,68 },69};70use up_data_structs::*;71// use pallet_contracts::weights::WeightInfo;72// #[cfg(any(feature = "std", test))]73use frame_system::{74 self as frame_system, EnsureRoot, EnsureSigned,75 limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78 traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use codec::{Encode, Decode};82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;91pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9293// Polkadot imports94use pallet_xcm::XcmPassthrough;95use polkadot_parachain::primitives::Sibling;96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 types::*,120 constants::*,121};122123// mod chain_extension;124// use crate::chain_extension::{NFTExtension, Imbalance};125126pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;127128/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know129/// the specifics of the runtime. They can then be made to be agnostic over specific formats130/// of data like extrinsics, allowing for them to continue syncing the network through upgrades131/// to even the core data structures.132pub mod opaque {133 use sp_std::prelude::*;134 use sp_runtime::impl_opaque_keys;135 use super::Aura;136137 pub use unique_runtime_common::types::*;138 pub use super::CrossAccountId;139140 impl_opaque_keys! {141 pub struct SessionKeys {142 pub aura: Aura,143 }144 }145}146147/// This runtime version.148pub const VERSION: RuntimeVersion = RuntimeVersion {149 spec_name: create_runtime_str!("opal"),150 impl_name: create_runtime_str!("opal"),151 authoring_version: 1,152 spec_version: 917004,153 impl_version: 0,154 apis: RUNTIME_API_VERSIONS,155 transaction_version: 1,156 state_version: 0,157};158159#[derive(codec::Encode, codec::Decode)]160pub enum XCMPMessage<XAccountId, XBalance> {161 /// Transfer tokens to the given account from the Parachain account.162 TransferToken(XAccountId, XBalance),163}164165/// The version information used to identify this runtime when compiled natively.166#[cfg(feature = "std")]167pub fn native_version() -> NativeVersion {168 NativeVersion {169 runtime_version: VERSION,170 can_author_with: Default::default(),171 }172}173174type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;175176pub struct DealWithFees;177impl OnUnbalanced<NegativeImbalance> for DealWithFees {178 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {179 if let Some(fees) = fees_then_tips.next() {180 // for fees, 100% to treasury181 let mut split = fees.ration(100, 0);182 if let Some(tips) = fees_then_tips.next() {183 // for tips, if any, 100% to treasury184 tips.ration_merge_into(100, 0, &mut split);185 }186 Treasury::on_unbalanced(split.0);187 // Author::on_unbalanced(split.1);188 }189 }190}191192parameter_types! {193 pub const BlockHashCount: BlockNumber = 2400;194 pub RuntimeBlockLength: BlockLength =195 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);196 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);197 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;198 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()199 .base_block(BlockExecutionWeight::get())200 .for_class(DispatchClass::all(), |weights| {201 weights.base_extrinsic = ExtrinsicBaseWeight::get();202 })203 .for_class(DispatchClass::Normal, |weights| {204 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);205 })206 .for_class(DispatchClass::Operational, |weights| {207 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);208 // Operational transactions have some extra reserved space, so that they209 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.210 weights.reserved = Some(211 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT212 );213 })214 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)215 .build_or_panic();216 pub const Version: RuntimeVersion = VERSION;217 pub const SS58Prefix: u8 = 42;218}219220/*2218880 - Unique2228881 - Quartz2238882 - Opal224*/225parameter_types! {226 pub const ChainId: u64 = 8882;227}228229pub struct FixedFee;230impl FeeCalculator for FixedFee {231 fn min_gas_price() -> U256 {232 // Targeting 0.15 UNQ per transfer233 1_018_751_825_264u64.into()234 }235}236237// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case238// (contract, which only writes a lot of data),239// approximating on top of our real store write weight240parameter_types! {241 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;242 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;243 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();244}245246/// Limiting EVM execution to 50% of block for substrate users and management tasks247/// EVM transaction consumes more weight than substrate's, so we can't rely on them being248/// scheduled fairly249const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);250parameter_types! {251 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());252}253254pub enum FixedGasWeightMapping {}255impl GasWeightMapping for FixedGasWeightMapping {256 fn gas_to_weight(gas: u64) -> Weight {257 gas.saturating_mul(WeightPerGas::get())258 }259 fn weight_to_gas(weight: Weight) -> u64 {260 weight / WeightPerGas::get()261 }262}263264impl pallet_evm::Config for Runtime {265 type BlockGasLimit = BlockGasLimit;266 type FeeCalculator = FixedFee;267 type GasWeightMapping = FixedGasWeightMapping;268 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;269 type CallOrigin = EnsureAddressTruncated;270 type WithdrawOrigin = EnsureAddressTruncated;271 type AddressMapping = HashedAddressMapping<Self::Hashing>;272 type PrecompilesType = ();273 type PrecompilesValue = ();274 type Currency = Balances;275 type Event = Event;276 type OnMethodCall = (277 pallet_evm_migration::OnMethodCall<Self>,278 pallet_unique::UniqueErcSupport<Self>,279 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,280 );281 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;282 type ChainId = ChainId;283 type Runner = pallet_evm::runner::stack::Runner<Self>;284 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;285 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;286 type FindAuthor = EthereumFindAuthor<Aura>;287}288289impl pallet_evm_migration::Config for Runtime {290 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;291}292293pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);294impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {295 fn find_author<'a, I>(digests: I) -> Option<H160>296 where297 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,298 {299 if let Some(author_index) = F::find_author(digests) {300 let authority_id = Aura::authorities()[author_index as usize].clone();301 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));302 }303 None304 }305}306307impl pallet_ethereum::Config for Runtime {308 type Event = Event;309 type StateRoot = pallet_ethereum::IntermediateStateRoot;310}311312impl pallet_randomness_collective_flip::Config for Runtime {}313314impl frame_system::Config for Runtime {315 /// The data to be stored in an account.316 type AccountData = pallet_balances::AccountData<Balance>;317 /// The identifier used to distinguish between accounts.318 type AccountId = AccountId;319 /// The basic call filter to use in dispatchable.320 type BaseCallFilter = Everything;321 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).322 type BlockHashCount = BlockHashCount;323 /// The maximum length of a block (in bytes).324 type BlockLength = RuntimeBlockLength;325 /// The index type for blocks.326 type BlockNumber = BlockNumber;327 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.328 type BlockWeights = RuntimeBlockWeights;329 /// The aggregated dispatch type that is available for extrinsics.330 type Call = Call;331 /// The weight of database operations that the runtime can invoke.332 type DbWeight = RocksDbWeight;333 /// The ubiquitous event type.334 type Event = Event;335 /// The type for hashing blocks and tries.336 type Hash = Hash;337 /// The hashing algorithm used.338 type Hashing = BlakeTwo256;339 /// The header type.340 type Header = generic::Header<BlockNumber, BlakeTwo256>;341 /// The index type for storing how many extrinsics an account has signed.342 type Index = Index;343 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.344 type Lookup = AccountIdLookup<AccountId, ()>;345 /// What to do if an account is fully reaped from the system.346 type OnKilledAccount = ();347 /// What to do if a new account is created.348 type OnNewAccount = ();349 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;350 /// The ubiquitous origin type.351 type Origin = Origin;352 /// This type is being generated by `construct_runtime!`.353 type PalletInfo = PalletInfo;354 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.355 type SS58Prefix = SS58Prefix;356 /// Weight information for the extrinsics of this pallet.357 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;358 /// Version of the runtime.359 type Version = Version;360 type MaxConsumers = ConstU32<16>;361}362363parameter_types! {364 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;365}366367impl pallet_timestamp::Config for Runtime {368 /// A timestamp: milliseconds since the unix epoch.369 type Moment = u64;370 type OnTimestampSet = ();371 type MinimumPeriod = MinimumPeriod;372 type WeightInfo = ();373}374375parameter_types! {376 // pub const ExistentialDeposit: u128 = 500;377 pub const ExistentialDeposit: u128 = 0;378 pub const MaxLocks: u32 = 50;379}380381impl pallet_balances::Config for Runtime {382 type MaxLocks = MaxLocks;383 type MaxReserves = ();384 type ReserveIdentifier = [u8; 8];385 /// The type for recording an account's balance.386 type Balance = Balance;387 /// The ubiquitous event type.388 type Event = Event;389 type DustRemoval = Treasury;390 type ExistentialDeposit = ExistentialDeposit;391 type AccountStore = System;392 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;393}394395pub const MICROUNIQUE: Balance = 1_000_000_000_000;396pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;397pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;398pub const UNIQUE: Balance = 100 * CENTIUNIQUE;399400pub const fn deposit(items: u32, bytes: u32) -> Balance {401 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE402}403404/*405parameter_types! {406 pub TombstoneDeposit: Balance = deposit(407 1,408 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,409 );410 pub DepositPerContract: Balance = TombstoneDeposit::get();411 pub const DepositPerStorageByte: Balance = deposit(0, 1);412 pub const DepositPerStorageItem: Balance = deposit(1, 0);413 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);414 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;415 pub const SignedClaimHandicap: u32 = 2;416 pub const MaxDepth: u32 = 32;417 pub const MaxValueSize: u32 = 16 * 1024;418 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb419 // The lazy deletion runs inside on_initialize.420 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *421 RuntimeBlockWeights::get().max_block;422 // The weight needed for decoding the queue should be less or equal than a fifth423 // of the overall weight dedicated to the lazy deletion.424 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (425 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -426 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)427 )) / 5) as u32;428 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();429}430431impl pallet_contracts::Config for Runtime {432 type Time = Timestamp;433 type Randomness = RandomnessCollectiveFlip;434 type Currency = Balances;435 type Event = Event;436 type RentPayment = ();437 type SignedClaimHandicap = SignedClaimHandicap;438 type TombstoneDeposit = TombstoneDeposit;439 type DepositPerContract = DepositPerContract;440 type DepositPerStorageByte = DepositPerStorageByte;441 type DepositPerStorageItem = DepositPerStorageItem;442 type RentFraction = RentFraction;443 type SurchargeReward = SurchargeReward;444 type WeightPrice = pallet_transaction_payment::Pallet<Self>;445 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;446 type ChainExtension = NFTExtension;447 type DeletionQueueDepth = DeletionQueueDepth;448 type DeletionWeightLimit = DeletionWeightLimit;449 type Schedule = Schedule;450 type CallStack = [pallet_contracts::Frame<Self>; 31];451}452*/453454parameter_types! {455 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer456 /// This value increases the priority of `Operational` transactions by adding457 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.458 pub const OperationalFeeMultiplier: u8 = 5;459}460461/// Linear implementor of `WeightToFeePolynomial`462pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);463464impl<T> WeightToFeePolynomial for LinearFee<T>465where466 T: BaseArithmetic + From<u32> + Copy + Unsigned,467{468 type Balance = T;469470 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {471 smallvec!(WeightToFeeCoefficient {472 // Targeting 0.1 Unique per NFT transfer473 coeff_integer: 142_688_000u32.into(),474 coeff_frac: Perbill::zero(),475 negative: false,476 degree: 1,477 })478 }479}480481impl pallet_transaction_payment::Config for Runtime {482 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;483 type TransactionByteFee = TransactionByteFee;484 type OperationalFeeMultiplier = OperationalFeeMultiplier;485 type WeightToFee = LinearFee<Balance>;486 type FeeMultiplierUpdate = ();487}488489parameter_types! {490 pub const ProposalBond: Permill = Permill::from_percent(5);491 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;492 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;493 pub const SpendPeriod: BlockNumber = 5 * MINUTES;494 pub const Burn: Permill = Permill::from_percent(0);495 pub const TipCountdown: BlockNumber = 1 * DAYS;496 pub const TipFindersFee: Percent = Percent::from_percent(20);497 pub const TipReportDepositBase: Balance = 1 * UNIQUE;498 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;499 pub const BountyDepositBase: Balance = 1 * UNIQUE;500 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;501 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");502 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;503 pub const MaximumReasonLength: u32 = 16384;504 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);505 pub const BountyValueMinimum: Balance = 5 * UNIQUE;506 pub const MaxApprovals: u32 = 100;507}508509impl pallet_treasury::Config for Runtime {510 type PalletId = TreasuryModuleId;511 type Currency = Balances;512 type ApproveOrigin = EnsureRoot<AccountId>;513 type RejectOrigin = EnsureRoot<AccountId>;514 type Event = Event;515 type OnSlash = ();516 type ProposalBond = ProposalBond;517 type ProposalBondMinimum = ProposalBondMinimum;518 type ProposalBondMaximum = ProposalBondMaximum;519 type SpendPeriod = SpendPeriod;520 type Burn = Burn;521 type BurnDestination = ();522 type SpendFunds = ();523 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;524 type MaxApprovals = MaxApprovals;525}526527impl pallet_sudo::Config for Runtime {528 type Event = Event;529 type Call = Call;530}531532pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);533534impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider535 for RelayChainBlockNumberProvider<T>536{537 type BlockNumber = BlockNumber;538539 fn current_block_number() -> Self::BlockNumber {540 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()541 .map(|d| d.relay_parent_number)542 .unwrap_or_default()543 }544}545546parameter_types! {547 pub const MinVestedTransfer: Balance = 10 * UNIQUE;548 pub const MaxVestingSchedules: u32 = 28;549}550551impl orml_vesting::Config for Runtime {552 type Event = Event;553 type Currency = pallet_balances::Pallet<Runtime>;554 type MinVestedTransfer = MinVestedTransfer;555 type VestedTransferOrigin = EnsureSigned<AccountId>;556 type WeightInfo = ();557 type MaxVestingSchedules = MaxVestingSchedules;558 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;559}560561parameter_types! {562 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;563 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;564}565566impl cumulus_pallet_parachain_system::Config for Runtime {567 type Event = Event;568 type SelfParaId = parachain_info::Pallet<Self>;569 type OnSystemEvent = ();570 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<571 // MaxDownwardMessageWeight,572 // XcmExecutor<XcmConfig>,573 // Call,574 // >;575 type OutboundXcmpMessageSource = XcmpQueue;576 type DmpMessageHandler = DmpQueue;577 type ReservedDmpWeight = ReservedDmpWeight;578 type ReservedXcmpWeight = ReservedXcmpWeight;579 type XcmpMessageHandler = XcmpQueue;580}581582impl parachain_info::Config for Runtime {}583584impl cumulus_pallet_aura_ext::Config for Runtime {}585586parameter_types! {587 pub const RelayLocation: MultiLocation = MultiLocation::parent();588 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;589 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();590 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();591}592593/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used594/// when determining ownership of accounts for asset transacting and when attempting to use XCM595/// `Transact` in order to determine the dispatch Origin.596pub type LocationToAccountId = (597 // The parent (Relay-chain) origin converts to the default `AccountId`.598 ParentIsPreset<AccountId>,599 // Sibling parachain origins convert to AccountId via the `ParaId::into`.600 SiblingParachainConvertsVia<Sibling, AccountId>,601 // Straight up local `AccountId32` origins just alias directly to `AccountId`.602 AccountId32Aliases<RelayNetwork, AccountId>,603);604605pub struct OnlySelfCurrency;606impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {607 fn matches_fungible(a: &MultiAsset) -> Option<B> {608 match (&a.id, &a.fun) {609 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),610 _ => None,611 }612 }613}614615/// Means for transacting assets on this chain.616pub type LocalAssetTransactor = CurrencyAdapter<617 // Use this currency:618 Balances,619 // Use this currency when it is a fungible asset matching the given location or name:620 OnlySelfCurrency,621 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:622 LocationToAccountId,623 // Our chain's account ID type (we can't get away without mentioning it explicitly):624 AccountId,625 // We don't track any teleports.626 (),627>;628629/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,630/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can631/// biases the kind of local `Origin` it will become.632pub type XcmOriginToTransactDispatchOrigin = (633 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location634 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for635 // foreign chains who want to have a local sovereign account on this chain which they control.636 SovereignSignedViaLocation<LocationToAccountId, Origin>,637 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when638 // recognised.639 RelayChainAsNative<RelayOrigin, Origin>,640 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when641 // recognised.642 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,643 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a644 // transaction from the Root origin.645 ParentAsSuperuser<Origin>,646 // Native signed account converter; this just converts an `AccountId32` origin into a normal647 // `Origin::Signed` origin of the same 32-byte value.648 SignedAccountId32AsNative<RelayNetwork, Origin>,649 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.650 XcmPassthrough<Origin>,651);652653parameter_types! {654 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.655 pub UnitWeightCost: Weight = 1_000_000;656 // 1200 UNIQUEs buy 1 second of weight.657 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);658 pub const MaxInstructions: u32 = 100;659 pub const MaxAuthorities: u32 = 100_000;660}661662match_type! {663 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {664 MultiLocation { parents: 1, interior: Here } |665 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }666 };667}668669pub type Barrier = (670 TakeWeightCredit,671 AllowTopLevelPaidExecutionFrom<Everything>,672 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,673 // ^^^ Parent & its unit plurality gets free execution674);675676pub struct UsingOnlySelfCurrencyComponents<677 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,678 AssetId: Get<MultiLocation>,679 AccountId,680 Currency: CurrencyT<AccountId>,681 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,682>(683 Weight,684 Currency::Balance,685 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,686);687impl<688 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,689 AssetId: Get<MultiLocation>,690 AccountId,691 Currency: CurrencyT<AccountId>,692 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,693 > WeightTrader694 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>695{696 fn new() -> Self {697 Self(0, Zero::zero(), PhantomData)698 }699700 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {701 let amount = WeightToFee::calc(&weight);702 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;703704 // location to this parachain through relay chain705 let option1: xcm::v1::AssetId = Concrete(MultiLocation {706 parents: 1,707 interior: X1(Parachain(ParachainInfo::parachain_id().into())),708 });709 // direct location710 let option2: xcm::v1::AssetId = Concrete(MultiLocation {711 parents: 0,712 interior: Here,713 });714715 let required = if payment.fungible.contains_key(&option1) {716 (option1, u128_amount).into()717 } else if payment.fungible.contains_key(&option2) {718 (option2, u128_amount).into()719 } else {720 (Concrete(MultiLocation::default()), u128_amount).into()721 };722723 let unused = payment724 .checked_sub(required)725 .map_err(|_| XcmError::TooExpensive)?;726 self.0 = self.0.saturating_add(weight);727 self.1 = self.1.saturating_add(amount);728 Ok(unused)729 }730731 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {732 let weight = weight.min(self.0);733 let amount = WeightToFee::calc(&weight);734 self.0 -= weight;735 self.1 = self.1.saturating_sub(amount);736 let amount: u128 = amount.saturated_into();737 if amount > 0 {738 Some((AssetId::get(), amount).into())739 } else {740 None741 }742 }743}744impl<745 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,746 AssetId: Get<MultiLocation>,747 AccountId,748 Currency: CurrencyT<AccountId>,749 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,750 > Drop751 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>752{753 fn drop(&mut self) {754 OnUnbalanced::on_unbalanced(Currency::issue(self.1));755 }756}757758pub struct XcmConfig;759impl Config for XcmConfig {760 type Call = Call;761 type XcmSender = XcmRouter;762 // How to withdraw and deposit an asset.763 type AssetTransactor = LocalAssetTransactor;764 type OriginConverter = XcmOriginToTransactDispatchOrigin;765 type IsReserve = NativeAsset;766 type IsTeleporter = (); // Teleportation is disabled767 type LocationInverter = LocationInverter<Ancestry>;768 type Barrier = Barrier;769 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;770 type Trader = UsingOnlySelfCurrencyComponents<771 IdentityFee<Balance>,772 RelayLocation,773 AccountId,774 Balances,775 (),776 >;777 type ResponseHandler = (); // Don't handle responses for now.778 type SubscriptionService = PolkadotXcm;779780 type AssetTrap = PolkadotXcm;781 type AssetClaims = PolkadotXcm;782}783784// parameter_types! {785// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;786// }787788/// No local origins on this chain are allowed to dispatch XCM sends/executions.789pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);790791/// The means for routing XCM messages which are not for local execution into the right message792/// queues.793pub type XcmRouter = (794 // Two routers - use UMP to communicate with the relay chain:795 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,796 // ..and XCMP to communicate with the sibling chains.797 XcmpQueue,798);799800impl pallet_evm_coder_substrate::Config for Runtime {801 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;802 type GasWeightMapping = FixedGasWeightMapping;803}804805impl pallet_xcm::Config for Runtime {806 type Event = Event;807 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;808 type XcmRouter = XcmRouter;809 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;810 type XcmExecuteFilter = Everything;811 type XcmExecutor = XcmExecutor<XcmConfig>;812 type XcmTeleportFilter = Everything;813 type XcmReserveTransferFilter = Everything;814 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;815 type LocationInverter = LocationInverter<Ancestry>;816 type Origin = Origin;817 type Call = Call;818 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;819 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;820}821822impl cumulus_pallet_xcm::Config for Runtime {823 type Event = Event;824 type XcmExecutor = XcmExecutor<XcmConfig>;825}826827impl cumulus_pallet_xcmp_queue::Config for Runtime {828 type Event = Event;829 type XcmExecutor = XcmExecutor<XcmConfig>;830 type ChannelInfo = ParachainSystem;831 type VersionWrapper = ();832 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;833 type ControllerOrigin = EnsureRoot<AccountId>;834 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;835}836837impl cumulus_pallet_dmp_queue::Config for Runtime {838 type Event = Event;839 type XcmExecutor = XcmExecutor<XcmConfig>;840 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;841}842843impl pallet_aura::Config for Runtime {844 type AuthorityId = AuraId;845 type DisabledValidators = ();846 type MaxAuthorities = MaxAuthorities;847}848849parameter_types! {850 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();851 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;852}853854impl pallet_common::Config for Runtime {855 type Event = Event;856 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;857 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;858 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;859860 type Currency = Balances;861 type CollectionCreationPrice = CollectionCreationPrice;862 type TreasuryAccountId = TreasuryAccountId;863}864865impl pallet_fungible::Config for Runtime {866 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;867}868impl pallet_refungible::Config for Runtime {869 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;870}871impl pallet_nonfungible::Config for Runtime {872 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;873}874875impl pallet_unique::Config for Runtime {876 type Event = Event;877 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;878}879880parameter_types! {881 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied882}883884/// Used for the pallet inflation885impl pallet_inflation::Config for Runtime {886 type Currency = Balances;887 type TreasuryAccountId = TreasuryAccountId;888 type InflationBlockInterval = InflationBlockInterval;889 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;890}891892// parameter_types! {893// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *894// RuntimeBlockWeights::get().max_block;895// pub const MaxScheduledPerBlock: u32 = 50;896// }897898type EvmSponsorshipHandler = (899 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,900 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,901);902type SponsorshipHandler = (903 pallet_unique::UniqueSponsorshipHandler<Runtime>,904 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,905 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,906);907908// impl pallet_unq_scheduler::Config for Runtime {909// type Event = Event;910// type Origin = Origin;911// type PalletsOrigin = OriginCaller;912// type Call = Call;913// type MaximumWeight = MaximumSchedulerWeight;914// type ScheduleOrigin = EnsureSigned<AccountId>;915// type MaxScheduledPerBlock = MaxScheduledPerBlock;916// type SponsorshipHandler = SponsorshipHandler;917// type WeightInfo = ();918// }919920impl pallet_evm_transaction_payment::Config for Runtime {921 type EvmSponsorshipHandler = EvmSponsorshipHandler;922 type Currency = Balances;923 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;924 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;925}926927impl pallet_charge_transaction::Config for Runtime {928 type SponsorshipHandler = SponsorshipHandler;929}930931// impl pallet_contract_helpers::Config for Runtime {932// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;933// }934935parameter_types! {936 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049937 pub const HelpersContractAddress: H160 = H160([938 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,939 ]);940}941942impl pallet_evm_contract_helpers::Config for Runtime {943 type ContractAddress = HelpersContractAddress;944 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;945}946947construct_runtime!(948 pub enum Runtime where949 Block = Block,950 NodeBlock = opaque::Block,951 UncheckedExtrinsic = UncheckedExtrinsic952 {953 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,954 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,955956 Aura: pallet_aura::{Pallet, Config<T>} = 22,957 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,958959 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,960 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,961 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,962 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,963 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,964 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,965 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,966 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,967 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,968 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,969970 // XCM helpers.971 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,972 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,973 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,974 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,975976 // Unique Pallets977 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,978 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,979 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,980 // free = 63981 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,982 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,983 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,984 Fungible: pallet_fungible::{Pallet, Storage} = 67,985 Refungible: pallet_refungible::{Pallet, Storage} = 68,986 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,987988 // Frontier989 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,990 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,991992 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,993 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,994 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,995 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,996 }997);998999pub struct TransactionConverter;10001001impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1002 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1003 UncheckedExtrinsic::new_unsigned(1004 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1005 )1006 }1007}10081009impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1010 fn convert_transaction(1011 &self,1012 transaction: pallet_ethereum::Transaction,1013 ) -> opaque::UncheckedExtrinsic {1014 let extrinsic = UncheckedExtrinsic::new_unsigned(1015 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1016 );1017 let encoded = extrinsic.encode();1018 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1019 .expect("Encoded extrinsic is always valid")1020 }1021}10221023/// The address format for describing accounts.1024pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1025/// Block header type as expected by this runtime.1026pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1027/// Block type as expected by this runtime.1028pub type Block = generic::Block<Header, UncheckedExtrinsic>;1029/// A Block signed with a Justification1030pub type SignedBlock = generic::SignedBlock<Block>;1031/// BlockId type as expected by this runtime.1032pub type BlockId = generic::BlockId<Block>;1033/// The SignedExtension to the basic transaction logic.1034pub type SignedExtra = (1035 frame_system::CheckSpecVersion<Runtime>,1036 // system::CheckTxVersion<Runtime>,1037 frame_system::CheckGenesis<Runtime>,1038 frame_system::CheckEra<Runtime>,1039 frame_system::CheckNonce<Runtime>,1040 frame_system::CheckWeight<Runtime>,1041 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1042 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1043);1044/// Unchecked extrinsic type as expected by this runtime.1045pub type UncheckedExtrinsic =1046 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1047/// Extrinsic type that has already been checked.1048pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1049/// Executive: handles dispatch to the various modules.1050pub type Executive = frame_executive::Executive<1051 Runtime,1052 Block,1053 frame_system::ChainContext<Runtime>,1054 Runtime,1055 AllPalletsReversedWithSystemFirst,1056>;10571058impl_opaque_keys! {1059 pub struct SessionKeys {1060 pub aura: Aura,1061 }1062}10631064impl fp_self_contained::SelfContainedCall for Call {1065 type SignedInfo = H160;10661067 fn is_self_contained(&self) -> bool {1068 match self {1069 Call::Ethereum(call) => call.is_self_contained(),1070 _ => false,1071 }1072 }10731074 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1075 match self {1076 Call::Ethereum(call) => call.check_self_contained(),1077 _ => None,1078 }1079 }10801081 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1082 match self {1083 Call::Ethereum(call) => call.validate_self_contained(info),1084 _ => None,1085 }1086 }10871088 fn pre_dispatch_self_contained(1089 &self,1090 info: &Self::SignedInfo,1091 ) -> Option<Result<(), TransactionValidityError>> {1092 match self {1093 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1094 _ => None,1095 }1096 }10971098 fn apply_self_contained(1099 self,1100 info: Self::SignedInfo,1101 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1102 match self {1103 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1104 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1105 )),1106 _ => None,1107 }1108 }1109}11101111macro_rules! dispatch_unique_runtime {1112 ($collection:ident.$method:ident($($name:ident),*)) => {{1113 use pallet_unique::dispatch::Dispatched;11141115 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1116 let dispatch = collection.as_dyn();11171118 Ok(dispatch.$method($($name),*))1119 }};1120}1121impl_runtime_apis! {1122 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1123 for Runtime1124 {1125 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1126 dispatch_unique_runtime!(collection.account_tokens(account))1127 }1128 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1129 dispatch_unique_runtime!(collection.token_exists(token))1130 }11311132 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1133 dispatch_unique_runtime!(collection.token_owner(token))1134 }1135 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1136 dispatch_unique_runtime!(collection.const_metadata(token))1137 }1138 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1139 dispatch_unique_runtime!(collection.variable_metadata(token))1140 }11411142 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1143 dispatch_unique_runtime!(collection.collection_tokens())1144 }1145 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1146 dispatch_unique_runtime!(collection.account_balance(account))1147 }1148 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1149 dispatch_unique_runtime!(collection.balance(account, token))1150 }1151 fn allowance(1152 collection: CollectionId,1153 sender: CrossAccountId,1154 spender: CrossAccountId,1155 token: TokenId,1156 ) -> Result<u128, DispatchError> {1157 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1158 }11591160 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1161 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1162 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1163 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1164 }1165 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1166 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1167 }1168 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1169 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1170 }1171 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1172 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1173 }1174 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1175 dispatch_unique_runtime!(collection.last_token_id())1176 }1177 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1178 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1179 }1180 fn collection_stats() -> Result<CollectionStats, DispatchError> {1181 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1182 }1183 }11841185 impl sp_api::Core<Block> for Runtime {1186 fn version() -> RuntimeVersion {1187 VERSION1188 }11891190 fn execute_block(block: Block) {1191 Executive::execute_block(block)1192 }11931194 fn initialize_block(header: &<Block as BlockT>::Header) {1195 Executive::initialize_block(header)1196 }1197 }11981199 impl sp_api::Metadata<Block> for Runtime {1200 fn metadata() -> OpaqueMetadata {1201 OpaqueMetadata::new(Runtime::metadata().into())1202 }1203 }12041205 impl sp_block_builder::BlockBuilder<Block> for Runtime {1206 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1207 Executive::apply_extrinsic(extrinsic)1208 }12091210 fn finalize_block() -> <Block as BlockT>::Header {1211 Executive::finalize_block()1212 }12131214 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1215 data.create_extrinsics()1216 }12171218 fn check_inherents(1219 block: Block,1220 data: sp_inherents::InherentData,1221 ) -> sp_inherents::CheckInherentsResult {1222 data.check_extrinsics(&block)1223 }12241225 // fn random_seed() -> <Block as BlockT>::Hash {1226 // RandomnessCollectiveFlip::random_seed().01227 // }1228 }12291230 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1231 fn validate_transaction(1232 source: TransactionSource,1233 tx: <Block as BlockT>::Extrinsic,1234 hash: <Block as BlockT>::Hash,1235 ) -> TransactionValidity {1236 Executive::validate_transaction(source, tx, hash)1237 }1238 }12391240 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1241 fn offchain_worker(header: &<Block as BlockT>::Header) {1242 Executive::offchain_worker(header)1243 }1244 }12451246 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1247 fn chain_id() -> u64 {1248 <Runtime as pallet_evm::Config>::ChainId::get()1249 }12501251 fn account_basic(address: H160) -> EVMAccount {1252 EVM::account_basic(&address)1253 }12541255 fn gas_price() -> U256 {1256 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1257 }12581259 fn account_code_at(address: H160) -> Vec<u8> {1260 EVM::account_codes(address)1261 }12621263 fn author() -> H160 {1264 <pallet_evm::Pallet<Runtime>>::find_author()1265 }12661267 fn storage_at(address: H160, index: U256) -> H256 {1268 let mut tmp = [0u8; 32];1269 index.to_big_endian(&mut tmp);1270 EVM::account_storages(address, H256::from_slice(&tmp[..]))1271 }12721273 #[allow(clippy::redundant_closure)]1274 fn call(1275 from: H160,1276 to: H160,1277 data: Vec<u8>,1278 value: U256,1279 gas_limit: U256,1280 max_fee_per_gas: Option<U256>,1281 max_priority_fee_per_gas: Option<U256>,1282 nonce: Option<U256>,1283 estimate: bool,1284 access_list: Option<Vec<(H160, Vec<H256>)>>,1285 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1286 let config = if estimate {1287 let mut config = <Runtime as pallet_evm::Config>::config().clone();1288 config.estimate = true;1289 Some(config)1290 } else {1291 None1292 };12931294 <Runtime as pallet_evm::Config>::Runner::call(1295 from,1296 to,1297 data,1298 value,1299 gas_limit.low_u64(),1300 max_fee_per_gas,1301 max_priority_fee_per_gas,1302 nonce,1303 access_list.unwrap_or_default(),1304 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1305 ).map_err(|err| err.into())1306 }13071308 #[allow(clippy::redundant_closure)]1309 fn create(1310 from: H160,1311 data: Vec<u8>,1312 value: U256,1313 gas_limit: U256,1314 max_fee_per_gas: Option<U256>,1315 max_priority_fee_per_gas: Option<U256>,1316 nonce: Option<U256>,1317 estimate: bool,1318 access_list: Option<Vec<(H160, Vec<H256>)>>,1319 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1320 let config = if estimate {1321 let mut config = <Runtime as pallet_evm::Config>::config().clone();1322 config.estimate = true;1323 Some(config)1324 } else {1325 None1326 };13271328 <Runtime as pallet_evm::Config>::Runner::create(1329 from,1330 data,1331 value,1332 gas_limit.low_u64(),1333 max_fee_per_gas,1334 max_priority_fee_per_gas,1335 nonce,1336 access_list.unwrap_or_default(),1337 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1338 ).map_err(|err| err.into())1339 }13401341 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1342 Ethereum::current_transaction_statuses()1343 }13441345 fn current_block() -> Option<pallet_ethereum::Block> {1346 Ethereum::current_block()1347 }13481349 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1350 Ethereum::current_receipts()1351 }13521353 fn current_all() -> (1354 Option<pallet_ethereum::Block>,1355 Option<Vec<pallet_ethereum::Receipt>>,1356 Option<Vec<TransactionStatus>>1357 ) {1358 (1359 Ethereum::current_block(),1360 Ethereum::current_receipts(),1361 Ethereum::current_transaction_statuses()1362 )1363 }13641365 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1366 xts.into_iter().filter_map(|xt| match xt.0.function {1367 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1368 _ => None1369 }).collect()1370 }13711372 fn elasticity() -> Option<Permill> {1373 None1374 }1375 }13761377 impl sp_session::SessionKeys<Block> for Runtime {1378 fn decode_session_keys(1379 encoded: Vec<u8>,1380 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1381 SessionKeys::decode_into_raw_public_keys(&encoded)1382 }13831384 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1385 SessionKeys::generate(seed)1386 }1387 }13881389 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1390 fn slot_duration() -> sp_consensus_aura::SlotDuration {1391 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1392 }13931394 fn authorities() -> Vec<AuraId> {1395 Aura::authorities().to_vec()1396 }1397 }13981399 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1400 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1401 ParachainSystem::collect_collation_info(header)1402 }1403 }14041405 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1406 fn account_nonce(account: AccountId) -> Index {1407 System::account_nonce(account)1408 }1409 }14101411 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1412 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1413 TransactionPayment::query_info(uxt, len)1414 }1415 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1416 TransactionPayment::query_fee_details(uxt, len)1417 }1418 }14191420 /*1421 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1422 for Runtime1423 {1424 fn call(1425 origin: AccountId,1426 dest: AccountId,1427 value: Balance,1428 gas_limit: u64,1429 input_data: Vec<u8>,1430 ) -> pallet_contracts_primitives::ContractExecResult {1431 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1432 }14331434 fn instantiate(1435 origin: AccountId,1436 endowment: Balance,1437 gas_limit: u64,1438 code: pallet_contracts_primitives::Code<Hash>,1439 data: Vec<u8>,1440 salt: Vec<u8>,1441 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1442 {1443 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1444 }14451446 fn get_storage(1447 address: AccountId,1448 key: [u8; 32],1449 ) -> pallet_contracts_primitives::GetStorageResult {1450 Contracts::get_storage(address, key)1451 }14521453 fn rent_projection(1454 address: AccountId,1455 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1456 Contracts::rent_projection(address)1457 }1458 }1459 */14601461 #[cfg(feature = "runtime-benchmarks")]1462 impl frame_benchmarking::Benchmark<Block> for Runtime {1463 fn benchmark_metadata(extra: bool) -> (1464 Vec<frame_benchmarking::BenchmarkList>,1465 Vec<frame_support::traits::StorageInfo>,1466 ) {1467 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1468 use frame_support::traits::StorageInfoTrait;14691470 let mut list = Vec::<BenchmarkList>::new();14711472 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1473 list_benchmark!(list, extra, pallet_unique, Unique);1474 list_benchmark!(list, extra, pallet_inflation, Inflation);1475 list_benchmark!(list, extra, pallet_fungible, Fungible);1476 list_benchmark!(list, extra, pallet_refungible, Refungible);1477 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1478 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);14791480 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();14811482 return (list, storage_info)1483 }14841485 fn dispatch_benchmark(1486 config: frame_benchmarking::BenchmarkConfig1487 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1488 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};14891490 let allowlist: Vec<TrackedStorageKey> = vec![1491 // Block Number1492 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1493 // Total Issuance1494 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1495 // Execution Phase1496 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1497 // Event Count1498 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1499 // System Events1500 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1501 ];15021503 let mut batches = Vec::<BenchmarkBatch>::new();1504 let params = (&config, &allowlist);15051506 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1507 add_benchmark!(params, batches, pallet_unique, Unique);1508 add_benchmark!(params, batches, pallet_inflation, Inflation);1509 add_benchmark!(params, batches, pallet_fungible, Fungible);1510 add_benchmark!(params, batches, pallet_refungible, Refungible);1511 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1512 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);15131514 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1515 Ok(batches)1516 }1517 }1518}15191520struct CheckInherents;15211522impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1523 fn check_inherents(1524 block: &Block,1525 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1526 ) -> sp_inherents::CheckInherentsResult {1527 let relay_chain_slot = relay_state_proof1528 .read_slot()1529 .expect("Could not read the relay chain slot from the proof");15301531 let inherent_data =1532 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1533 relay_chain_slot,1534 sp_std::time::Duration::from_secs(6),1535 )1536 .create_inherent_data()1537 .expect("Could not create the timestamp inherent data");15381539 inherent_data.check_extrinsics(block)1540 }1541}15421543cumulus_pallet_parachain_system::register_validate_block!(1544 Runtime = Runtime,1545 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1546 CheckInherents = CheckInherents,1547);1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{37 AccountIdLookup, BlakeTwo256, Block as BlockT,38 AccountIdConversion, Zero,39 },40 transaction_validity::{TransactionSource, TransactionValidity},41 ApplyExtrinsicResult, RuntimeAppPublic,42};4344use sp_std::prelude::*;4546#[cfg(feature = "std")]47use sp_version::NativeVersion;48use sp_version::RuntimeVersion;49pub use pallet_transaction_payment::{50 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,51};52// A few exports that help ease life for downstream crates.53pub use pallet_balances::Call as BalancesCall;54pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};55pub use frame_support::{56 construct_runtime, match_type,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,68 },69};70use up_data_structs::*;71// use pallet_contracts::weights::WeightInfo;72// #[cfg(any(feature = "std", test))]73use frame_system::{74 self as frame_system, EnsureRoot, EnsureSigned,75 limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78 traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use codec::{Encode, Decode};82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;91pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9293// Polkadot imports94use pallet_xcm::XcmPassthrough;95use polkadot_parachain::primitives::Sibling;96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 types::*,120 constants::*,121};122123// mod chain_extension;124// use crate::chain_extension::{NFTExtension, Imbalance};125126pub const RUNTIME_NAME: &'static str = "Opal";127128pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;129130/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know131/// the specifics of the runtime. They can then be made to be agnostic over specific formats132/// of data like extrinsics, allowing for them to continue syncing the network through upgrades133/// to even the core data structures.134pub mod opaque {135 use sp_std::prelude::*;136 use sp_runtime::impl_opaque_keys;137 use super::Aura;138139 pub use unique_runtime_common::types::*;140 pub use super::CrossAccountId;141142 impl_opaque_keys! {143 pub struct SessionKeys {144 pub aura: Aura,145 }146 }147}148149/// This runtime version.150pub const VERSION: RuntimeVersion = RuntimeVersion {151 spec_name: create_runtime_str!("opal"),152 impl_name: create_runtime_str!("opal"),153 authoring_version: 1,154 spec_version: 917004,155 impl_version: 0,156 apis: RUNTIME_API_VERSIONS,157 transaction_version: 1,158 state_version: 0,159};160161#[derive(codec::Encode, codec::Decode)]162pub enum XCMPMessage<XAccountId, XBalance> {163 /// Transfer tokens to the given account from the Parachain account.164 TransferToken(XAccountId, XBalance),165}166167/// The version information used to identify this runtime when compiled natively.168#[cfg(feature = "std")]169pub fn native_version() -> NativeVersion {170 NativeVersion {171 runtime_version: VERSION,172 can_author_with: Default::default(),173 }174}175176type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;177178pub struct DealWithFees;179impl OnUnbalanced<NegativeImbalance> for DealWithFees {180 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {181 if let Some(fees) = fees_then_tips.next() {182 // for fees, 100% to treasury183 let mut split = fees.ration(100, 0);184 if let Some(tips) = fees_then_tips.next() {185 // for tips, if any, 100% to treasury186 tips.ration_merge_into(100, 0, &mut split);187 }188 Treasury::on_unbalanced(split.0);189 // Author::on_unbalanced(split.1);190 }191 }192}193194parameter_types! {195 pub const BlockHashCount: BlockNumber = 2400;196 pub RuntimeBlockLength: BlockLength =197 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);198 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);199 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;200 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()201 .base_block(BlockExecutionWeight::get())202 .for_class(DispatchClass::all(), |weights| {203 weights.base_extrinsic = ExtrinsicBaseWeight::get();204 })205 .for_class(DispatchClass::Normal, |weights| {206 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);207 })208 .for_class(DispatchClass::Operational, |weights| {209 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);210 // Operational transactions have some extra reserved space, so that they211 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.212 weights.reserved = Some(213 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT214 );215 })216 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)217 .build_or_panic();218 pub const Version: RuntimeVersion = VERSION;219 pub const SS58Prefix: u8 = 42;220}221222/*2238880 - Unique2248881 - Quartz2258882 - Opal226*/227parameter_types! {228 pub const ChainId: u64 = 8882;229}230231pub struct FixedFee;232impl FeeCalculator for FixedFee {233 fn min_gas_price() -> U256 {234 // Targeting 0.15 UNQ per transfer235 1_018_751_825_264u64.into()236 }237}238239// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case240// (contract, which only writes a lot of data),241// approximating on top of our real store write weight242parameter_types! {243 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;244 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;245 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();246}247248/// Limiting EVM execution to 50% of block for substrate users and management tasks249/// EVM transaction consumes more weight than substrate's, so we can't rely on them being250/// scheduled fairly251const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);252parameter_types! {253 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());254}255256pub enum FixedGasWeightMapping {}257impl GasWeightMapping for FixedGasWeightMapping {258 fn gas_to_weight(gas: u64) -> Weight {259 gas.saturating_mul(WeightPerGas::get())260 }261 fn weight_to_gas(weight: Weight) -> u64 {262 weight / WeightPerGas::get()263 }264}265266impl pallet_evm::Config for Runtime {267 type BlockGasLimit = BlockGasLimit;268 type FeeCalculator = FixedFee;269 type GasWeightMapping = FixedGasWeightMapping;270 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;271 type CallOrigin = EnsureAddressTruncated;272 type WithdrawOrigin = EnsureAddressTruncated;273 type AddressMapping = HashedAddressMapping<Self::Hashing>;274 type PrecompilesType = ();275 type PrecompilesValue = ();276 type Currency = Balances;277 type Event = Event;278 type OnMethodCall = (279 pallet_evm_migration::OnMethodCall<Self>,280 pallet_unique::UniqueErcSupport<Self>,281 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,282 );283 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;284 type ChainId = ChainId;285 type Runner = pallet_evm::runner::stack::Runner<Self>;286 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;287 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;288 type FindAuthor = EthereumFindAuthor<Aura>;289}290291impl pallet_evm_migration::Config for Runtime {292 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;293}294295pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);296impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {297 fn find_author<'a, I>(digests: I) -> Option<H160>298 where299 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,300 {301 if let Some(author_index) = F::find_author(digests) {302 let authority_id = Aura::authorities()[author_index as usize].clone();303 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));304 }305 None306 }307}308309impl pallet_ethereum::Config for Runtime {310 type Event = Event;311 type StateRoot = pallet_ethereum::IntermediateStateRoot;312}313314impl pallet_randomness_collective_flip::Config for Runtime {}315316impl frame_system::Config for Runtime {317 /// The data to be stored in an account.318 type AccountData = pallet_balances::AccountData<Balance>;319 /// The identifier used to distinguish between accounts.320 type AccountId = AccountId;321 /// The basic call filter to use in dispatchable.322 type BaseCallFilter = Everything;323 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).324 type BlockHashCount = BlockHashCount;325 /// The maximum length of a block (in bytes).326 type BlockLength = RuntimeBlockLength;327 /// The index type for blocks.328 type BlockNumber = BlockNumber;329 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.330 type BlockWeights = RuntimeBlockWeights;331 /// The aggregated dispatch type that is available for extrinsics.332 type Call = Call;333 /// The weight of database operations that the runtime can invoke.334 type DbWeight = RocksDbWeight;335 /// The ubiquitous event type.336 type Event = Event;337 /// The type for hashing blocks and tries.338 type Hash = Hash;339 /// The hashing algorithm used.340 type Hashing = BlakeTwo256;341 /// The header type.342 type Header = generic::Header<BlockNumber, BlakeTwo256>;343 /// The index type for storing how many extrinsics an account has signed.344 type Index = Index;345 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.346 type Lookup = AccountIdLookup<AccountId, ()>;347 /// What to do if an account is fully reaped from the system.348 type OnKilledAccount = ();349 /// What to do if a new account is created.350 type OnNewAccount = ();351 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;352 /// The ubiquitous origin type.353 type Origin = Origin;354 /// This type is being generated by `construct_runtime!`.355 type PalletInfo = PalletInfo;356 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.357 type SS58Prefix = SS58Prefix;358 /// Weight information for the extrinsics of this pallet.359 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;360 /// Version of the runtime.361 type Version = Version;362 type MaxConsumers = ConstU32<16>;363}364365parameter_types! {366 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;367}368369impl pallet_timestamp::Config for Runtime {370 /// A timestamp: milliseconds since the unix epoch.371 type Moment = u64;372 type OnTimestampSet = ();373 type MinimumPeriod = MinimumPeriod;374 type WeightInfo = ();375}376377parameter_types! {378 // pub const ExistentialDeposit: u128 = 500;379 pub const ExistentialDeposit: u128 = 0;380 pub const MaxLocks: u32 = 50;381}382383impl pallet_balances::Config for Runtime {384 type MaxLocks = MaxLocks;385 type MaxReserves = ();386 type ReserveIdentifier = [u8; 8];387 /// The type for recording an account's balance.388 type Balance = Balance;389 /// The ubiquitous event type.390 type Event = Event;391 type DustRemoval = Treasury;392 type ExistentialDeposit = ExistentialDeposit;393 type AccountStore = System;394 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;395}396397pub const MICROUNIQUE: Balance = 1_000_000_000_000;398pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;399pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;400pub const UNIQUE: Balance = 100 * CENTIUNIQUE;401402pub const fn deposit(items: u32, bytes: u32) -> Balance {403 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE404}405406/*407parameter_types! {408 pub TombstoneDeposit: Balance = deposit(409 1,410 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,411 );412 pub DepositPerContract: Balance = TombstoneDeposit::get();413 pub const DepositPerStorageByte: Balance = deposit(0, 1);414 pub const DepositPerStorageItem: Balance = deposit(1, 0);415 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);416 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;417 pub const SignedClaimHandicap: u32 = 2;418 pub const MaxDepth: u32 = 32;419 pub const MaxValueSize: u32 = 16 * 1024;420 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb421 // The lazy deletion runs inside on_initialize.422 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *423 RuntimeBlockWeights::get().max_block;424 // The weight needed for decoding the queue should be less or equal than a fifth425 // of the overall weight dedicated to the lazy deletion.426 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (427 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -428 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)429 )) / 5) as u32;430 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();431}432433impl pallet_contracts::Config for Runtime {434 type Time = Timestamp;435 type Randomness = RandomnessCollectiveFlip;436 type Currency = Balances;437 type Event = Event;438 type RentPayment = ();439 type SignedClaimHandicap = SignedClaimHandicap;440 type TombstoneDeposit = TombstoneDeposit;441 type DepositPerContract = DepositPerContract;442 type DepositPerStorageByte = DepositPerStorageByte;443 type DepositPerStorageItem = DepositPerStorageItem;444 type RentFraction = RentFraction;445 type SurchargeReward = SurchargeReward;446 type WeightPrice = pallet_transaction_payment::Pallet<Self>;447 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;448 type ChainExtension = NFTExtension;449 type DeletionQueueDepth = DeletionQueueDepth;450 type DeletionWeightLimit = DeletionWeightLimit;451 type Schedule = Schedule;452 type CallStack = [pallet_contracts::Frame<Self>; 31];453}454*/455456parameter_types! {457 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer458 /// This value increases the priority of `Operational` transactions by adding459 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.460 pub const OperationalFeeMultiplier: u8 = 5;461}462463/// Linear implementor of `WeightToFeePolynomial`464pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);465466impl<T> WeightToFeePolynomial for LinearFee<T>467where468 T: BaseArithmetic + From<u32> + Copy + Unsigned,469{470 type Balance = T;471472 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {473 smallvec!(WeightToFeeCoefficient {474 // Targeting 0.1 Unique per NFT transfer475 coeff_integer: 142_688_000u32.into(),476 coeff_frac: Perbill::zero(),477 negative: false,478 degree: 1,479 })480 }481}482483impl pallet_transaction_payment::Config for Runtime {484 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;485 type TransactionByteFee = TransactionByteFee;486 type OperationalFeeMultiplier = OperationalFeeMultiplier;487 type WeightToFee = LinearFee<Balance>;488 type FeeMultiplierUpdate = ();489}490491parameter_types! {492 pub const ProposalBond: Permill = Permill::from_percent(5);493 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;494 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;495 pub const SpendPeriod: BlockNumber = 5 * MINUTES;496 pub const Burn: Permill = Permill::from_percent(0);497 pub const TipCountdown: BlockNumber = 1 * DAYS;498 pub const TipFindersFee: Percent = Percent::from_percent(20);499 pub const TipReportDepositBase: Balance = 1 * UNIQUE;500 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;501 pub const BountyDepositBase: Balance = 1 * UNIQUE;502 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;503 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");504 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;505 pub const MaximumReasonLength: u32 = 16384;506 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);507 pub const BountyValueMinimum: Balance = 5 * UNIQUE;508 pub const MaxApprovals: u32 = 100;509}510511impl pallet_treasury::Config for Runtime {512 type PalletId = TreasuryModuleId;513 type Currency = Balances;514 type ApproveOrigin = EnsureRoot<AccountId>;515 type RejectOrigin = EnsureRoot<AccountId>;516 type Event = Event;517 type OnSlash = ();518 type ProposalBond = ProposalBond;519 type ProposalBondMinimum = ProposalBondMinimum;520 type ProposalBondMaximum = ProposalBondMaximum;521 type SpendPeriod = SpendPeriod;522 type Burn = Burn;523 type BurnDestination = ();524 type SpendFunds = ();525 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;526 type MaxApprovals = MaxApprovals;527}528529impl pallet_sudo::Config for Runtime {530 type Event = Event;531 type Call = Call;532}533534pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);535536impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider537 for RelayChainBlockNumberProvider<T>538{539 type BlockNumber = BlockNumber;540541 fn current_block_number() -> Self::BlockNumber {542 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()543 .map(|d| d.relay_parent_number)544 .unwrap_or_default()545 }546}547548parameter_types! {549 pub const MinVestedTransfer: Balance = 10 * UNIQUE;550 pub const MaxVestingSchedules: u32 = 28;551}552553impl orml_vesting::Config for Runtime {554 type Event = Event;555 type Currency = pallet_balances::Pallet<Runtime>;556 type MinVestedTransfer = MinVestedTransfer;557 type VestedTransferOrigin = EnsureSigned<AccountId>;558 type WeightInfo = ();559 type MaxVestingSchedules = MaxVestingSchedules;560 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;561}562563parameter_types! {564 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;565 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;566}567568impl cumulus_pallet_parachain_system::Config for Runtime {569 type Event = Event;570 type SelfParaId = parachain_info::Pallet<Self>;571 type OnSystemEvent = ();572 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<573 // MaxDownwardMessageWeight,574 // XcmExecutor<XcmConfig>,575 // Call,576 // >;577 type OutboundXcmpMessageSource = XcmpQueue;578 type DmpMessageHandler = DmpQueue;579 type ReservedDmpWeight = ReservedDmpWeight;580 type ReservedXcmpWeight = ReservedXcmpWeight;581 type XcmpMessageHandler = XcmpQueue;582}583584impl parachain_info::Config for Runtime {}585586impl cumulus_pallet_aura_ext::Config for Runtime {}587588parameter_types! {589 pub const RelayLocation: MultiLocation = MultiLocation::parent();590 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;591 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();592 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();593}594595/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used596/// when determining ownership of accounts for asset transacting and when attempting to use XCM597/// `Transact` in order to determine the dispatch Origin.598pub type LocationToAccountId = (599 // The parent (Relay-chain) origin converts to the default `AccountId`.600 ParentIsPreset<AccountId>,601 // Sibling parachain origins convert to AccountId via the `ParaId::into`.602 SiblingParachainConvertsVia<Sibling, AccountId>,603 // Straight up local `AccountId32` origins just alias directly to `AccountId`.604 AccountId32Aliases<RelayNetwork, AccountId>,605);606607pub struct OnlySelfCurrency;608impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {609 fn matches_fungible(a: &MultiAsset) -> Option<B> {610 match (&a.id, &a.fun) {611 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),612 _ => None,613 }614 }615}616617/// Means for transacting assets on this chain.618pub type LocalAssetTransactor = CurrencyAdapter<619 // Use this currency:620 Balances,621 // Use this currency when it is a fungible asset matching the given location or name:622 OnlySelfCurrency,623 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:624 LocationToAccountId,625 // Our chain's account ID type (we can't get away without mentioning it explicitly):626 AccountId,627 // We don't track any teleports.628 (),629>;630631/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,632/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can633/// biases the kind of local `Origin` it will become.634pub type XcmOriginToTransactDispatchOrigin = (635 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location636 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for637 // foreign chains who want to have a local sovereign account on this chain which they control.638 SovereignSignedViaLocation<LocationToAccountId, Origin>,639 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when640 // recognised.641 RelayChainAsNative<RelayOrigin, Origin>,642 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when643 // recognised.644 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,645 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a646 // transaction from the Root origin.647 ParentAsSuperuser<Origin>,648 // Native signed account converter; this just converts an `AccountId32` origin into a normal649 // `Origin::Signed` origin of the same 32-byte value.650 SignedAccountId32AsNative<RelayNetwork, Origin>,651 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.652 XcmPassthrough<Origin>,653);654655parameter_types! {656 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.657 pub UnitWeightCost: Weight = 1_000_000;658 // 1200 UNIQUEs buy 1 second of weight.659 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);660 pub const MaxInstructions: u32 = 100;661 pub const MaxAuthorities: u32 = 100_000;662}663664match_type! {665 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {666 MultiLocation { parents: 1, interior: Here } |667 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }668 };669}670671pub type Barrier = (672 TakeWeightCredit,673 AllowTopLevelPaidExecutionFrom<Everything>,674 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,675 // ^^^ Parent & its unit plurality gets free execution676);677678pub struct UsingOnlySelfCurrencyComponents<679 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,680 AssetId: Get<MultiLocation>,681 AccountId,682 Currency: CurrencyT<AccountId>,683 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,684>(685 Weight,686 Currency::Balance,687 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,688);689impl<690 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,691 AssetId: Get<MultiLocation>,692 AccountId,693 Currency: CurrencyT<AccountId>,694 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,695 > WeightTrader696 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>697{698 fn new() -> Self {699 Self(0, Zero::zero(), PhantomData)700 }701702 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {703 let amount = WeightToFee::calc(&weight);704 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;705706 // location to this parachain through relay chain707 let option1: xcm::v1::AssetId = Concrete(MultiLocation {708 parents: 1,709 interior: X1(Parachain(ParachainInfo::parachain_id().into())),710 });711 // direct location712 let option2: xcm::v1::AssetId = Concrete(MultiLocation {713 parents: 0,714 interior: Here,715 });716717 let required = if payment.fungible.contains_key(&option1) {718 (option1, u128_amount).into()719 } else if payment.fungible.contains_key(&option2) {720 (option2, u128_amount).into()721 } else {722 (Concrete(MultiLocation::default()), u128_amount).into()723 };724725 let unused = payment726 .checked_sub(required)727 .map_err(|_| XcmError::TooExpensive)?;728 self.0 = self.0.saturating_add(weight);729 self.1 = self.1.saturating_add(amount);730 Ok(unused)731 }732733 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {734 let weight = weight.min(self.0);735 let amount = WeightToFee::calc(&weight);736 self.0 -= weight;737 self.1 = self.1.saturating_sub(amount);738 let amount: u128 = amount.saturated_into();739 if amount > 0 {740 Some((AssetId::get(), amount).into())741 } else {742 None743 }744 }745}746impl<747 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,748 AssetId: Get<MultiLocation>,749 AccountId,750 Currency: CurrencyT<AccountId>,751 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,752 > Drop753 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>754{755 fn drop(&mut self) {756 OnUnbalanced::on_unbalanced(Currency::issue(self.1));757 }758}759760pub struct XcmConfig;761impl Config for XcmConfig {762 type Call = Call;763 type XcmSender = XcmRouter;764 // How to withdraw and deposit an asset.765 type AssetTransactor = LocalAssetTransactor;766 type OriginConverter = XcmOriginToTransactDispatchOrigin;767 type IsReserve = NativeAsset;768 type IsTeleporter = (); // Teleportation is disabled769 type LocationInverter = LocationInverter<Ancestry>;770 type Barrier = Barrier;771 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;772 type Trader = UsingOnlySelfCurrencyComponents<773 IdentityFee<Balance>,774 RelayLocation,775 AccountId,776 Balances,777 (),778 >;779 type ResponseHandler = (); // Don't handle responses for now.780 type SubscriptionService = PolkadotXcm;781782 type AssetTrap = PolkadotXcm;783 type AssetClaims = PolkadotXcm;784}785786// parameter_types! {787// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;788// }789790/// No local origins on this chain are allowed to dispatch XCM sends/executions.791pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);792793/// The means for routing XCM messages which are not for local execution into the right message794/// queues.795pub type XcmRouter = (796 // Two routers - use UMP to communicate with the relay chain:797 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,798 // ..and XCMP to communicate with the sibling chains.799 XcmpQueue,800);801802impl pallet_evm_coder_substrate::Config for Runtime {803 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;804 type GasWeightMapping = FixedGasWeightMapping;805}806807impl pallet_xcm::Config for Runtime {808 type Event = Event;809 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;810 type XcmRouter = XcmRouter;811 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;812 type XcmExecuteFilter = Everything;813 type XcmExecutor = XcmExecutor<XcmConfig>;814 type XcmTeleportFilter = Everything;815 type XcmReserveTransferFilter = Everything;816 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;817 type LocationInverter = LocationInverter<Ancestry>;818 type Origin = Origin;819 type Call = Call;820 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;821 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;822}823824impl cumulus_pallet_xcm::Config for Runtime {825 type Event = Event;826 type XcmExecutor = XcmExecutor<XcmConfig>;827}828829impl cumulus_pallet_xcmp_queue::Config for Runtime {830 type Event = Event;831 type XcmExecutor = XcmExecutor<XcmConfig>;832 type ChannelInfo = ParachainSystem;833 type VersionWrapper = ();834 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;835 type ControllerOrigin = EnsureRoot<AccountId>;836 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;837}838839impl cumulus_pallet_dmp_queue::Config for Runtime {840 type Event = Event;841 type XcmExecutor = XcmExecutor<XcmConfig>;842 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;843}844845impl pallet_aura::Config for Runtime {846 type AuthorityId = AuraId;847 type DisabledValidators = ();848 type MaxAuthorities = MaxAuthorities;849}850851parameter_types! {852 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();853 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;854}855856impl pallet_common::Config for Runtime {857 type Event = Event;858 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;859 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;860 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;861862 type Currency = Balances;863 type CollectionCreationPrice = CollectionCreationPrice;864 type TreasuryAccountId = TreasuryAccountId;865}866867impl pallet_fungible::Config for Runtime {868 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;869}870impl pallet_refungible::Config for Runtime {871 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;872}873impl pallet_nonfungible::Config for Runtime {874 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;875}876877impl pallet_unique::Config for Runtime {878 type Event = Event;879 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;880}881882parameter_types! {883 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied884}885886/// Used for the pallet inflation887impl pallet_inflation::Config for Runtime {888 type Currency = Balances;889 type TreasuryAccountId = TreasuryAccountId;890 type InflationBlockInterval = InflationBlockInterval;891 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;892}893894// parameter_types! {895// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *896// RuntimeBlockWeights::get().max_block;897// pub const MaxScheduledPerBlock: u32 = 50;898// }899900type EvmSponsorshipHandler = (901 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,902 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,903);904type SponsorshipHandler = (905 pallet_unique::UniqueSponsorshipHandler<Runtime>,906 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,907 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,908);909910// impl pallet_unq_scheduler::Config for Runtime {911// type Event = Event;912// type Origin = Origin;913// type PalletsOrigin = OriginCaller;914// type Call = Call;915// type MaximumWeight = MaximumSchedulerWeight;916// type ScheduleOrigin = EnsureSigned<AccountId>;917// type MaxScheduledPerBlock = MaxScheduledPerBlock;918// type SponsorshipHandler = SponsorshipHandler;919// type WeightInfo = ();920// }921922impl pallet_evm_transaction_payment::Config for Runtime {923 type EvmSponsorshipHandler = EvmSponsorshipHandler;924 type Currency = Balances;925 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;926 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;927}928929impl pallet_charge_transaction::Config for Runtime {930 type SponsorshipHandler = SponsorshipHandler;931}932933// impl pallet_contract_helpers::Config for Runtime {934// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;935// }936937parameter_types! {938 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049939 pub const HelpersContractAddress: H160 = H160([940 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,941 ]);942}943944impl pallet_evm_contract_helpers::Config for Runtime {945 type ContractAddress = HelpersContractAddress;946 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;947}948949construct_runtime!(950 pub enum Runtime where951 Block = Block,952 NodeBlock = opaque::Block,953 UncheckedExtrinsic = UncheckedExtrinsic954 {955 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,956 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,957958 Aura: pallet_aura::{Pallet, Config<T>} = 22,959 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,960961 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,962 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,963 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,964 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,965 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,966 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,967 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,968 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,969 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,970 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,971972 // XCM helpers.973 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,974 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,975 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,976 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,977978 // Unique Pallets979 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,980 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,981 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,982 // free = 63983 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,984 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,985 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,986 Fungible: pallet_fungible::{Pallet, Storage} = 67,987 Refungible: pallet_refungible::{Pallet, Storage} = 68,988 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,989990 // Frontier991 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,992 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,993994 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,995 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,996 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,997 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,998 }999);10001001pub struct TransactionConverter;10021003impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1004 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1005 UncheckedExtrinsic::new_unsigned(1006 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1007 )1008 }1009}10101011impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1012 fn convert_transaction(1013 &self,1014 transaction: pallet_ethereum::Transaction,1015 ) -> opaque::UncheckedExtrinsic {1016 let extrinsic = UncheckedExtrinsic::new_unsigned(1017 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1018 );1019 let encoded = extrinsic.encode();1020 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1021 .expect("Encoded extrinsic is always valid")1022 }1023}10241025/// The address format for describing accounts.1026pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1027/// Block header type as expected by this runtime.1028pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1029/// Block type as expected by this runtime.1030pub type Block = generic::Block<Header, UncheckedExtrinsic>;1031/// A Block signed with a Justification1032pub type SignedBlock = generic::SignedBlock<Block>;1033/// BlockId type as expected by this runtime.1034pub type BlockId = generic::BlockId<Block>;1035/// The SignedExtension to the basic transaction logic.1036pub type SignedExtra = (1037 frame_system::CheckSpecVersion<Runtime>,1038 // system::CheckTxVersion<Runtime>,1039 frame_system::CheckGenesis<Runtime>,1040 frame_system::CheckEra<Runtime>,1041 frame_system::CheckNonce<Runtime>,1042 frame_system::CheckWeight<Runtime>,1043 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1044 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1045);1046/// Unchecked extrinsic type as expected by this runtime.1047pub type UncheckedExtrinsic =1048 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1049/// Extrinsic type that has already been checked.1050pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1051/// Executive: handles dispatch to the various modules.1052pub type Executive = frame_executive::Executive<1053 Runtime,1054 Block,1055 frame_system::ChainContext<Runtime>,1056 Runtime,1057 AllPalletsReversedWithSystemFirst,1058>;10591060impl_opaque_keys! {1061 pub struct SessionKeys {1062 pub aura: Aura,1063 }1064}10651066impl fp_self_contained::SelfContainedCall for Call {1067 type SignedInfo = H160;10681069 fn is_self_contained(&self) -> bool {1070 match self {1071 Call::Ethereum(call) => call.is_self_contained(),1072 _ => false,1073 }1074 }10751076 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1077 match self {1078 Call::Ethereum(call) => call.check_self_contained(),1079 _ => None,1080 }1081 }10821083 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1084 match self {1085 Call::Ethereum(call) => call.validate_self_contained(info),1086 _ => None,1087 }1088 }10891090 fn pre_dispatch_self_contained(1091 &self,1092 info: &Self::SignedInfo,1093 ) -> Option<Result<(), TransactionValidityError>> {1094 match self {1095 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1096 _ => None,1097 }1098 }10991100 fn apply_self_contained(1101 self,1102 info: Self::SignedInfo,1103 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1104 match self {1105 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1106 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1107 )),1108 _ => None,1109 }1110 }1111}11121113macro_rules! dispatch_unique_runtime {1114 ($collection:ident.$method:ident($($name:ident),*)) => {{1115 use pallet_unique::dispatch::Dispatched;11161117 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1118 let dispatch = collection.as_dyn();11191120 Ok(dispatch.$method($($name),*))1121 }};1122}1123impl_runtime_apis! {1124 impl up_rpc::UniqueApi<Block, CrossAccountId, AccountId>1125 for Runtime1126 {1127 fn account_tokens(collection: CollectionId, account: CrossAccountId) -> Result<Vec<TokenId>, DispatchError> {1128 dispatch_unique_runtime!(collection.account_tokens(account))1129 }1130 fn token_exists(collection: CollectionId, token: TokenId) -> Result<bool, DispatchError> {1131 dispatch_unique_runtime!(collection.token_exists(token))1132 }11331134 fn token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {1135 dispatch_unique_runtime!(collection.token_owner(token))1136 }1137 fn const_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1138 dispatch_unique_runtime!(collection.const_metadata(token))1139 }1140 fn variable_metadata(collection: CollectionId, token: TokenId) -> Result<Vec<u8>, DispatchError> {1141 dispatch_unique_runtime!(collection.variable_metadata(token))1142 }11431144 fn collection_tokens(collection: CollectionId) -> Result<u32, DispatchError> {1145 dispatch_unique_runtime!(collection.collection_tokens())1146 }1147 fn account_balance(collection: CollectionId, account: CrossAccountId) -> Result<u32, DispatchError> {1148 dispatch_unique_runtime!(collection.account_balance(account))1149 }1150 fn balance(collection: CollectionId, account: CrossAccountId, token: TokenId) -> Result<u128, DispatchError> {1151 dispatch_unique_runtime!(collection.balance(account, token))1152 }1153 fn allowance(1154 collection: CollectionId,1155 sender: CrossAccountId,1156 spender: CrossAccountId,1157 token: TokenId,1158 ) -> Result<u128, DispatchError> {1159 dispatch_unique_runtime!(collection.allowance(sender, spender, token))1160 }11611162 fn eth_contract_code(account: H160) -> Option<Vec<u8>> {1163 <pallet_unique::UniqueErcSupport<Runtime>>::get_code(&account)1164 .or_else(|| <pallet_evm_migration::OnMethodCall<Runtime>>::get_code(&account))1165 .or_else(|| <pallet_evm_contract_helpers::HelpersOnMethodCall<Self>>::get_code(&account))1166 }1167 fn adminlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1168 Ok(<pallet_common::Pallet<Runtime>>::adminlist(collection))1169 }1170 fn allowlist(collection: CollectionId) -> Result<Vec<CrossAccountId>, DispatchError> {1171 Ok(<pallet_common::Pallet<Runtime>>::allowlist(collection))1172 }1173 fn allowed(collection: CollectionId, user: CrossAccountId) -> Result<bool, DispatchError> {1174 Ok(<pallet_common::Pallet<Runtime>>::allowed(collection, user))1175 }1176 fn last_token_id(collection: CollectionId) -> Result<TokenId, DispatchError> {1177 dispatch_unique_runtime!(collection.last_token_id())1178 }1179 fn collection_by_id(collection: CollectionId) -> Result<Option<Collection<AccountId>>, DispatchError> {1180 Ok(<pallet_common::CollectionById<Runtime>>::get(collection))1181 }1182 fn collection_stats() -> Result<CollectionStats, DispatchError> {1183 Ok(<pallet_common::Pallet<Runtime>>::collection_stats())1184 }1185 }11861187 impl sp_api::Core<Block> for Runtime {1188 fn version() -> RuntimeVersion {1189 VERSION1190 }11911192 fn execute_block(block: Block) {1193 Executive::execute_block(block)1194 }11951196 fn initialize_block(header: &<Block as BlockT>::Header) {1197 Executive::initialize_block(header)1198 }1199 }12001201 impl sp_api::Metadata<Block> for Runtime {1202 fn metadata() -> OpaqueMetadata {1203 OpaqueMetadata::new(Runtime::metadata().into())1204 }1205 }12061207 impl sp_block_builder::BlockBuilder<Block> for Runtime {1208 fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {1209 Executive::apply_extrinsic(extrinsic)1210 }12111212 fn finalize_block() -> <Block as BlockT>::Header {1213 Executive::finalize_block()1214 }12151216 fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {1217 data.create_extrinsics()1218 }12191220 fn check_inherents(1221 block: Block,1222 data: sp_inherents::InherentData,1223 ) -> sp_inherents::CheckInherentsResult {1224 data.check_extrinsics(&block)1225 }12261227 // fn random_seed() -> <Block as BlockT>::Hash {1228 // RandomnessCollectiveFlip::random_seed().01229 // }1230 }12311232 impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {1233 fn validate_transaction(1234 source: TransactionSource,1235 tx: <Block as BlockT>::Extrinsic,1236 hash: <Block as BlockT>::Hash,1237 ) -> TransactionValidity {1238 Executive::validate_transaction(source, tx, hash)1239 }1240 }12411242 impl sp_offchain::OffchainWorkerApi<Block> for Runtime {1243 fn offchain_worker(header: &<Block as BlockT>::Header) {1244 Executive::offchain_worker(header)1245 }1246 }12471248 impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {1249 fn chain_id() -> u64 {1250 <Runtime as pallet_evm::Config>::ChainId::get()1251 }12521253 fn account_basic(address: H160) -> EVMAccount {1254 EVM::account_basic(&address)1255 }12561257 fn gas_price() -> U256 {1258 <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()1259 }12601261 fn account_code_at(address: H160) -> Vec<u8> {1262 EVM::account_codes(address)1263 }12641265 fn author() -> H160 {1266 <pallet_evm::Pallet<Runtime>>::find_author()1267 }12681269 fn storage_at(address: H160, index: U256) -> H256 {1270 let mut tmp = [0u8; 32];1271 index.to_big_endian(&mut tmp);1272 EVM::account_storages(address, H256::from_slice(&tmp[..]))1273 }12741275 #[allow(clippy::redundant_closure)]1276 fn call(1277 from: H160,1278 to: H160,1279 data: Vec<u8>,1280 value: U256,1281 gas_limit: U256,1282 max_fee_per_gas: Option<U256>,1283 max_priority_fee_per_gas: Option<U256>,1284 nonce: Option<U256>,1285 estimate: bool,1286 access_list: Option<Vec<(H160, Vec<H256>)>>,1287 ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {1288 let config = if estimate {1289 let mut config = <Runtime as pallet_evm::Config>::config().clone();1290 config.estimate = true;1291 Some(config)1292 } else {1293 None1294 };12951296 <Runtime as pallet_evm::Config>::Runner::call(1297 from,1298 to,1299 data,1300 value,1301 gas_limit.low_u64(),1302 max_fee_per_gas,1303 max_priority_fee_per_gas,1304 nonce,1305 access_list.unwrap_or_default(),1306 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1307 ).map_err(|err| err.into())1308 }13091310 #[allow(clippy::redundant_closure)]1311 fn create(1312 from: H160,1313 data: Vec<u8>,1314 value: U256,1315 gas_limit: U256,1316 max_fee_per_gas: Option<U256>,1317 max_priority_fee_per_gas: Option<U256>,1318 nonce: Option<U256>,1319 estimate: bool,1320 access_list: Option<Vec<(H160, Vec<H256>)>>,1321 ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {1322 let config = if estimate {1323 let mut config = <Runtime as pallet_evm::Config>::config().clone();1324 config.estimate = true;1325 Some(config)1326 } else {1327 None1328 };13291330 <Runtime as pallet_evm::Config>::Runner::create(1331 from,1332 data,1333 value,1334 gas_limit.low_u64(),1335 max_fee_per_gas,1336 max_priority_fee_per_gas,1337 nonce,1338 access_list.unwrap_or_default(),1339 config.as_ref().unwrap_or_else(|| <Runtime as pallet_evm::Config>::config()),1340 ).map_err(|err| err.into())1341 }13421343 fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {1344 Ethereum::current_transaction_statuses()1345 }13461347 fn current_block() -> Option<pallet_ethereum::Block> {1348 Ethereum::current_block()1349 }13501351 fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {1352 Ethereum::current_receipts()1353 }13541355 fn current_all() -> (1356 Option<pallet_ethereum::Block>,1357 Option<Vec<pallet_ethereum::Receipt>>,1358 Option<Vec<TransactionStatus>>1359 ) {1360 (1361 Ethereum::current_block(),1362 Ethereum::current_receipts(),1363 Ethereum::current_transaction_statuses()1364 )1365 }13661367 fn extrinsic_filter(xts: Vec<<Block as sp_api::BlockT>::Extrinsic>) -> Vec<pallet_ethereum::Transaction> {1368 xts.into_iter().filter_map(|xt| match xt.0.function {1369 Call::Ethereum(pallet_ethereum::Call::transact { transaction }) => Some(transaction),1370 _ => None1371 }).collect()1372 }13731374 fn elasticity() -> Option<Permill> {1375 None1376 }1377 }13781379 impl sp_session::SessionKeys<Block> for Runtime {1380 fn decode_session_keys(1381 encoded: Vec<u8>,1382 ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {1383 SessionKeys::decode_into_raw_public_keys(&encoded)1384 }13851386 fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {1387 SessionKeys::generate(seed)1388 }1389 }13901391 impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {1392 fn slot_duration() -> sp_consensus_aura::SlotDuration {1393 sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())1394 }13951396 fn authorities() -> Vec<AuraId> {1397 Aura::authorities().to_vec()1398 }1399 }14001401 impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {1402 fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {1403 ParachainSystem::collect_collation_info(header)1404 }1405 }14061407 impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {1408 fn account_nonce(account: AccountId) -> Index {1409 System::account_nonce(account)1410 }1411 }14121413 impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {1414 fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {1415 TransactionPayment::query_info(uxt, len)1416 }1417 fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {1418 TransactionPayment::query_fee_details(uxt, len)1419 }1420 }14211422 /*1423 impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber, Hash>1424 for Runtime1425 {1426 fn call(1427 origin: AccountId,1428 dest: AccountId,1429 value: Balance,1430 gas_limit: u64,1431 input_data: Vec<u8>,1432 ) -> pallet_contracts_primitives::ContractExecResult {1433 Contracts::bare_call(origin, dest, value, gas_limit, input_data, false)1434 }14351436 fn instantiate(1437 origin: AccountId,1438 endowment: Balance,1439 gas_limit: u64,1440 code: pallet_contracts_primitives::Code<Hash>,1441 data: Vec<u8>,1442 salt: Vec<u8>,1443 ) -> pallet_contracts_primitives::ContractInstantiateResult<AccountId, BlockNumber>1444 {1445 Contracts::bare_instantiate(origin, endowment, gas_limit, code, data, salt, true, false)1446 }14471448 fn get_storage(1449 address: AccountId,1450 key: [u8; 32],1451 ) -> pallet_contracts_primitives::GetStorageResult {1452 Contracts::get_storage(address, key)1453 }14541455 fn rent_projection(1456 address: AccountId,1457 ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {1458 Contracts::rent_projection(address)1459 }1460 }1461 */14621463 #[cfg(feature = "runtime-benchmarks")]1464 impl frame_benchmarking::Benchmark<Block> for Runtime {1465 fn benchmark_metadata(extra: bool) -> (1466 Vec<frame_benchmarking::BenchmarkList>,1467 Vec<frame_support::traits::StorageInfo>,1468 ) {1469 use frame_benchmarking::{list_benchmark, Benchmarking, BenchmarkList};1470 use frame_support::traits::StorageInfoTrait;14711472 let mut list = Vec::<BenchmarkList>::new();14731474 list_benchmark!(list, extra, pallet_evm_migration, EvmMigration);1475 list_benchmark!(list, extra, pallet_unique, Unique);1476 list_benchmark!(list, extra, pallet_inflation, Inflation);1477 list_benchmark!(list, extra, pallet_fungible, Fungible);1478 list_benchmark!(list, extra, pallet_refungible, Refungible);1479 list_benchmark!(list, extra, pallet_nonfungible, Nonfungible);1480 // list_benchmark!(list, extra, pallet_evm_coder_substrate, EvmCoderSubstrate);14811482 let storage_info = AllPalletsReversedWithSystemFirst::storage_info();14831484 return (list, storage_info)1485 }14861487 fn dispatch_benchmark(1488 config: frame_benchmarking::BenchmarkConfig1489 ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {1490 use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};14911492 let allowlist: Vec<TrackedStorageKey> = vec![1493 // Block Number1494 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac").to_vec().into(),1495 // Total Issuance1496 hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),1497 // Execution Phase1498 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),1499 // Event Count1500 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),1501 // System Events1502 hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),1503 ];15041505 let mut batches = Vec::<BenchmarkBatch>::new();1506 let params = (&config, &allowlist);15071508 add_benchmark!(params, batches, pallet_evm_migration, EvmMigration);1509 add_benchmark!(params, batches, pallet_unique, Unique);1510 add_benchmark!(params, batches, pallet_inflation, Inflation);1511 add_benchmark!(params, batches, pallet_fungible, Fungible);1512 add_benchmark!(params, batches, pallet_refungible, Refungible);1513 add_benchmark!(params, batches, pallet_nonfungible, Nonfungible);1514 // add_benchmark!(params, batches, pallet_evm_coder_substrate, EvmCoderSubstrate);15151516 if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }1517 Ok(batches)1518 }1519 }1520}15211522struct CheckInherents;15231524impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1525 fn check_inherents(1526 block: &Block,1527 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1528 ) -> sp_inherents::CheckInherentsResult {1529 let relay_chain_slot = relay_state_proof1530 .read_slot()1531 .expect("Could not read the relay chain slot from the proof");15321533 let inherent_data =1534 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1535 relay_chain_slot,1536 sp_std::time::Duration::from_secs(6),1537 )1538 .create_inherent_data()1539 .expect("Could not create the timestamp inherent data");15401541 inherent_data.check_extrinsics(block)1542 }1543}15441545cumulus_pallet_parachain_system::register_validate_block!(1546 Runtime = Runtime,1547 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1548 CheckInherents = CheckInherents,1549);runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -111,6 +111,8 @@
// mod chain_extension;
// use crate::chain_extension::{NFTExtension, Imbalance};
+pub const RUNTIME_NAME: &'static str = "Quartz";
+
pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -111,6 +111,8 @@
// mod chain_extension;
// use crate::chain_extension::{NFTExtension, Imbalance};
+pub const RUNTIME_NAME: &'static str = "Unique";
+
pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know