difftreelog
CORE-302 Fix compile after rebase
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6818,11 +6818,15 @@
name = "pallet-unique"
version = "0.1.0"
dependencies = [
+ "ethereum",
+ "evm-coder",
"frame-benchmarking",
"frame-support",
"frame-system",
"pallet-common",
"pallet-evm",
+ "pallet-evm-coder-substrate",
+ "pallet-nonfungible",
"parity-scale-codec 3.1.2",
"scale-info",
"serde",
pallets/unique/Cargo.tomldiffbeforeafterboth--- a/pallets/unique/Cargo.toml
+++ b/pallets/unique/Cargo.toml
@@ -33,6 +33,22 @@
limit-testing = ["up-data-structs/limit-testing"]
################################################################################
+# Standart Dependencies
+
+[dependencies.serde]
+default-features = false
+features = ['derive']
+version = '1.0.130'
+
+[dependencies.serde-json-core]
+default-features = false
+version = "0.4"
+
+[dependencies.ethereum]
+version = "0.12.0"
+default-features = false
+
+################################################################################
# Substrate Dependencies
[dependencies.codec]
@@ -66,15 +82,6 @@
# default-features = false
# git = "https://github.com/paritytech/substrate"
# branch = "polkadot-v0.9.21"
-
-[dependencies.serde]
-default-features = false
-features = ['derive']
-version = '1.0.130'
-
-[dependencies.serde-json-core]
-default-features = false
-version = "0.4"
[dependencies.sp-runtime]
default-features = false
@@ -90,7 +97,6 @@
default-features = false
git = "https://github.com/paritytech/substrate"
branch = "polkadot-v0.9.21"
-
################################################################################
# Local Dependencies
@@ -101,3 +107,6 @@
] }
pallet-evm = { default-features = false, git = "https://github.com/uniquenetwork/frontier", branch = "unique-polkadot-v0.9.21-logs" }
pallet-common = { default-features = false, path = "../common" }
+evm-coder = { default-features = false, path = '../../crates/evm-coder' }
+pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
+pallet-nonfungible = { default-features = false, path = '../../pallets/nonfungible' }
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -14,100 +14,19 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-pub mod sponsoring;
-
-use fp_evm::PrecompileResult;
-use pallet_common::{
- CollectionById,
- erc::CommonEvmHandler,
- eth::{map_eth_to_id, map_eth_to_token_id},
-};
-use pallet_fungible::FungibleHandle;
-use pallet_nonfungible::NonfungibleHandle;
-use pallet_refungible::{RefungibleHandle, erc::RefungibleTokenHandle};
-use sp_std::borrow::ToOwned;
-use sp_std::vec::Vec;
-use sp_core::{H160, U256};
-use crate::{CollectionMode, Config, dispatch::Dispatched};
-use pallet_common::CollectionHandle;
-
-pub struct UniqueErcSupport<T: Config>(core::marker::PhantomData<T>);
-
-impl<T: Config> pallet_evm::OnMethodCall<T> for UniqueErcSupport<T> {
- fn is_reserved(target: &H160) -> bool {
- map_eth_to_id(target).is_some()
- }
- fn is_used(target: &H160) -> bool {
- map_eth_to_id(target)
- .map(<CollectionById<T>>::contains_key)
- .unwrap_or(false)
- }
- fn get_code(target: &H160) -> Option<Vec<u8>> {
- if let Some(collection_id) = map_eth_to_id(target) {
- let collection = <CollectionById<T>>::get(collection_id)?;
- Some(
- match collection.mode {
- CollectionMode::NFT => <NonfungibleHandle<T>>::CODE,
- CollectionMode::Fungible(_) => <FungibleHandle<T>>::CODE,
- CollectionMode::ReFungible => <RefungibleHandle<T>>::CODE,
- }
- .to_owned(),
- )
- } else if let Some((collection_id, _token_id)) = map_eth_to_token_id(target) {
- let collection = <CollectionById<T>>::get(collection_id)?;
- if collection.mode != CollectionMode::ReFungible {
- return None;
- }
- // TODO: check token existence
- Some(<RefungibleTokenHandle<T>>::CODE.to_owned())
- } else {
- None
- }
- }
- fn call(
- source: &H160,
- target: &H160,
- gas_limit: u64,
- input: &[u8],
- value: U256,
- ) -> Option<PrecompileResult> {
- if let Some(collection_id) = map_eth_to_id(target) {
- let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
- let dispatched = Dispatched::dispatch(collection);
-
- match dispatched {
- Dispatched::Fungible(h) => h.call(source, input, value),
- Dispatched::Nonfungible(h) => h.call(source, input, value),
- Dispatched::Refungible(h) => h.call(source, input, value),
- }
- } else if let Some((collection_id, token_id)) = map_eth_to_token_id(target) {
- let collection = <CollectionHandle<T>>::new_with_gas_limit(collection_id, gas_limit)?;
- if collection.mode != CollectionMode::ReFungible {
- return None;
- }
-
- let handle = RefungibleHandle::cast(collection);
- // TODO: check token existence
- RefungibleTokenHandle(handle, token_id).call(source, input, value)
- } else {
- None
- }
- }
-}
-
pub mod evm_collection {
use core::marker::PhantomData;
use evm_coder::{execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
use ethereum as _;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
- use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId};
+ use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, Pallet as PalletEvm};
use up_data_structs::{
CreateCollectionData, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
MAX_COLLECTION_NAME_LENGTH,
};
use frame_support::traits::Get;
use sp_core::H160;
- use pallet_common::{CollectionHandle, save_eth, pallet::CollectionById};
+ use pallet_common::{CollectionHandle, CollectionById};
use sp_std::{vec::Vec, rc::Rc};
use alloc::format;
@@ -121,13 +40,13 @@
type ContractAddress: Get<H160>;
}
- struct EvmCollectionHelper<T: Config>(Rc<SubstrateRecorder<T>>);
+ struct EvmCollectionHelper<T: Config>(SubstrateRecorder<T>);
impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
&self.0
}
- fn into_recorder(self) -> Rc<SubstrateRecorder<T>> {
+ fn into_recorder(self) -> SubstrateRecorder<T> {
self.0
}
}
@@ -171,10 +90,13 @@
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
- self.0.log_mirrored(EthCollectionEvent::CollectionCreated {
- owner: *caller.as_eth(),
- collection_id: address,
- });
+ <PalletEvm<T>>::deposit_log(
+ EthCollectionEvent::CollectionCreated {
+ owner: *caller.as_eth(),
+ collection_id: address,
+ }
+ .to_log(address),
+ );
Ok(address)
}
@@ -188,14 +110,14 @@
}
}
- struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
+ struct EvmCollection<T: Config>(H160, SubstrateRecorder<T>);
impl<T: Config> WithRecorder<T> for EvmCollection<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
- &self.0
+ &self.1
}
- fn into_recorder(self) -> Rc<SubstrateRecorder<T>> {
- self.0
+ fn into_recorder(self) -> SubstrateRecorder<T> {
+ self.1
}
}
@@ -216,21 +138,23 @@
caller: caller,
sponsor: address,
) -> Result<void> {
- let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
+ let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
check_is_owner(caller, &collection)?;
let sponsor = T::CrossAccountId::from_eth(sponsor);
collection.set_sponsor(sponsor.as_sub().clone());
- save_eth(collection)
+ collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
}
fn confirm_sponsorship(&self, caller: caller) -> Result<void> {
- let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
+ let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
let caller = T::CrossAccountId::from_eth(caller);
if !collection.confirm_sponsorship(caller.as_sub()) {
return Err(Error::Revert("Caller is not set as sponsor".into()));
}
- save_eth(collection)
+ collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
}
fn set_limits(
@@ -238,17 +162,18 @@
caller: caller,
limits_json: string,
) -> Result<void> {
- let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
+ let mut collection = collection_from_address::<T>(self.contract_address(caller).unwrap(), self.1.gas_left())?;
check_is_owner(caller, &collection)?;
let limits = serde_json_core::from_str(limits_json.as_ref())
.map_err(|e| Error::Revert(format!("Parse JSON error: {}", e)))?;
collection.limits = limits.0;
- save_eth(collection)
+ collection.save().map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+ Ok(())
}
fn contract_address(&self, _caller: caller) -> Result<address> {
- Ok(self.0.contract())
+ Ok(self.0)
}
}
@@ -258,12 +183,13 @@
fn collection_from_address<T: Config>(
collection_address: address,
- recorder: &Rc<SubstrateRecorder<T>>,
+ gas_limit: u64
) -> Result<CollectionHandle<T>> {
let collection_id = pallet_common::eth::map_eth_to_id(&collection_address)
- .ok_or(Error::Revert("Contract is not an unique collection".into()))?;
+ .ok_or(Error::Revert("Contract is not an unique collection".into()))?;
+ let recorder = <SubstrateRecorder<T>>::new(gas_limit);
let collection =
- pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder.clone())
+ pallet_common::CollectionHandle::new_with_recorder(collection_id, recorder)
.ok_or(Error::Revert("Create collection handle error".into()))?;
Ok(collection)
}
@@ -297,7 +223,7 @@
return None;
}
- let helpers = EvmCollectionHelper::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
+ let helpers = EvmCollectionHelper::<T>(SubstrateRecorder::<T>::new(gas_left));
pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
@@ -331,7 +257,7 @@
return None;
}
- let helpers = EvmCollection::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
+ let helpers = EvmCollection::<T>(*target, SubstrateRecorder::<T>::new(gas_left));
pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -22,6 +22,8 @@
clippy::unused_unit
)]
+extern crate alloc;
+
use frame_support::{
decl_module, decl_storage, decl_error, decl_event,
dispatch::DispatchResult,
@@ -46,7 +48,7 @@
CollectionHandle, Pallet as PalletCommon, CommonWeightInfo, dispatch::dispatch_call,
dispatch::CollectionDispatch,
};
-pub use eth::evm_collection;
+pub mod eth;
#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;
runtime/quartz/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::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use unique_runtime_common::dispatch::{CollectionDispatchT, CollectionDispatch};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 pallet_unique::evm_collection;84use fp_rpc::TransactionStatus;85use sp_runtime::{86 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},87 transaction_validity::TransactionValidityError,88 SaturatedConversion,89};9091// pub use pallet_timestamp::Call as TimestampCall;92pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9394// Polkadot imports95use pallet_xcm::XcmPassthrough;96use polkadot_parachain::primitives::Sibling;97use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};98use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};99use xcm_builder::{100 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,101 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,102 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,103 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,104 ParentIsPreset,105};106use xcm_executor::{Config, XcmExecutor, Assets};107use sp_std::{marker::PhantomData};108109use xcm::latest::{110 // Xcm,111 AssetId::{Concrete},112 Fungibility::Fungible as XcmFungible,113 MultiAsset,114 Error as XcmError,115};116use xcm_executor::traits::{MatchesFungible, WeightTrader};117//use xcm_executor::traits::MatchesFungible;118use sp_runtime::traits::CheckedConversion;119120use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};121122pub const RUNTIME_NAME: &str = "quartz";123pub const TOKEN_SYMBOL: &str = "QTZ";124125type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;126127impl RuntimeInstance for Runtime {128 type CrossAccountId = self::CrossAccountId;129130 type TransactionConverter = self::TransactionConverter;131132 fn get_transaction_converter() -> TransactionConverter {133 TransactionConverter134 }135}136137/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know138/// the specifics of the runtime. They can then be made to be agnostic over specific formats139/// of data like extrinsics, allowing for them to continue syncing the network through upgrades140/// to even the core data structures.141pub mod opaque {142 use sp_std::prelude::*;143 use sp_runtime::impl_opaque_keys;144 use super::Aura;145146 pub use unique_runtime_common::types::*;147148 impl_opaque_keys! {149 pub struct SessionKeys {150 pub aura: Aura,151 }152 }153}154155/// This runtime version.156pub const VERSION: RuntimeVersion = RuntimeVersion {157 spec_name: create_runtime_str!(RUNTIME_NAME),158 impl_name: create_runtime_str!(RUNTIME_NAME),159 authoring_version: 1,160 spec_version: 920000,161 impl_version: 0,162 apis: RUNTIME_API_VERSIONS,163 transaction_version: 1,164 state_version: 0,165};166167#[derive(codec::Encode, codec::Decode)]168pub enum XCMPMessage<XAccountId, XBalance> {169 /// Transfer tokens to the given account from the Parachain account.170 TransferToken(XAccountId, XBalance),171}172173/// The version information used to identify this runtime when compiled natively.174#[cfg(feature = "std")]175pub fn native_version() -> NativeVersion {176 NativeVersion {177 runtime_version: VERSION,178 can_author_with: Default::default(),179 }180}181182type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;183184pub struct DealWithFees;185impl OnUnbalanced<NegativeImbalance> for DealWithFees {186 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {187 if let Some(fees) = fees_then_tips.next() {188 // for fees, 100% to treasury189 let mut split = fees.ration(100, 0);190 if let Some(tips) = fees_then_tips.next() {191 // for tips, if any, 100% to treasury192 tips.ration_merge_into(100, 0, &mut split);193 }194 Treasury::on_unbalanced(split.0);195 // Author::on_unbalanced(split.1);196 }197 }198}199200parameter_types! {201 pub const BlockHashCount: BlockNumber = 2400;202 pub RuntimeBlockLength: BlockLength =203 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);204 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);205 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;206 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()207 .base_block(BlockExecutionWeight::get())208 .for_class(DispatchClass::all(), |weights| {209 weights.base_extrinsic = ExtrinsicBaseWeight::get();210 })211 .for_class(DispatchClass::Normal, |weights| {212 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);213 })214 .for_class(DispatchClass::Operational, |weights| {215 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);216 // Operational transactions have some extra reserved space, so that they217 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.218 weights.reserved = Some(219 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT220 );221 })222 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)223 .build_or_panic();224 pub const Version: RuntimeVersion = VERSION;225 pub const SS58Prefix: u8 = 255;226}227228parameter_types! {229 pub const ChainId: u64 = 8881;230}231232pub struct FixedFee;233impl FeeCalculator for FixedFee {234 fn min_gas_price() -> U256 {235 MIN_GAS_PRICE.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<Self>;272 type WithdrawOrigin = EnsureAddressTruncated<Self>;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_evm_contract_helpers::HelpersOnMethodCall<Self>,281 CollectionDispatchT<Self>,282 evm_collection::CollectionOnMethodCall<Self>,283 evm_collection::CollectionHelperOnMethodCall<Self>,284 );285 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;286 type ChainId = ChainId;287 type Runner = pallet_evm::runner::stack::Runner<Self>;288 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;289 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;290 type FindAuthor = EthereumFindAuthor<Aura>;291}292293impl pallet_evm_migration::Config for Runtime {294 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;295}296297pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);298impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {299 fn find_author<'a, I>(digests: I) -> Option<H160>300 where301 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,302 {303 if let Some(author_index) = F::find_author(digests) {304 let authority_id = Aura::authorities()[author_index as usize].clone();305 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));306 }307 None308 }309}310311impl pallet_ethereum::Config for Runtime {312 type Event = Event;313 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;314}315316impl pallet_randomness_collective_flip::Config for Runtime {}317318impl frame_system::Config for Runtime {319 /// The data to be stored in an account.320 type AccountData = pallet_balances::AccountData<Balance>;321 /// The identifier used to distinguish between accounts.322 type AccountId = AccountId;323 /// The basic call filter to use in dispatchable.324 type BaseCallFilter = Everything;325 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).326 type BlockHashCount = BlockHashCount;327 /// The maximum length of a block (in bytes).328 type BlockLength = RuntimeBlockLength;329 /// The index type for blocks.330 type BlockNumber = BlockNumber;331 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.332 type BlockWeights = RuntimeBlockWeights;333 /// The aggregated dispatch type that is available for extrinsics.334 type Call = Call;335 /// The weight of database operations that the runtime can invoke.336 type DbWeight = RocksDbWeight;337 /// The ubiquitous event type.338 type Event = Event;339 /// The type for hashing blocks and tries.340 type Hash = Hash;341 /// The hashing algorithm used.342 type Hashing = BlakeTwo256;343 /// The header type.344 type Header = generic::Header<BlockNumber, BlakeTwo256>;345 /// The index type for storing how many extrinsics an account has signed.346 type Index = Index;347 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.348 type Lookup = AccountIdLookup<AccountId, ()>;349 /// What to do if an account is fully reaped from the system.350 type OnKilledAccount = ();351 /// What to do if a new account is created.352 type OnNewAccount = ();353 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;354 /// The ubiquitous origin type.355 type Origin = Origin;356 /// This type is being generated by `construct_runtime!`.357 type PalletInfo = PalletInfo;358 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.359 type SS58Prefix = SS58Prefix;360 /// Weight information for the extrinsics of this pallet.361 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;362 /// Version of the runtime.363 type Version = Version;364 type MaxConsumers = ConstU32<16>;365}366367parameter_types! {368 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;369}370371impl pallet_timestamp::Config for Runtime {372 /// A timestamp: milliseconds since the unix epoch.373 type Moment = u64;374 type OnTimestampSet = ();375 type MinimumPeriod = MinimumPeriod;376 type WeightInfo = ();377}378379parameter_types! {380 // pub const ExistentialDeposit: u128 = 500;381 pub const ExistentialDeposit: u128 = 0;382 pub const MaxLocks: u32 = 50;383}384385impl pallet_balances::Config for Runtime {386 type MaxLocks = MaxLocks;387 type MaxReserves = ();388 type ReserveIdentifier = [u8; 8];389 /// The type for recording an account's balance.390 type Balance = Balance;391 /// The ubiquitous event type.392 type Event = Event;393 type DustRemoval = Treasury;394 type ExistentialDeposit = ExistentialDeposit;395 type AccountStore = System;396 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;397}398399pub const fn deposit(items: u32, bytes: u32) -> Balance {400 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE401}402403/*404parameter_types! {405 pub TombstoneDeposit: Balance = deposit(406 1,407 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,408 );409 pub DepositPerContract: Balance = TombstoneDeposit::get();410 pub const DepositPerStorageByte: Balance = deposit(0, 1);411 pub const DepositPerStorageItem: Balance = deposit(1, 0);412 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);413 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;414 pub const SignedClaimHandicap: u32 = 2;415 pub const MaxDepth: u32 = 32;416 pub const MaxValueSize: u32 = 16 * 1024;417 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb418 // The lazy deletion runs inside on_initialize.419 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *420 RuntimeBlockWeights::get().max_block;421 // The weight needed for decoding the queue should be less or equal than a fifth422 // of the overall weight dedicated to the lazy deletion.423 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (424 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -425 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)426 )) / 5) as u32;427 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();428}429430impl pallet_contracts::Config for Runtime {431 type Time = Timestamp;432 type Randomness = RandomnessCollectiveFlip;433 type Currency = Balances;434 type Event = Event;435 type RentPayment = ();436 type SignedClaimHandicap = SignedClaimHandicap;437 type TombstoneDeposit = TombstoneDeposit;438 type DepositPerContract = DepositPerContract;439 type DepositPerStorageByte = DepositPerStorageByte;440 type DepositPerStorageItem = DepositPerStorageItem;441 type RentFraction = RentFraction;442 type SurchargeReward = SurchargeReward;443 type WeightPrice = pallet_transaction_payment::Pallet<Self>;444 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;445 type ChainExtension = NFTExtension;446 type DeletionQueueDepth = DeletionQueueDepth;447 type DeletionWeightLimit = DeletionWeightLimit;448 type Schedule = Schedule;449 type CallStack = [pallet_contracts::Frame<Self>; 31];450}451*/452453parameter_types! {454 /// This value increases the priority of `Operational` transactions by adding455 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.456 pub const OperationalFeeMultiplier: u8 = 5;457}458459/// Linear implementor of `WeightToFeePolynomial`460pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);461462impl<T> WeightToFeePolynomial for LinearFee<T>463where464 T: BaseArithmetic + From<u32> + Copy + Unsigned,465{466 type Balance = T;467468 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {469 smallvec!(WeightToFeeCoefficient {470 // Targeting 0.1 Unique per NFT transfer471 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),472 coeff_frac: Perbill::zero(),473 negative: false,474 degree: 1,475 })476 }477}478479impl pallet_transaction_payment::Config for Runtime {480 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;481 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;482 type OperationalFeeMultiplier = OperationalFeeMultiplier;483 type WeightToFee = LinearFee<Balance>;484 type FeeMultiplierUpdate = ();485}486487parameter_types! {488 pub const ProposalBond: Permill = Permill::from_percent(5);489 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;490 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;491 pub const SpendPeriod: BlockNumber = 5 * MINUTES;492 pub const Burn: Permill = Permill::from_percent(0);493 pub const TipCountdown: BlockNumber = 1 * DAYS;494 pub const TipFindersFee: Percent = Percent::from_percent(20);495 pub const TipReportDepositBase: Balance = 1 * UNIQUE;496 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;497 pub const BountyDepositBase: Balance = 1 * UNIQUE;498 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;499 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");500 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;501 pub const MaximumReasonLength: u32 = 16384;502 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);503 pub const BountyValueMinimum: Balance = 5 * UNIQUE;504 pub const MaxApprovals: u32 = 100;505}506507impl pallet_treasury::Config for Runtime {508 type PalletId = TreasuryModuleId;509 type Currency = Balances;510 type ApproveOrigin = EnsureRoot<AccountId>;511 type RejectOrigin = EnsureRoot<AccountId>;512 type Event = Event;513 type OnSlash = ();514 type ProposalBond = ProposalBond;515 type ProposalBondMinimum = ProposalBondMinimum;516 type ProposalBondMaximum = ProposalBondMaximum;517 type SpendPeriod = SpendPeriod;518 type Burn = Burn;519 type BurnDestination = ();520 type SpendFunds = ();521 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;522 type MaxApprovals = MaxApprovals;523}524525impl pallet_sudo::Config for Runtime {526 type Event = Event;527 type Call = Call;528}529530pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);531532impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider533 for RelayChainBlockNumberProvider<T>534{535 type BlockNumber = BlockNumber;536537 fn current_block_number() -> Self::BlockNumber {538 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()539 .map(|d| d.relay_parent_number)540 .unwrap_or_default()541 }542}543544parameter_types! {545 pub const MinVestedTransfer: Balance = 10 * UNIQUE;546 pub const MaxVestingSchedules: u32 = 28;547}548549impl orml_vesting::Config for Runtime {550 type Event = Event;551 type Currency = pallet_balances::Pallet<Runtime>;552 type MinVestedTransfer = MinVestedTransfer;553 type VestedTransferOrigin = EnsureSigned<AccountId>;554 type WeightInfo = ();555 type MaxVestingSchedules = MaxVestingSchedules;556 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;557}558559parameter_types! {560 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;561 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562}563564impl cumulus_pallet_parachain_system::Config for Runtime {565 type Event = Event;566 type SelfParaId = parachain_info::Pallet<Self>;567 type OnSystemEvent = ();568 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<569 // MaxDownwardMessageWeight,570 // XcmExecutor<XcmConfig>,571 // Call,572 // >;573 type OutboundXcmpMessageSource = XcmpQueue;574 type DmpMessageHandler = DmpQueue;575 type ReservedDmpWeight = ReservedDmpWeight;576 type ReservedXcmpWeight = ReservedXcmpWeight;577 type XcmpMessageHandler = XcmpQueue;578}579580impl parachain_info::Config for Runtime {}581582impl cumulus_pallet_aura_ext::Config for Runtime {}583584parameter_types! {585 pub const RelayLocation: MultiLocation = MultiLocation::parent();586 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;587 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();588 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();589}590591/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used592/// when determining ownership of accounts for asset transacting and when attempting to use XCM593/// `Transact` in order to determine the dispatch Origin.594pub type LocationToAccountId = (595 // The parent (Relay-chain) origin converts to the default `AccountId`.596 ParentIsPreset<AccountId>,597 // Sibling parachain origins convert to AccountId via the `ParaId::into`.598 SiblingParachainConvertsVia<Sibling, AccountId>,599 // Straight up local `AccountId32` origins just alias directly to `AccountId`.600 AccountId32Aliases<RelayNetwork, AccountId>,601);602603pub struct OnlySelfCurrency;604impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {605 fn matches_fungible(a: &MultiAsset) -> Option<B> {606 match (&a.id, &a.fun) {607 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),608 _ => None,609 }610 }611}612613/// Means for transacting assets on this chain.614pub type LocalAssetTransactor = CurrencyAdapter<615 // Use this currency:616 Balances,617 // Use this currency when it is a fungible asset matching the given location or name:618 OnlySelfCurrency,619 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:620 LocationToAccountId,621 // Our chain's account ID type (we can't get away without mentioning it explicitly):622 AccountId,623 // We don't track any teleports.624 (),625>;626627/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,628/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can629/// biases the kind of local `Origin` it will become.630pub type XcmOriginToTransactDispatchOrigin = (631 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location632 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for633 // foreign chains who want to have a local sovereign account on this chain which they control.634 SovereignSignedViaLocation<LocationToAccountId, Origin>,635 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when636 // recognised.637 RelayChainAsNative<RelayOrigin, Origin>,638 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when639 // recognised.640 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,641 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a642 // transaction from the Root origin.643 ParentAsSuperuser<Origin>,644 // Native signed account converter; this just converts an `AccountId32` origin into a normal645 // `Origin::Signed` origin of the same 32-byte value.646 SignedAccountId32AsNative<RelayNetwork, Origin>,647 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.648 XcmPassthrough<Origin>,649);650651parameter_types! {652 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.653 pub UnitWeightCost: Weight = 1_000_000;654 // 1200 UNIQUEs buy 1 second of weight.655 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);656 pub const MaxInstructions: u32 = 100;657 pub const MaxAuthorities: u32 = 100_000;658}659660match_types! {661 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {662 MultiLocation { parents: 1, interior: Here } |663 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }664 };665}666667pub type Barrier = (668 TakeWeightCredit,669 AllowTopLevelPaidExecutionFrom<Everything>,670 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,671 // ^^^ Parent & its unit plurality gets free execution672);673674pub struct UsingOnlySelfCurrencyComponents<675 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,676 AssetId: Get<MultiLocation>,677 AccountId,678 Currency: CurrencyT<AccountId>,679 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,680>(681 Weight,682 Currency::Balance,683 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,684);685impl<686 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,687 AssetId: Get<MultiLocation>,688 AccountId,689 Currency: CurrencyT<AccountId>,690 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,691 > WeightTrader692 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>693{694 fn new() -> Self {695 Self(0, Zero::zero(), PhantomData)696 }697698 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {699 let amount = WeightToFee::calc(&weight);700 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;701702 // location to this parachain through relay chain703 let option1: xcm::v1::AssetId = Concrete(MultiLocation {704 parents: 1,705 interior: X1(Parachain(ParachainInfo::parachain_id().into())),706 });707 // direct location708 let option2: xcm::v1::AssetId = Concrete(MultiLocation {709 parents: 0,710 interior: Here,711 });712713 let required = if payment.fungible.contains_key(&option1) {714 (option1, u128_amount).into()715 } else if payment.fungible.contains_key(&option2) {716 (option2, u128_amount).into()717 } else {718 (Concrete(MultiLocation::default()), u128_amount).into()719 };720721 let unused = payment722 .checked_sub(required)723 .map_err(|_| XcmError::TooExpensive)?;724 self.0 = self.0.saturating_add(weight);725 self.1 = self.1.saturating_add(amount);726 Ok(unused)727 }728729 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {730 let weight = weight.min(self.0);731 let amount = WeightToFee::calc(&weight);732 self.0 -= weight;733 self.1 = self.1.saturating_sub(amount);734 let amount: u128 = amount.saturated_into();735 if amount > 0 {736 Some((AssetId::get(), amount).into())737 } else {738 None739 }740 }741}742impl<743 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,744 AssetId: Get<MultiLocation>,745 AccountId,746 Currency: CurrencyT<AccountId>,747 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,748 > Drop749 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>750{751 fn drop(&mut self) {752 OnUnbalanced::on_unbalanced(Currency::issue(self.1));753 }754}755756pub struct XcmConfig;757impl Config for XcmConfig {758 type Call = Call;759 type XcmSender = XcmRouter;760 // How to withdraw and deposit an asset.761 type AssetTransactor = LocalAssetTransactor;762 type OriginConverter = XcmOriginToTransactDispatchOrigin;763 type IsReserve = NativeAsset;764 type IsTeleporter = (); // Teleportation is disabled765 type LocationInverter = LocationInverter<Ancestry>;766 type Barrier = Barrier;767 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;768 type Trader = UsingOnlySelfCurrencyComponents<769 IdentityFee<Balance>,770 RelayLocation,771 AccountId,772 Balances,773 (),774 >;775 type ResponseHandler = (); // Don't handle responses for now.776 type SubscriptionService = PolkadotXcm;777778 type AssetTrap = PolkadotXcm;779 type AssetClaims = PolkadotXcm;780}781782// parameter_types! {783// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;784// }785786/// No local origins on this chain are allowed to dispatch XCM sends/executions.787pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);788789/// The means for routing XCM messages which are not for local execution into the right message790/// queues.791pub type XcmRouter = (792 // Two routers - use UMP to communicate with the relay chain:793 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,794 // ..and XCMP to communicate with the sibling chains.795 XcmpQueue,796);797798impl pallet_evm_coder_substrate::Config for Runtime {799 type GasWeightMapping = FixedGasWeightMapping;800}801802impl pallet_xcm::Config for Runtime {803 type Event = Event;804 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;805 type XcmRouter = XcmRouter;806 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;807 type XcmExecuteFilter = Everything;808 type XcmExecutor = XcmExecutor<XcmConfig>;809 type XcmTeleportFilter = Everything;810 type XcmReserveTransferFilter = Everything;811 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;812 type LocationInverter = LocationInverter<Ancestry>;813 type Origin = Origin;814 type Call = Call;815 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;816 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;817}818819impl cumulus_pallet_xcm::Config for Runtime {820 type Event = Event;821 type XcmExecutor = XcmExecutor<XcmConfig>;822}823824impl cumulus_pallet_xcmp_queue::Config for Runtime {825 type WeightInfo = ();826 type Event = Event;827 type XcmExecutor = XcmExecutor<XcmConfig>;828 type ChannelInfo = ParachainSystem;829 type VersionWrapper = ();830 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;831 type ControllerOrigin = EnsureRoot<AccountId>;832 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;833}834835impl cumulus_pallet_dmp_queue::Config for Runtime {836 type Event = Event;837 type XcmExecutor = XcmExecutor<XcmConfig>;838 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;839}840841impl pallet_aura::Config for Runtime {842 type AuthorityId = AuraId;843 type DisabledValidators = ();844 type MaxAuthorities = MaxAuthorities;845}846847parameter_types! {848 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();849 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;850}851852impl pallet_common::Config for Runtime {853 type Event = Event;854855 type Currency = Balances;856 type CollectionCreationPrice = CollectionCreationPrice;857 type TreasuryAccountId = TreasuryAccountId;858 type CollectionDispatch = CollectionDispatchT<Self>;859860 type EvmTokenAddressMapping = EvmTokenAddressMapping;861 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;862}863864impl pallet_structure::Config for Runtime {865 type Event = Event;866 type Call = Call;867 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;868}869870impl pallet_evm::account::Config for Runtime {871 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;872 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;873 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;874}875876impl pallet_fungible::Config for Runtime {877 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;878}879impl pallet_refungible::Config for Runtime {880 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;881}882impl pallet_nonfungible::Config for Runtime {883 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;884}885886impl pallet_proxy_rmrk_core::Config for Runtime {887 type Event = Event;888}889890impl pallet_proxy_rmrk_equip::Config for Runtime {891 type Event = Event;892}893894impl pallet_unique::Config for Runtime {895 type Event = Event;896 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;897}898899parameter_types! {900 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied901}902903/// Used for the pallet inflation904impl pallet_inflation::Config for Runtime {905 type Currency = Balances;906 type TreasuryAccountId = TreasuryAccountId;907 type InflationBlockInterval = InflationBlockInterval;908 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;909}910911// parameter_types! {912// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *913// RuntimeBlockWeights::get().max_block;914// pub const MaxScheduledPerBlock: u32 = 50;915// }916917type EvmSponsorshipHandler = (918 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,919 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,920);921type SponsorshipHandler = (922 pallet_unique::UniqueSponsorshipHandler<Runtime>,923 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,924 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,925);926927// impl pallet_unq_scheduler::Config for Runtime {928// type Event = Event;929// type Origin = Origin;930// type PalletsOrigin = OriginCaller;931// type Call = Call;932// type MaximumWeight = MaximumSchedulerWeight;933// type ScheduleOrigin = EnsureSigned<AccountId>;934// type MaxScheduledPerBlock = MaxScheduledPerBlock;935// type SponsorshipHandler = SponsorshipHandler;936// type WeightInfo = ();937// }938939impl pallet_evm_transaction_payment::Config for Runtime {940 type EvmSponsorshipHandler = EvmSponsorshipHandler;941 type Currency = Balances;942}943944impl pallet_charge_transaction::Config for Runtime {945 type SponsorshipHandler = SponsorshipHandler;946}947948// impl pallet_contract_helpers::Config for Runtime {949// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;950// }951952parameter_types! {953 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049954 pub const HelpersContractAddress: H160 = H160([955 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,956 ]);957 958 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f959 pub const EvmCollectionHelperAddress: H160 = H160([960 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,961 ]);962}963964impl pallet_evm_contract_helpers::Config for Runtime {965 type ContractAddress = HelpersContractAddress;966 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;967}968969impl evm_collection::Config for Runtime {970 type ContractAddress = EvmCollectionHelperAddress;971}972973construct_runtime!(974 pub enum Runtime where975 Block = Block,976 NodeBlock = opaque::Block,977 UncheckedExtrinsic = UncheckedExtrinsic978 {979 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,980 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,981982 Aura: pallet_aura::{Pallet, Config<T>} = 22,983 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,984985 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,986 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,987 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,988 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,989 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,990 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,991 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,992 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,993 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,994 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,995996 // XCM helpers.997 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,998 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,999 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1000 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10011002 // Unique Pallets1003 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1004 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1005 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1006 // free = 631007 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1008 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1009 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1010 Fungible: pallet_fungible::{Pallet, Storage} = 67,1011 Refungible: pallet_refungible::{Pallet, Storage} = 68,1012 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1013 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1014 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1015 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10161017 // Frontier1018 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1019 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10201021 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1022 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1023 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1024 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1025 }1026);10271028pub struct TransactionConverter;10291030impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1031 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1032 UncheckedExtrinsic::new_unsigned(1033 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1034 )1035 }1036}10371038impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1039 fn convert_transaction(1040 &self,1041 transaction: pallet_ethereum::Transaction,1042 ) -> opaque::UncheckedExtrinsic {1043 let extrinsic = UncheckedExtrinsic::new_unsigned(1044 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1045 );1046 let encoded = extrinsic.encode();1047 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1048 .expect("Encoded extrinsic is always valid")1049 }1050}10511052/// The address format for describing accounts.1053pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1054/// Block header type as expected by this runtime.1055pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1056/// Block type as expected by this runtime.1057pub type Block = generic::Block<Header, UncheckedExtrinsic>;1058/// A Block signed with a Justification1059pub type SignedBlock = generic::SignedBlock<Block>;1060/// BlockId type as expected by this runtime.1061pub type BlockId = generic::BlockId<Block>;1062/// The SignedExtension to the basic transaction logic.1063pub type SignedExtra = (1064 frame_system::CheckSpecVersion<Runtime>,1065 // system::CheckTxVersion<Runtime>,1066 frame_system::CheckGenesis<Runtime>,1067 frame_system::CheckEra<Runtime>,1068 frame_system::CheckNonce<Runtime>,1069 frame_system::CheckWeight<Runtime>,1070 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1071 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1072 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1073);1074/// Unchecked extrinsic type as expected by this runtime.1075pub type UncheckedExtrinsic =1076 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1077/// Extrinsic type that has already been checked.1078pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1079/// Executive: handles dispatch to the various modules.1080pub type Executive = frame_executive::Executive<1081 Runtime,1082 Block,1083 frame_system::ChainContext<Runtime>,1084 Runtime,1085 AllPalletsReversedWithSystemFirst,1086>;10871088impl_opaque_keys! {1089 pub struct SessionKeys {1090 pub aura: Aura,1091 }1092}10931094impl fp_self_contained::SelfContainedCall for Call {1095 type SignedInfo = H160;10961097 fn is_self_contained(&self) -> bool {1098 match self {1099 Call::Ethereum(call) => call.is_self_contained(),1100 _ => false,1101 }1102 }11031104 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1105 match self {1106 Call::Ethereum(call) => call.check_self_contained(),1107 _ => None,1108 }1109 }11101111 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1112 match self {1113 Call::Ethereum(call) => call.validate_self_contained(info),1114 _ => None,1115 }1116 }11171118 fn pre_dispatch_self_contained(1119 &self,1120 info: &Self::SignedInfo,1121 ) -> Option<Result<(), TransactionValidityError>> {1122 match self {1123 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1124 _ => None,1125 }1126 }11271128 fn apply_self_contained(1129 self,1130 info: Self::SignedInfo,1131 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1132 match self {1133 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1134 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1135 )),1136 _ => None,1137 }1138 }1139}11401141macro_rules! dispatch_unique_runtime {1142 ($collection:ident.$method:ident($($name:ident),*)) => {{1143 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1144 let dispatch = collection.as_dyn();11451146 Ok::<_, DispatchError>(dispatch.$method($($name),*))1147 }};1148}11491150impl_common_runtime_apis!();11511152struct CheckInherents;11531154impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1155 fn check_inherents(1156 block: &Block,1157 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1158 ) -> sp_inherents::CheckInherentsResult {1159 let relay_chain_slot = relay_state_proof1160 .read_slot()1161 .expect("Could not read the relay chain slot from the proof");11621163 let inherent_data =1164 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1165 relay_chain_slot,1166 sp_std::time::Duration::from_secs(6),1167 )1168 .create_inherent_data()1169 .expect("Could not create the timestamp inherent data");11701171 inherent_data.check_extrinsics(block)1172 }1173}11741175cumulus_pallet_parachain_system::register_validate_block!(1176 Runtime = Runtime,1177 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1178 CheckInherents = CheckInherents,1179);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::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use up_data_structs::*;70// use pallet_contracts::weights::WeightInfo;71// #[cfg(any(feature = "std", test))]72use frame_system::{73 self as frame_system, EnsureRoot, EnsureSigned,74 limits::{BlockWeights, BlockLength},75};76use sp_arithmetic::{77 traits::{BaseArithmetic, Unsigned},78};79use smallvec::smallvec;80use codec::{Encode, Decode};81use pallet_unique::eth::evm_collection;82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};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 up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};97use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};98use xcm_builder::{99 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,100 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,101 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,102 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,103 ParentIsPreset,104};105use xcm_executor::{Config, XcmExecutor, Assets};106use sp_std::{marker::PhantomData};107108use xcm::latest::{109 // Xcm,110 AssetId::{Concrete},111 Fungibility::Fungible as XcmFungible,112 MultiAsset,113 Error as XcmError,114};115use xcm_executor::traits::{MatchesFungible, WeightTrader};116//use xcm_executor::traits::MatchesFungible;117use sp_runtime::traits::CheckedConversion;118119use unique_runtime_common::{120 impl_common_runtime_apis,121 types::*,122 constants::*,123 dispatch::{CollectionDispatchT, CollectionDispatch},124 sponsoring::UniqueSponsorshipHandler,125 eth_sponsoring::UniqueEthSponsorshipHandler,126 weights::CommonWeights,127};128129pub const RUNTIME_NAME: &str = "quartz";130pub const TOKEN_SYMBOL: &str = "QTZ";131132type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;133134impl RuntimeInstance for Runtime {135 type CrossAccountId = self::CrossAccountId;136137 type TransactionConverter = self::TransactionConverter;138139 fn get_transaction_converter() -> TransactionConverter {140 TransactionConverter141 }142}143144/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know145/// the specifics of the runtime. They can then be made to be agnostic over specific formats146/// of data like extrinsics, allowing for them to continue syncing the network through upgrades147/// to even the core data structures.148pub mod opaque {149 use sp_std::prelude::*;150 use sp_runtime::impl_opaque_keys;151 use super::Aura;152153 pub use unique_runtime_common::types::*;154155 impl_opaque_keys! {156 pub struct SessionKeys {157 pub aura: Aura,158 }159 }160}161162/// This runtime version.163pub const VERSION: RuntimeVersion = RuntimeVersion {164 spec_name: create_runtime_str!(RUNTIME_NAME),165 impl_name: create_runtime_str!(RUNTIME_NAME),166 authoring_version: 1,167 spec_version: 920000,168 impl_version: 0,169 apis: RUNTIME_API_VERSIONS,170 transaction_version: 1,171 state_version: 0,172};173174#[derive(codec::Encode, codec::Decode)]175pub enum XCMPMessage<XAccountId, XBalance> {176 /// Transfer tokens to the given account from the Parachain account.177 TransferToken(XAccountId, XBalance),178}179180/// The version information used to identify this runtime when compiled natively.181#[cfg(feature = "std")]182pub fn native_version() -> NativeVersion {183 NativeVersion {184 runtime_version: VERSION,185 can_author_with: Default::default(),186 }187}188189type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;190191pub struct DealWithFees;192impl OnUnbalanced<NegativeImbalance> for DealWithFees {193 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {194 if let Some(fees) = fees_then_tips.next() {195 // for fees, 100% to treasury196 let mut split = fees.ration(100, 0);197 if let Some(tips) = fees_then_tips.next() {198 // for tips, if any, 100% to treasury199 tips.ration_merge_into(100, 0, &mut split);200 }201 Treasury::on_unbalanced(split.0);202 // Author::on_unbalanced(split.1);203 }204 }205}206207parameter_types! {208 pub const BlockHashCount: BlockNumber = 2400;209 pub RuntimeBlockLength: BlockLength =210 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);211 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);212 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;213 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()214 .base_block(BlockExecutionWeight::get())215 .for_class(DispatchClass::all(), |weights| {216 weights.base_extrinsic = ExtrinsicBaseWeight::get();217 })218 .for_class(DispatchClass::Normal, |weights| {219 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);220 })221 .for_class(DispatchClass::Operational, |weights| {222 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);223 // Operational transactions have some extra reserved space, so that they224 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.225 weights.reserved = Some(226 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT227 );228 })229 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)230 .build_or_panic();231 pub const Version: RuntimeVersion = VERSION;232 pub const SS58Prefix: u8 = 255;233}234235parameter_types! {236 pub const ChainId: u64 = 8881;237}238239pub struct FixedFee;240impl FeeCalculator for FixedFee {241 fn min_gas_price() -> U256 {242 MIN_GAS_PRICE.into()243 }244}245246// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case247// (contract, which only writes a lot of data),248// approximating on top of our real store write weight249parameter_types! {250 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;251 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;252 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();253}254255/// Limiting EVM execution to 50% of block for substrate users and management tasks256/// EVM transaction consumes more weight than substrate's, so we can't rely on them being257/// scheduled fairly258const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);259parameter_types! {260 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());261}262263pub enum FixedGasWeightMapping {}264impl GasWeightMapping for FixedGasWeightMapping {265 fn gas_to_weight(gas: u64) -> Weight {266 gas.saturating_mul(WeightPerGas::get())267 }268 fn weight_to_gas(weight: Weight) -> u64 {269 weight / WeightPerGas::get()270 }271}272273impl pallet_evm::Config for Runtime {274 type BlockGasLimit = BlockGasLimit;275 type FeeCalculator = FixedFee;276 type GasWeightMapping = FixedGasWeightMapping;277 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;278 type CallOrigin = EnsureAddressTruncated<Self>;279 type WithdrawOrigin = EnsureAddressTruncated<Self>;280 type AddressMapping = HashedAddressMapping<Self::Hashing>;281 type PrecompilesType = ();282 type PrecompilesValue = ();283 type Currency = Balances;284 type Event = Event;285 type OnMethodCall = (286 pallet_evm_migration::OnMethodCall<Self>,287 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,288 CollectionDispatchT<Self>,289 evm_collection::CollectionOnMethodCall<Self>,290 evm_collection::CollectionHelperOnMethodCall<Self>,291 );292 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;293 type ChainId = ChainId;294 type Runner = pallet_evm::runner::stack::Runner<Self>;295 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;296 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;297 type FindAuthor = EthereumFindAuthor<Aura>;298}299300impl pallet_evm_migration::Config for Runtime {301 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;302}303304pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);305impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {306 fn find_author<'a, I>(digests: I) -> Option<H160>307 where308 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,309 {310 if let Some(author_index) = F::find_author(digests) {311 let authority_id = Aura::authorities()[author_index as usize].clone();312 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));313 }314 None315 }316}317318impl pallet_ethereum::Config for Runtime {319 type Event = Event;320 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;321}322323impl pallet_randomness_collective_flip::Config for Runtime {}324325impl frame_system::Config for Runtime {326 /// The data to be stored in an account.327 type AccountData = pallet_balances::AccountData<Balance>;328 /// The identifier used to distinguish between accounts.329 type AccountId = AccountId;330 /// The basic call filter to use in dispatchable.331 type BaseCallFilter = Everything;332 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).333 type BlockHashCount = BlockHashCount;334 /// The maximum length of a block (in bytes).335 type BlockLength = RuntimeBlockLength;336 /// The index type for blocks.337 type BlockNumber = BlockNumber;338 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.339 type BlockWeights = RuntimeBlockWeights;340 /// The aggregated dispatch type that is available for extrinsics.341 type Call = Call;342 /// The weight of database operations that the runtime can invoke.343 type DbWeight = RocksDbWeight;344 /// The ubiquitous event type.345 type Event = Event;346 /// The type for hashing blocks and tries.347 type Hash = Hash;348 /// The hashing algorithm used.349 type Hashing = BlakeTwo256;350 /// The header type.351 type Header = generic::Header<BlockNumber, BlakeTwo256>;352 /// The index type for storing how many extrinsics an account has signed.353 type Index = Index;354 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.355 type Lookup = AccountIdLookup<AccountId, ()>;356 /// What to do if an account is fully reaped from the system.357 type OnKilledAccount = ();358 /// What to do if a new account is created.359 type OnNewAccount = ();360 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;361 /// The ubiquitous origin type.362 type Origin = Origin;363 /// This type is being generated by `construct_runtime!`.364 type PalletInfo = PalletInfo;365 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.366 type SS58Prefix = SS58Prefix;367 /// Weight information for the extrinsics of this pallet.368 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;369 /// Version of the runtime.370 type Version = Version;371 type MaxConsumers = ConstU32<16>;372}373374parameter_types! {375 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;376}377378impl pallet_timestamp::Config for Runtime {379 /// A timestamp: milliseconds since the unix epoch.380 type Moment = u64;381 type OnTimestampSet = ();382 type MinimumPeriod = MinimumPeriod;383 type WeightInfo = ();384}385386parameter_types! {387 // pub const ExistentialDeposit: u128 = 500;388 pub const ExistentialDeposit: u128 = 0;389 pub const MaxLocks: u32 = 50;390}391392impl pallet_balances::Config for Runtime {393 type MaxLocks = MaxLocks;394 type MaxReserves = ();395 type ReserveIdentifier = [u8; 8];396 /// The type for recording an account's balance.397 type Balance = Balance;398 /// The ubiquitous event type.399 type Event = Event;400 type DustRemoval = Treasury;401 type ExistentialDeposit = ExistentialDeposit;402 type AccountStore = System;403 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;404}405406pub const fn deposit(items: u32, bytes: u32) -> Balance {407 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE408}409410/*411parameter_types! {412 pub TombstoneDeposit: Balance = deposit(413 1,414 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,415 );416 pub DepositPerContract: Balance = TombstoneDeposit::get();417 pub const DepositPerStorageByte: Balance = deposit(0, 1);418 pub const DepositPerStorageItem: Balance = deposit(1, 0);419 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);420 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;421 pub const SignedClaimHandicap: u32 = 2;422 pub const MaxDepth: u32 = 32;423 pub const MaxValueSize: u32 = 16 * 1024;424 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb425 // The lazy deletion runs inside on_initialize.426 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *427 RuntimeBlockWeights::get().max_block;428 // The weight needed for decoding the queue should be less or equal than a fifth429 // of the overall weight dedicated to the lazy deletion.430 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (431 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -432 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)433 )) / 5) as u32;434 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();435}436437impl pallet_contracts::Config for Runtime {438 type Time = Timestamp;439 type Randomness = RandomnessCollectiveFlip;440 type Currency = Balances;441 type Event = Event;442 type RentPayment = ();443 type SignedClaimHandicap = SignedClaimHandicap;444 type TombstoneDeposit = TombstoneDeposit;445 type DepositPerContract = DepositPerContract;446 type DepositPerStorageByte = DepositPerStorageByte;447 type DepositPerStorageItem = DepositPerStorageItem;448 type RentFraction = RentFraction;449 type SurchargeReward = SurchargeReward;450 type WeightPrice = pallet_transaction_payment::Pallet<Self>;451 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;452 type ChainExtension = NFTExtension;453 type DeletionQueueDepth = DeletionQueueDepth;454 type DeletionWeightLimit = DeletionWeightLimit;455 type Schedule = Schedule;456 type CallStack = [pallet_contracts::Frame<Self>; 31];457}458*/459460parameter_types! {461 /// This value increases the priority of `Operational` transactions by adding462 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.463 pub const OperationalFeeMultiplier: u8 = 5;464}465466/// Linear implementor of `WeightToFeePolynomial`467pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);468469impl<T> WeightToFeePolynomial for LinearFee<T>470where471 T: BaseArithmetic + From<u32> + Copy + Unsigned,472{473 type Balance = T;474475 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {476 smallvec!(WeightToFeeCoefficient {477 // Targeting 0.1 Unique per NFT transfer478 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),479 coeff_frac: Perbill::zero(),480 negative: false,481 degree: 1,482 })483 }484}485486impl pallet_transaction_payment::Config for Runtime {487 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;488 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;489 type OperationalFeeMultiplier = OperationalFeeMultiplier;490 type WeightToFee = LinearFee<Balance>;491 type FeeMultiplierUpdate = ();492}493494parameter_types! {495 pub const ProposalBond: Permill = Permill::from_percent(5);496 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;497 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;498 pub const SpendPeriod: BlockNumber = 5 * MINUTES;499 pub const Burn: Permill = Permill::from_percent(0);500 pub const TipCountdown: BlockNumber = 1 * DAYS;501 pub const TipFindersFee: Percent = Percent::from_percent(20);502 pub const TipReportDepositBase: Balance = 1 * UNIQUE;503 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;504 pub const BountyDepositBase: Balance = 1 * UNIQUE;505 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;506 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");507 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;508 pub const MaximumReasonLength: u32 = 16384;509 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);510 pub const BountyValueMinimum: Balance = 5 * UNIQUE;511 pub const MaxApprovals: u32 = 100;512}513514impl pallet_treasury::Config for Runtime {515 type PalletId = TreasuryModuleId;516 type Currency = Balances;517 type ApproveOrigin = EnsureRoot<AccountId>;518 type RejectOrigin = EnsureRoot<AccountId>;519 type Event = Event;520 type OnSlash = ();521 type ProposalBond = ProposalBond;522 type ProposalBondMinimum = ProposalBondMinimum;523 type ProposalBondMaximum = ProposalBondMaximum;524 type SpendPeriod = SpendPeriod;525 type Burn = Burn;526 type BurnDestination = ();527 type SpendFunds = ();528 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;529 type MaxApprovals = MaxApprovals;530}531532impl pallet_sudo::Config for Runtime {533 type Event = Event;534 type Call = Call;535}536537pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);538539impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider540 for RelayChainBlockNumberProvider<T>541{542 type BlockNumber = BlockNumber;543544 fn current_block_number() -> Self::BlockNumber {545 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()546 .map(|d| d.relay_parent_number)547 .unwrap_or_default()548 }549}550551parameter_types! {552 pub const MinVestedTransfer: Balance = 10 * UNIQUE;553 pub const MaxVestingSchedules: u32 = 28;554}555556impl orml_vesting::Config for Runtime {557 type Event = Event;558 type Currency = pallet_balances::Pallet<Runtime>;559 type MinVestedTransfer = MinVestedTransfer;560 type VestedTransferOrigin = EnsureSigned<AccountId>;561 type WeightInfo = ();562 type MaxVestingSchedules = MaxVestingSchedules;563 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;564}565566parameter_types! {567 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;568 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;569}570571impl cumulus_pallet_parachain_system::Config for Runtime {572 type Event = Event;573 type SelfParaId = parachain_info::Pallet<Self>;574 type OnSystemEvent = ();575 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<576 // MaxDownwardMessageWeight,577 // XcmExecutor<XcmConfig>,578 // Call,579 // >;580 type OutboundXcmpMessageSource = XcmpQueue;581 type DmpMessageHandler = DmpQueue;582 type ReservedDmpWeight = ReservedDmpWeight;583 type ReservedXcmpWeight = ReservedXcmpWeight;584 type XcmpMessageHandler = XcmpQueue;585}586587impl parachain_info::Config for Runtime {}588589impl cumulus_pallet_aura_ext::Config for Runtime {}590591parameter_types! {592 pub const RelayLocation: MultiLocation = MultiLocation::parent();593 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;594 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();595 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();596}597598/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used599/// when determining ownership of accounts for asset transacting and when attempting to use XCM600/// `Transact` in order to determine the dispatch Origin.601pub type LocationToAccountId = (602 // The parent (Relay-chain) origin converts to the default `AccountId`.603 ParentIsPreset<AccountId>,604 // Sibling parachain origins convert to AccountId via the `ParaId::into`.605 SiblingParachainConvertsVia<Sibling, AccountId>,606 // Straight up local `AccountId32` origins just alias directly to `AccountId`.607 AccountId32Aliases<RelayNetwork, AccountId>,608);609610pub struct OnlySelfCurrency;611impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {612 fn matches_fungible(a: &MultiAsset) -> Option<B> {613 match (&a.id, &a.fun) {614 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),615 _ => None,616 }617 }618}619620/// Means for transacting assets on this chain.621pub type LocalAssetTransactor = CurrencyAdapter<622 // Use this currency:623 Balances,624 // Use this currency when it is a fungible asset matching the given location or name:625 OnlySelfCurrency,626 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:627 LocationToAccountId,628 // Our chain's account ID type (we can't get away without mentioning it explicitly):629 AccountId,630 // We don't track any teleports.631 (),632>;633634/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,635/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can636/// biases the kind of local `Origin` it will become.637pub type XcmOriginToTransactDispatchOrigin = (638 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location639 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for640 // foreign chains who want to have a local sovereign account on this chain which they control.641 SovereignSignedViaLocation<LocationToAccountId, Origin>,642 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when643 // recognised.644 RelayChainAsNative<RelayOrigin, Origin>,645 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when646 // recognised.647 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,648 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a649 // transaction from the Root origin.650 ParentAsSuperuser<Origin>,651 // Native signed account converter; this just converts an `AccountId32` origin into a normal652 // `Origin::Signed` origin of the same 32-byte value.653 SignedAccountId32AsNative<RelayNetwork, Origin>,654 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.655 XcmPassthrough<Origin>,656);657658parameter_types! {659 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.660 pub UnitWeightCost: Weight = 1_000_000;661 // 1200 UNIQUEs buy 1 second of weight.662 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);663 pub const MaxInstructions: u32 = 100;664 pub const MaxAuthorities: u32 = 100_000;665}666667match_types! {668 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {669 MultiLocation { parents: 1, interior: Here } |670 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }671 };672}673674pub type Barrier = (675 TakeWeightCredit,676 AllowTopLevelPaidExecutionFrom<Everything>,677 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,678 // ^^^ Parent & its unit plurality gets free execution679);680681pub struct UsingOnlySelfCurrencyComponents<682 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,683 AssetId: Get<MultiLocation>,684 AccountId,685 Currency: CurrencyT<AccountId>,686 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,687>(688 Weight,689 Currency::Balance,690 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,691);692impl<693 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,694 AssetId: Get<MultiLocation>,695 AccountId,696 Currency: CurrencyT<AccountId>,697 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,698 > WeightTrader699 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>700{701 fn new() -> Self {702 Self(0, Zero::zero(), PhantomData)703 }704705 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {706 let amount = WeightToFee::calc(&weight);707 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;708709 // location to this parachain through relay chain710 let option1: xcm::v1::AssetId = Concrete(MultiLocation {711 parents: 1,712 interior: X1(Parachain(ParachainInfo::parachain_id().into())),713 });714 // direct location715 let option2: xcm::v1::AssetId = Concrete(MultiLocation {716 parents: 0,717 interior: Here,718 });719720 let required = if payment.fungible.contains_key(&option1) {721 (option1, u128_amount).into()722 } else if payment.fungible.contains_key(&option2) {723 (option2, u128_amount).into()724 } else {725 (Concrete(MultiLocation::default()), u128_amount).into()726 };727728 let unused = payment729 .checked_sub(required)730 .map_err(|_| XcmError::TooExpensive)?;731 self.0 = self.0.saturating_add(weight);732 self.1 = self.1.saturating_add(amount);733 Ok(unused)734 }735736 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {737 let weight = weight.min(self.0);738 let amount = WeightToFee::calc(&weight);739 self.0 -= weight;740 self.1 = self.1.saturating_sub(amount);741 let amount: u128 = amount.saturated_into();742 if amount > 0 {743 Some((AssetId::get(), amount).into())744 } else {745 None746 }747 }748}749impl<750 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,751 AssetId: Get<MultiLocation>,752 AccountId,753 Currency: CurrencyT<AccountId>,754 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,755 > Drop756 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>757{758 fn drop(&mut self) {759 OnUnbalanced::on_unbalanced(Currency::issue(self.1));760 }761}762763pub struct XcmConfig;764impl Config for XcmConfig {765 type Call = Call;766 type XcmSender = XcmRouter;767 // How to withdraw and deposit an asset.768 type AssetTransactor = LocalAssetTransactor;769 type OriginConverter = XcmOriginToTransactDispatchOrigin;770 type IsReserve = NativeAsset;771 type IsTeleporter = (); // Teleportation is disabled772 type LocationInverter = LocationInverter<Ancestry>;773 type Barrier = Barrier;774 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;775 type Trader = UsingOnlySelfCurrencyComponents<776 IdentityFee<Balance>,777 RelayLocation,778 AccountId,779 Balances,780 (),781 >;782 type ResponseHandler = (); // Don't handle responses for now.783 type SubscriptionService = PolkadotXcm;784785 type AssetTrap = PolkadotXcm;786 type AssetClaims = PolkadotXcm;787}788789// parameter_types! {790// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;791// }792793/// No local origins on this chain are allowed to dispatch XCM sends/executions.794pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);795796/// The means for routing XCM messages which are not for local execution into the right message797/// queues.798pub type XcmRouter = (799 // Two routers - use UMP to communicate with the relay chain:800 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,801 // ..and XCMP to communicate with the sibling chains.802 XcmpQueue,803);804805impl pallet_evm_coder_substrate::Config for Runtime {806 type GasWeightMapping = FixedGasWeightMapping;807}808809impl pallet_xcm::Config for Runtime {810 type Event = Event;811 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;812 type XcmRouter = XcmRouter;813 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;814 type XcmExecuteFilter = Everything;815 type XcmExecutor = XcmExecutor<XcmConfig>;816 type XcmTeleportFilter = Everything;817 type XcmReserveTransferFilter = Everything;818 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;819 type LocationInverter = LocationInverter<Ancestry>;820 type Origin = Origin;821 type Call = Call;822 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;823 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;824}825826impl cumulus_pallet_xcm::Config for Runtime {827 type Event = Event;828 type XcmExecutor = XcmExecutor<XcmConfig>;829}830831impl cumulus_pallet_xcmp_queue::Config for Runtime {832 type WeightInfo = ();833 type Event = Event;834 type XcmExecutor = XcmExecutor<XcmConfig>;835 type ChannelInfo = ParachainSystem;836 type VersionWrapper = ();837 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;838 type ControllerOrigin = EnsureRoot<AccountId>;839 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;840}841842impl cumulus_pallet_dmp_queue::Config for Runtime {843 type Event = Event;844 type XcmExecutor = XcmExecutor<XcmConfig>;845 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;846}847848impl pallet_aura::Config for Runtime {849 type AuthorityId = AuraId;850 type DisabledValidators = ();851 type MaxAuthorities = MaxAuthorities;852}853854parameter_types! {855 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();856 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;857}858859impl pallet_common::Config for Runtime {860 type Event = Event;861862 type Currency = Balances;863 type CollectionCreationPrice = CollectionCreationPrice;864 type TreasuryAccountId = TreasuryAccountId;865 type CollectionDispatch = CollectionDispatchT<Self>;866867 type EvmTokenAddressMapping = EvmTokenAddressMapping;868 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;869}870871impl pallet_structure::Config for Runtime {872 type Event = Event;873 type Call = Call;874 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;875}876877impl pallet_evm::account::Config for Runtime {878 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;879 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;880 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;881}882883impl pallet_fungible::Config for Runtime {884 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;885}886impl pallet_refungible::Config for Runtime {887 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;888}889impl pallet_nonfungible::Config for Runtime {890 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;891}892893impl pallet_proxy_rmrk_core::Config for Runtime {894 type Event = Event;895}896897impl pallet_proxy_rmrk_equip::Config for Runtime {898 type Event = Event;899}900901impl pallet_unique::Config for Runtime {902 type Event = Event;903 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;904 type CommonWeightInfo = CommonWeights<Self>;905}906907parameter_types! {908 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied909}910911/// Used for the pallet inflation912impl pallet_inflation::Config for Runtime {913 type Currency = Balances;914 type TreasuryAccountId = TreasuryAccountId;915 type InflationBlockInterval = InflationBlockInterval;916 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;917}918919// parameter_types! {920// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *921// RuntimeBlockWeights::get().max_block;922// pub const MaxScheduledPerBlock: u32 = 50;923// }924925type EvmSponsorshipHandler = (926 UniqueEthSponsorshipHandler<Runtime>,927 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,928);929type SponsorshipHandler = (930 UniqueSponsorshipHandler<Runtime>,931 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,932 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,933);934935// impl pallet_unq_scheduler::Config for Runtime {936// type Event = Event;937// type Origin = Origin;938// type PalletsOrigin = OriginCaller;939// type Call = Call;940// type MaximumWeight = MaximumSchedulerWeight;941// type ScheduleOrigin = EnsureSigned<AccountId>;942// type MaxScheduledPerBlock = MaxScheduledPerBlock;943// type SponsorshipHandler = SponsorshipHandler;944// type WeightInfo = ();945// }946947impl pallet_evm_transaction_payment::Config for Runtime {948 type EvmSponsorshipHandler = EvmSponsorshipHandler;949 type Currency = Balances;950}951952impl pallet_charge_transaction::Config for Runtime {953 type SponsorshipHandler = SponsorshipHandler;954}955956// impl pallet_contract_helpers::Config for Runtime {957// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;958// }959960parameter_types! {961 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049962 pub const HelpersContractAddress: H160 = H160([963 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,964 ]);965 966 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f967 pub const EvmCollectionHelperAddress: H160 = H160([968 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,969 ]);970}971972impl pallet_evm_contract_helpers::Config for Runtime {973 type ContractAddress = HelpersContractAddress;974 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;975}976977impl evm_collection::Config for Runtime {978 type ContractAddress = EvmCollectionHelperAddress;979}980981construct_runtime!(982 pub enum Runtime where983 Block = Block,984 NodeBlock = opaque::Block,985 UncheckedExtrinsic = UncheckedExtrinsic986 {987 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,988 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,989990 Aura: pallet_aura::{Pallet, Config<T>} = 22,991 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,992993 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,994 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,995 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,996 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,997 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,998 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,999 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1000 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1001 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1002 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10031004 // XCM helpers.1005 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1006 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1007 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1008 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10091010 // Unique Pallets1011 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1012 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1013 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1014 // free = 631015 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1016 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1017 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1018 Fungible: pallet_fungible::{Pallet, Storage} = 67,1019 Refungible: pallet_refungible::{Pallet, Storage} = 68,1020 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1021 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1022 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1023 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10241025 // Frontier1026 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1027 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10281029 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1030 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1031 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1032 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1033 }1034);10351036pub struct TransactionConverter;10371038impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1039 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1040 UncheckedExtrinsic::new_unsigned(1041 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1042 )1043 }1044}10451046impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1047 fn convert_transaction(1048 &self,1049 transaction: pallet_ethereum::Transaction,1050 ) -> opaque::UncheckedExtrinsic {1051 let extrinsic = UncheckedExtrinsic::new_unsigned(1052 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1053 );1054 let encoded = extrinsic.encode();1055 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1056 .expect("Encoded extrinsic is always valid")1057 }1058}10591060/// The address format for describing accounts.1061pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1062/// Block header type as expected by this runtime.1063pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1064/// Block type as expected by this runtime.1065pub type Block = generic::Block<Header, UncheckedExtrinsic>;1066/// A Block signed with a Justification1067pub type SignedBlock = generic::SignedBlock<Block>;1068/// BlockId type as expected by this runtime.1069pub type BlockId = generic::BlockId<Block>;1070/// The SignedExtension to the basic transaction logic.1071pub type SignedExtra = (1072 frame_system::CheckSpecVersion<Runtime>,1073 // system::CheckTxVersion<Runtime>,1074 frame_system::CheckGenesis<Runtime>,1075 frame_system::CheckEra<Runtime>,1076 frame_system::CheckNonce<Runtime>,1077 frame_system::CheckWeight<Runtime>,1078 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1079 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1080 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1081);1082/// Unchecked extrinsic type as expected by this runtime.1083pub type UncheckedExtrinsic =1084 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1085/// Extrinsic type that has already been checked.1086pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1087/// Executive: handles dispatch to the various modules.1088pub type Executive = frame_executive::Executive<1089 Runtime,1090 Block,1091 frame_system::ChainContext<Runtime>,1092 Runtime,1093 AllPalletsReversedWithSystemFirst,1094>;10951096impl_opaque_keys! {1097 pub struct SessionKeys {1098 pub aura: Aura,1099 }1100}11011102impl fp_self_contained::SelfContainedCall for Call {1103 type SignedInfo = H160;11041105 fn is_self_contained(&self) -> bool {1106 match self {1107 Call::Ethereum(call) => call.is_self_contained(),1108 _ => false,1109 }1110 }11111112 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1113 match self {1114 Call::Ethereum(call) => call.check_self_contained(),1115 _ => None,1116 }1117 }11181119 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1120 match self {1121 Call::Ethereum(call) => call.validate_self_contained(info),1122 _ => None,1123 }1124 }11251126 fn pre_dispatch_self_contained(1127 &self,1128 info: &Self::SignedInfo,1129 ) -> Option<Result<(), TransactionValidityError>> {1130 match self {1131 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1132 _ => None,1133 }1134 }11351136 fn apply_self_contained(1137 self,1138 info: Self::SignedInfo,1139 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1140 match self {1141 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1142 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1143 )),1144 _ => None,1145 }1146 }1147}11481149macro_rules! dispatch_unique_runtime {1150 ($collection:ident.$method:ident($($name:ident),*)) => {{1151 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1152 let dispatch = collection.as_dyn();11531154 Ok::<_, DispatchError>(dispatch.$method($($name),*))1155 }};1156}11571158impl_common_runtime_apis!();11591160struct CheckInherents;11611162impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1163 fn check_inherents(1164 block: &Block,1165 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1166 ) -> sp_inherents::CheckInherentsResult {1167 let relay_chain_slot = relay_state_proof1168 .read_slot()1169 .expect("Could not read the relay chain slot from the proof");11701171 let inherent_data =1172 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1173 relay_chain_slot,1174 sp_std::time::Duration::from_secs(6),1175 )1176 .create_inherent_data()1177 .expect("Could not create the timestamp inherent data");11781179 inherent_data.check_extrinsics(block)1180 }1181}11821183cumulus_pallet_parachain_system::register_validate_block!(1184 Runtime = Runtime,1185 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1186 CheckInherents = CheckInherents,1187);runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -50,6 +50,7 @@
pub use pallet_balances::Call as BalancesCall;
pub use pallet_evm::{
EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _, OnMethodCall,
+ Account as EVMAccount, FeeCalculator, GasWeightMapping,
};
pub use frame_support::{
construct_runtime, match_types,
@@ -84,8 +85,7 @@
};
use smallvec::smallvec;
use codec::{Encode, Decode};
-use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};
-use pallet_unique::evm_collection;
+use pallet_unique::eth::evm_collection;
use fp_rpc::TransactionStatus;
use sp_runtime::{
traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},
@@ -121,7 +121,15 @@
//use xcm_executor::traits::MatchesFungible;
use sp_runtime::traits::CheckedConversion;
-use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};
+use unique_runtime_common::{
+ impl_common_runtime_apis,
+ types::*,
+ constants::*,
+ dispatch::{CollectionDispatchT, CollectionDispatch},
+ sponsoring::UniqueSponsorshipHandler,
+ eth_sponsoring::UniqueEthSponsorshipHandler,
+ weights::CommonWeights,
+};
pub const RUNTIME_NAME: &str = "unique";
pub const TOKEN_SYMBOL: &str = "UNQ";