difftreelog
fix evm nitpicks
in: master
11 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -4290,9 +4290,6 @@
version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"
-dependencies = [
- "spin",
-]
[[package]]
name = "lazycell"
@@ -5920,7 +5917,6 @@
"frame-benchmarking",
"frame-support",
"frame-system",
- "lazy_static",
"pallet-evm",
"pallet-evm-coder-substrate",
"parity-scale-codec 3.1.2",
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -27,7 +27,6 @@
scale-info = { version = "2.0.1", default-features = false, features = [
"derive",
] }
-lazy_static = { version = "1.4.0", default-features = false, features = ["spin_no_std"] }
[features]
default = ["std"]
pallets/common/src/erc.rsdiffbeforeafterboth--- a/pallets/common/src/erc.rs
+++ b/pallets/common/src/erc.rs
@@ -15,7 +15,7 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use evm_coder::{
- solidity_interface,
+ solidity_interface, solidity,
types::*,
execution::{Result, Error},
};
@@ -88,40 +88,64 @@
Ok(())
}
- fn set_limit(&mut self, caller: caller, limit: string, value: string) -> Result<void> {
+ #[solidity(rename_selector = "setLimit")]
+ fn set_int_limit(&mut self, caller: caller, limit: string, value: uint32) -> Result<void> {
check_is_owner(caller, self)?;
let mut limits = self.limits.clone();
match limit.as_str() {
"accountTokenOwnershipLimit" => {
- limits.account_token_ownership_limit = parse_int(value)?;
+ limits.account_token_ownership_limit = Some(value);
}
"sponsoredDataSize" => {
- limits.sponsored_data_size = parse_int(value)?;
+ limits.sponsored_data_size = Some(value);
}
"sponsoredDataRateLimit" => {
- limits.sponsored_data_rate_limit =
- Some(SponsoringRateLimit::Blocks(parse_int(value)?.unwrap()));
+ limits.sponsored_data_rate_limit = Some(SponsoringRateLimit::Blocks(value));
}
"tokenLimit" => {
- limits.token_limit = parse_int(value)?;
+ limits.token_limit = Some(value);
}
"sponsorTransferTimeout" => {
- limits.sponsor_transfer_timeout = parse_int(value)?;
+ limits.sponsor_transfer_timeout = Some(value);
}
"sponsorApproveTimeout" => {
- limits.sponsor_approve_timeout = parse_int(value)?;
+ limits.sponsor_approve_timeout = Some(value);
}
+ _ => {
+ return Err(Error::Revert(format!(
+ "Unknown integer limit \"{}\"",
+ limit
+ )))
+ }
+ }
+ self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
+ .map_err(dispatch_to_evm::<T>)?;
+ save(self);
+ Ok(())
+ }
+
+ #[solidity(rename_selector = "setLimit")]
+ fn set_bool_limit(&mut self, caller: caller, limit: string, value: bool) -> Result<void> {
+ check_is_owner(caller, self)?;
+ let mut limits = self.limits.clone();
+
+ match limit.as_str() {
"ownerCanTransfer" => {
- limits.owner_can_transfer = parse_bool(value)?;
+ limits.owner_can_transfer = Some(value);
}
"ownerCanDestroy" => {
- limits.owner_can_destroy = parse_bool(value)?;
+ limits.owner_can_destroy = Some(value);
}
"transfersEnabled" => {
- limits.transfers_enabled = parse_bool(value)?;
+ limits.transfers_enabled = Some(value);
}
- _ => return Err(Error::Revert(format!("Unknown limit \"{}\"", limit))),
+ _ => {
+ return Err(Error::Revert(format!(
+ "Unknown boolean limit \"{}\"",
+ limit
+ )))
+ }
}
self.limits = <Pallet<T>>::clamp_limits(self.mode.clone(), &self.limits, limits)
.map_err(dispatch_to_evm::<T>)?;
@@ -146,16 +170,9 @@
<crate::CollectionById<T>>::insert(collection.id, collection.collection.clone());
}
-fn parse_int(value: string) -> Result<Option<u32>> {
- value
- .parse::<u32>()
- .map_err(|e| Error::Revert(format!("Int value \"{}\" parse error: {}", value, e)))
- .map(|value| Some(value))
-}
-
-fn parse_bool(value: string) -> Result<Option<bool>> {
- value
- .parse::<bool>()
- .map_err(|e| Error::Revert(format!("Bool value \"{}\" parse error: {}", value, e)))
- .map(|value| Some(value))
+pub fn token_uri_key() -> up_data_structs::PropertyKey {
+ b"tokenURI"
+ .to_vec()
+ .try_into()
+ .expect("length < limit; qed")
}
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -17,14 +17,6 @@
use up_data_structs::CollectionId;
use sp_core::H160;
-lazy_static::lazy_static! {
- pub static ref KEY_TOKEN_URI: up_data_structs::PropertyKey = {
- let key: evm_coder::types::string = "tokenURI".into(); //TODO: make static
- let key: up_data_structs::PropertyKey = key.into_bytes().try_into().expect("Can't create \"tokenURI\" key");
- key
- };
-}
-
// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
// TODO: Unhardcode prefix
const ETH_COLLECTION_PREFIX: [u8; 16] = [
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -22,14 +22,14 @@
use evm_coder::{ToLog, execution::*, generate_stubgen, solidity, solidity_interface, types::*, weight};
use frame_support::BoundedVec;
use up_data_structs::{
- TokenId, SchemaVersion, PropertyPermission, PropertyKeyPermission, Property, CollectionId,
- PropertyKey, CollectionPropertiesVec,
+ TokenId, PropertyPermission, PropertyKeyPermission, Property, CollectionId, PropertyKey,
+ CollectionPropertiesVec,
};
use pallet_evm_coder_substrate::dispatch_to_evm;
use sp_core::{H160, U256};
use sp_std::vec::Vec;
use pallet_common::{
- erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
+ erc::{CommonEvmHandler, PrecompileResult, CollectionCall, token_uri_key},
CollectionHandle, CollectionPropertyPermissions,
};
use pallet_evm::account::CrossAccountId;
@@ -161,7 +161,7 @@
/// Returns token's const_metadata
#[solidity(rename_selector = "tokenURI")]
fn token_uri(&self, token_id: uint256) -> Result<string> {
- let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ let key = token_uri_key();
if !has_token_permission::<T>(self.id, &key) {
return Err("No tokenURI permission".into());
}
@@ -362,7 +362,7 @@
token_id: uint256,
token_uri: string,
) -> Result<bool> {
- let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ let key = token_uri_key();
let permission = get_token_permission::<T>(self.id, &key)?;
if !permission.collection_admin {
return Err("Operation is not allowed".into());
@@ -524,6 +524,7 @@
to: address,
tokens: Vec<(uint256, string)>,
) -> Result<bool> {
+ let key = token_uri_key();
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
let mut expected_index = <TokensMinted<T>>::get(self.id)
@@ -541,8 +542,19 @@
}
expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
+ let mut properties = CollectionPropertiesVec::default();
+ properties
+ .try_push(Property {
+ key: key.clone(),
+ value: token_uri
+ .into_bytes()
+ .try_into()
+ .map_err(|_| "token uri is too long")?,
+ })
+ .map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+
data.push(CreateItemData::<T> {
- properties: BoundedVec::default(),
+ properties,
owner: to.clone(),
});
}
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -15,29 +15,20 @@
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
use core::marker::PhantomData;
-use evm_coder::{execution::*, generate_stubgen, solidity_interface, types::*, ToLog};
+use evm_coder::{execution::*, generate_stubgen, solidity_interface, weight, types::*};
use ethereum as _;
use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
-use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId, Pallet as PalletEvm};
+use pallet_evm::{OnMethodCall, PrecompileResult, account::CrossAccountId};
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::CollectionById;
+use pallet_common::{CollectionById, erc::token_uri_key};
+use crate::{SelfWeightOf, Config, weights::WeightInfo};
use sp_std::vec::Vec;
use alloc::format;
-
-pub trait Config:
- frame_system::Config
- + pallet_evm_coder_substrate::Config
- + pallet_evm::account::Config
- + pallet_nonfungible::Config
-{
- type ContractAddress: Get<H160>;
-}
struct EvmCollectionHelper<T: Config>(SubstrateRecorder<T>);
impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
@@ -51,8 +42,9 @@
}
#[solidity_interface(name = "CollectionHelper")]
-impl<T: Config> EvmCollectionHelper<T> {
- fn create_721_collection(
+impl<T: Config + pallet_nonfungible::Config> EvmCollectionHelper<T> {
+ #[weight(<SelfWeightOf<T>>::create_collection())]
+ fn create_nonfungible_collection(
&self,
caller: caller,
name: string,
@@ -77,7 +69,7 @@
.try_into()
.map_err(|_| error_feild_too_long(stringify!(token_prefix), MAX_TOKEN_PREFIX_LENGTH))?;
- let key = pallet_common::eth::KEY_TOKEN_URI.clone();
+ let key = token_uri_key();
let permission = up_data_structs::PropertyPermission {
mutable: true,
collection_admin: true,
@@ -102,13 +94,6 @@
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
let address = pallet_common::eth::collection_id_to_address(collection_id);
- <PalletEvm<T>>::deposit_log(
- EthCollectionEvent::CollectionCreated {
- owner: *caller.as_eth(),
- collection_id: address,
- }
- .to_log(address),
- );
Ok(address)
}
@@ -122,18 +107,8 @@
}
}
-#[derive(ToLog)]
-pub enum EthCollectionEvent {
- CollectionCreated {
- #[indexed]
- owner: address,
- #[indexed]
- collection_id: address,
- },
-}
-
pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
-impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
+impl<T: Config + pallet_nonfungible::Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
fn is_reserved(contract: &sp_core::H160) -> bool {
contract == &T::ContractAddress::get()
}
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -30,17 +30,18 @@
ensure,
weights::{Weight},
transactional,
- pallet_prelude::{DispatchResultWithPostInfo, ConstU32},
+ pallet_prelude::{DispatchResultWithPostInfo, ConstU32, Get},
BoundedVec,
};
+use sp_core::H160;
use scale_info::TypeInfo;
use frame_system::{self as system, ensure_signed};
use sp_runtime::{sp_std::prelude::Vec};
use up_data_structs::{
MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
- AccessMode, CreateItemData, CollectionLimits, CollectionPermissions, CollectionId,
- CollectionMode, TokenId, SponsorshipState, CreateCollectionData, CreateItemExData, budget,
- Property, PropertyKey, PropertyKeyPermission,
+ CreateItemData, CollectionLimits, CollectionPermissions, CollectionId, CollectionMode, TokenId,
+ SponsorshipState, CreateCollectionData, CreateItemExData, budget, Property, PropertyKey,
+ PropertyKeyPermission,
};
use pallet_evm::account::CrossAccountId;
use pallet_common::{
@@ -74,6 +75,7 @@
/// Weight information for extrinsics in this pallet.
type WeightInfo: WeightInfo;
type CommonWeightInfo: CommonWeightInfo<Self::CrossAccountId>;
+ type ContractAddress: Get<H160>;
}
decl_event! {
runtime/opal/src/lib.rsdiffbeforeafterboth--- a/runtime/opal/src/lib.rs
+++ b/runtime/opal/src/lib.rs
@@ -917,6 +917,7 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
+ type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -987,10 +988,6 @@
impl pallet_evm_contract_helpers::Config for Runtime {
type ContractAddress = HelpersContractAddress;
type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
-}
-
-impl pallet_unique::eth::Config for Runtime {
- type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
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 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_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};82use fp_rpc::TransactionStatus;83use sp_runtime::{84 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85 transaction_validity::TransactionValidityError,86 SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;90pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 impl_common_runtime_apis,120 types::*,121 constants::*,122 dispatch::{CollectionDispatchT, CollectionDispatch},123 sponsoring::UniqueSponsorshipHandler,124 eth_sponsoring::UniqueEthSponsorshipHandler,125 weights::CommonWeights,126};127128pub const RUNTIME_NAME: &str = "quartz";129pub const TOKEN_SYMBOL: &str = "QTZ";130131type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;132133impl RuntimeInstance for Runtime {134 type CrossAccountId = self::CrossAccountId;135136 type TransactionConverter = self::TransactionConverter;137138 fn get_transaction_converter() -> TransactionConverter {139 TransactionConverter140 }141}142143/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know144/// the specifics of the runtime. They can then be made to be agnostic over specific formats145/// of data like extrinsics, allowing for them to continue syncing the network through upgrades146/// to even the core data structures.147pub mod opaque {148 use sp_std::prelude::*;149 use sp_runtime::impl_opaque_keys;150 use super::Aura;151152 pub use unique_runtime_common::types::*;153154 impl_opaque_keys! {155 pub struct SessionKeys {156 pub aura: Aura,157 }158 }159}160161/// This runtime version.162pub const VERSION: RuntimeVersion = RuntimeVersion {163 spec_name: create_runtime_str!(RUNTIME_NAME),164 impl_name: create_runtime_str!(RUNTIME_NAME),165 authoring_version: 1,166 spec_version: 921000,167 impl_version: 0,168 apis: RUNTIME_API_VERSIONS,169 transaction_version: 1,170 state_version: 0,171};172173#[derive(codec::Encode, codec::Decode)]174pub enum XCMPMessage<XAccountId, XBalance> {175 /// Transfer tokens to the given account from the Parachain account.176 TransferToken(XAccountId, XBalance),177}178179/// The version information used to identify this runtime when compiled natively.180#[cfg(feature = "std")]181pub fn native_version() -> NativeVersion {182 NativeVersion {183 runtime_version: VERSION,184 can_author_with: Default::default(),185 }186}187188type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;189190pub struct DealWithFees;191impl OnUnbalanced<NegativeImbalance> for DealWithFees {192 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {193 if let Some(fees) = fees_then_tips.next() {194 // for fees, 100% to treasury195 let mut split = fees.ration(100, 0);196 if let Some(tips) = fees_then_tips.next() {197 // for tips, if any, 100% to treasury198 tips.ration_merge_into(100, 0, &mut split);199 }200 Treasury::on_unbalanced(split.0);201 // Author::on_unbalanced(split.1);202 }203 }204}205206parameter_types! {207 pub const BlockHashCount: BlockNumber = 2400;208 pub RuntimeBlockLength: BlockLength =209 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);210 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);211 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;212 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()213 .base_block(BlockExecutionWeight::get())214 .for_class(DispatchClass::all(), |weights| {215 weights.base_extrinsic = ExtrinsicBaseWeight::get();216 })217 .for_class(DispatchClass::Normal, |weights| {218 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);219 })220 .for_class(DispatchClass::Operational, |weights| {221 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);222 // Operational transactions have some extra reserved space, so that they223 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.224 weights.reserved = Some(225 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT226 );227 })228 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)229 .build_or_panic();230 pub const Version: RuntimeVersion = VERSION;231 pub const SS58Prefix: u8 = 255;232}233234parameter_types! {235 pub const ChainId: u64 = 8881;236}237238pub struct FixedFee;239impl FeeCalculator for FixedFee {240 fn min_gas_price() -> U256 {241 MIN_GAS_PRICE.into()242 }243}244245// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case246// (contract, which only writes a lot of data),247// approximating on top of our real store write weight248parameter_types! {249 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;250 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;251 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();252}253254/// Limiting EVM execution to 50% of block for substrate users and management tasks255/// EVM transaction consumes more weight than substrate's, so we can't rely on them being256/// scheduled fairly257const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);258parameter_types! {259 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());260}261262pub enum FixedGasWeightMapping {}263impl GasWeightMapping for FixedGasWeightMapping {264 fn gas_to_weight(gas: u64) -> Weight {265 gas.saturating_mul(WeightPerGas::get())266 }267 fn weight_to_gas(weight: Weight) -> u64 {268 weight / WeightPerGas::get()269 }270}271272impl pallet_evm::Config for Runtime {273 type BlockGasLimit = BlockGasLimit;274 type FeeCalculator = FixedFee;275 type GasWeightMapping = FixedGasWeightMapping;276 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;277 type CallOrigin = EnsureAddressTruncated<Self>;278 type WithdrawOrigin = EnsureAddressTruncated<Self>;279 type AddressMapping = HashedAddressMapping<Self::Hashing>;280 type PrecompilesType = ();281 type PrecompilesValue = ();282 type Currency = Balances;283 type Event = Event;284 type OnMethodCall = (285 pallet_evm_migration::OnMethodCall<Self>,286 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,287 CollectionDispatchT<Self>,288 pallet_unique::eth::CollectionHelperOnMethodCall<Self>,289 );290 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;291 type ChainId = ChainId;292 type Runner = pallet_evm::runner::stack::Runner<Self>;293 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;294 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;295 type FindAuthor = EthereumFindAuthor<Aura>;296}297298impl pallet_evm_migration::Config for Runtime {299 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;300}301302pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);303impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {304 fn find_author<'a, I>(digests: I) -> Option<H160>305 where306 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,307 {308 if let Some(author_index) = F::find_author(digests) {309 let authority_id = Aura::authorities()[author_index as usize].clone();310 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));311 }312 None313 }314}315316impl pallet_ethereum::Config for Runtime {317 type Event = Event;318 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;319}320321impl pallet_randomness_collective_flip::Config for Runtime {}322323impl frame_system::Config for Runtime {324 /// The data to be stored in an account.325 type AccountData = pallet_balances::AccountData<Balance>;326 /// The identifier used to distinguish between accounts.327 type AccountId = AccountId;328 /// The basic call filter to use in dispatchable.329 type BaseCallFilter = Everything;330 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).331 type BlockHashCount = BlockHashCount;332 /// The maximum length of a block (in bytes).333 type BlockLength = RuntimeBlockLength;334 /// The index type for blocks.335 type BlockNumber = BlockNumber;336 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.337 type BlockWeights = RuntimeBlockWeights;338 /// The aggregated dispatch type that is available for extrinsics.339 type Call = Call;340 /// The weight of database operations that the runtime can invoke.341 type DbWeight = RocksDbWeight;342 /// The ubiquitous event type.343 type Event = Event;344 /// The type for hashing blocks and tries.345 type Hash = Hash;346 /// The hashing algorithm used.347 type Hashing = BlakeTwo256;348 /// The header type.349 type Header = generic::Header<BlockNumber, BlakeTwo256>;350 /// The index type for storing how many extrinsics an account has signed.351 type Index = Index;352 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.353 type Lookup = AccountIdLookup<AccountId, ()>;354 /// What to do if an account is fully reaped from the system.355 type OnKilledAccount = ();356 /// What to do if a new account is created.357 type OnNewAccount = ();358 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;359 /// The ubiquitous origin type.360 type Origin = Origin;361 /// This type is being generated by `construct_runtime!`.362 type PalletInfo = PalletInfo;363 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.364 type SS58Prefix = SS58Prefix;365 /// Weight information for the extrinsics of this pallet.366 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;367 /// Version of the runtime.368 type Version = Version;369 type MaxConsumers = ConstU32<16>;370}371372parameter_types! {373 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;374}375376impl pallet_timestamp::Config for Runtime {377 /// A timestamp: milliseconds since the unix epoch.378 type Moment = u64;379 type OnTimestampSet = ();380 type MinimumPeriod = MinimumPeriod;381 type WeightInfo = ();382}383384parameter_types! {385 // pub const ExistentialDeposit: u128 = 500;386 pub const ExistentialDeposit: u128 = 0;387 pub const MaxLocks: u32 = 50;388}389390impl pallet_balances::Config for Runtime {391 type MaxLocks = MaxLocks;392 type MaxReserves = ();393 type ReserveIdentifier = [u8; 8];394 /// The type for recording an account's balance.395 type Balance = Balance;396 /// The ubiquitous event type.397 type Event = Event;398 type DustRemoval = Treasury;399 type ExistentialDeposit = ExistentialDeposit;400 type AccountStore = System;401 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;402}403404pub const fn deposit(items: u32, bytes: u32) -> Balance {405 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE406}407408/*409parameter_types! {410 pub TombstoneDeposit: Balance = deposit(411 1,412 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,413 );414 pub DepositPerContract: Balance = TombstoneDeposit::get();415 pub const DepositPerStorageByte: Balance = deposit(0, 1);416 pub const DepositPerStorageItem: Balance = deposit(1, 0);417 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);418 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;419 pub const SignedClaimHandicap: u32 = 2;420 pub const MaxDepth: u32 = 32;421 pub const MaxValueSize: u32 = 16 * 1024;422 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb423 // The lazy deletion runs inside on_initialize.424 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *425 RuntimeBlockWeights::get().max_block;426 // The weight needed for decoding the queue should be less or equal than a fifth427 // of the overall weight dedicated to the lazy deletion.428 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (429 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -430 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)431 )) / 5) as u32;432 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();433}434435impl pallet_contracts::Config for Runtime {436 type Time = Timestamp;437 type Randomness = RandomnessCollectiveFlip;438 type Currency = Balances;439 type Event = Event;440 type RentPayment = ();441 type SignedClaimHandicap = SignedClaimHandicap;442 type TombstoneDeposit = TombstoneDeposit;443 type DepositPerContract = DepositPerContract;444 type DepositPerStorageByte = DepositPerStorageByte;445 type DepositPerStorageItem = DepositPerStorageItem;446 type RentFraction = RentFraction;447 type SurchargeReward = SurchargeReward;448 type WeightPrice = pallet_transaction_payment::Pallet<Self>;449 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;450 type ChainExtension = NFTExtension;451 type DeletionQueueDepth = DeletionQueueDepth;452 type DeletionWeightLimit = DeletionWeightLimit;453 type Schedule = Schedule;454 type CallStack = [pallet_contracts::Frame<Self>; 31];455}456*/457458parameter_types! {459 /// This value increases the priority of `Operational` transactions by adding460 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.461 pub const OperationalFeeMultiplier: u8 = 5;462}463464/// Linear implementor of `WeightToFeePolynomial`465pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);466467impl<T> WeightToFeePolynomial for LinearFee<T>468where469 T: BaseArithmetic + From<u32> + Copy + Unsigned,470{471 type Balance = T;472473 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {474 smallvec!(WeightToFeeCoefficient {475 // Targeting 0.1 Unique per NFT transfer476 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),477 coeff_frac: Perbill::zero(),478 negative: false,479 degree: 1,480 })481 }482}483484impl pallet_transaction_payment::Config for Runtime {485 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;486 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;487 type OperationalFeeMultiplier = OperationalFeeMultiplier;488 type WeightToFee = LinearFee<Balance>;489 type FeeMultiplierUpdate = ();490}491492parameter_types! {493 pub const ProposalBond: Permill = Permill::from_percent(5);494 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;495 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;496 pub const SpendPeriod: BlockNumber = 5 * MINUTES;497 pub const Burn: Permill = Permill::from_percent(0);498 pub const TipCountdown: BlockNumber = 1 * DAYS;499 pub const TipFindersFee: Percent = Percent::from_percent(20);500 pub const TipReportDepositBase: Balance = 1 * UNIQUE;501 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;502 pub const BountyDepositBase: Balance = 1 * UNIQUE;503 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;504 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");505 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;506 pub const MaximumReasonLength: u32 = 16384;507 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);508 pub const BountyValueMinimum: Balance = 5 * UNIQUE;509 pub const MaxApprovals: u32 = 100;510}511512impl pallet_treasury::Config for Runtime {513 type PalletId = TreasuryModuleId;514 type Currency = Balances;515 type ApproveOrigin = EnsureRoot<AccountId>;516 type RejectOrigin = EnsureRoot<AccountId>;517 type Event = Event;518 type OnSlash = ();519 type ProposalBond = ProposalBond;520 type ProposalBondMinimum = ProposalBondMinimum;521 type ProposalBondMaximum = ProposalBondMaximum;522 type SpendPeriod = SpendPeriod;523 type Burn = Burn;524 type BurnDestination = ();525 type SpendFunds = ();526 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;527 type MaxApprovals = MaxApprovals;528}529530impl pallet_sudo::Config for Runtime {531 type Event = Event;532 type Call = Call;533}534535pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);536537impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider538 for RelayChainBlockNumberProvider<T>539{540 type BlockNumber = BlockNumber;541542 fn current_block_number() -> Self::BlockNumber {543 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()544 .map(|d| d.relay_parent_number)545 .unwrap_or_default()546 }547}548549parameter_types! {550 pub const MinVestedTransfer: Balance = 10 * UNIQUE;551 pub const MaxVestingSchedules: u32 = 28;552}553554impl orml_vesting::Config for Runtime {555 type Event = Event;556 type Currency = pallet_balances::Pallet<Runtime>;557 type MinVestedTransfer = MinVestedTransfer;558 type VestedTransferOrigin = EnsureSigned<AccountId>;559 type WeightInfo = ();560 type MaxVestingSchedules = MaxVestingSchedules;561 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;562}563564parameter_types! {565 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;566 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;567}568569impl cumulus_pallet_parachain_system::Config for Runtime {570 type Event = Event;571 type SelfParaId = parachain_info::Pallet<Self>;572 type OnSystemEvent = ();573 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<574 // MaxDownwardMessageWeight,575 // XcmExecutor<XcmConfig>,576 // Call,577 // >;578 type OutboundXcmpMessageSource = XcmpQueue;579 type DmpMessageHandler = DmpQueue;580 type ReservedDmpWeight = ReservedDmpWeight;581 type ReservedXcmpWeight = ReservedXcmpWeight;582 type XcmpMessageHandler = XcmpQueue;583}584585impl parachain_info::Config for Runtime {}586587impl cumulus_pallet_aura_ext::Config for Runtime {}588589parameter_types! {590 pub const RelayLocation: MultiLocation = MultiLocation::parent();591 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;592 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();593 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();594}595596/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used597/// when determining ownership of accounts for asset transacting and when attempting to use XCM598/// `Transact` in order to determine the dispatch Origin.599pub type LocationToAccountId = (600 // The parent (Relay-chain) origin converts to the default `AccountId`.601 ParentIsPreset<AccountId>,602 // Sibling parachain origins convert to AccountId via the `ParaId::into`.603 SiblingParachainConvertsVia<Sibling, AccountId>,604 // Straight up local `AccountId32` origins just alias directly to `AccountId`.605 AccountId32Aliases<RelayNetwork, AccountId>,606);607608pub struct OnlySelfCurrency;609impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {610 fn matches_fungible(a: &MultiAsset) -> Option<B> {611 match (&a.id, &a.fun) {612 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),613 _ => None,614 }615 }616}617618/// Means for transacting assets on this chain.619pub type LocalAssetTransactor = CurrencyAdapter<620 // Use this currency:621 Balances,622 // Use this currency when it is a fungible asset matching the given location or name:623 OnlySelfCurrency,624 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:625 LocationToAccountId,626 // Our chain's account ID type (we can't get away without mentioning it explicitly):627 AccountId,628 // We don't track any teleports.629 (),630>;631632/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,633/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can634/// biases the kind of local `Origin` it will become.635pub type XcmOriginToTransactDispatchOrigin = (636 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location637 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for638 // foreign chains who want to have a local sovereign account on this chain which they control.639 SovereignSignedViaLocation<LocationToAccountId, Origin>,640 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when641 // recognised.642 RelayChainAsNative<RelayOrigin, Origin>,643 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when644 // recognised.645 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,646 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a647 // transaction from the Root origin.648 ParentAsSuperuser<Origin>,649 // Native signed account converter; this just converts an `AccountId32` origin into a normal650 // `Origin::Signed` origin of the same 32-byte value.651 SignedAccountId32AsNative<RelayNetwork, Origin>,652 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.653 XcmPassthrough<Origin>,654);655656parameter_types! {657 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.658 pub UnitWeightCost: Weight = 1_000_000;659 // 1200 UNIQUEs buy 1 second of weight.660 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);661 pub const MaxInstructions: u32 = 100;662 pub const MaxAuthorities: u32 = 100_000;663}664665match_types! {666 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {667 MultiLocation { parents: 1, interior: Here } |668 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }669 };670}671672pub type Barrier = (673 TakeWeightCredit,674 AllowTopLevelPaidExecutionFrom<Everything>,675 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,676 // ^^^ Parent & its unit plurality gets free execution677);678679pub struct UsingOnlySelfCurrencyComponents<680 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,681 AssetId: Get<MultiLocation>,682 AccountId,683 Currency: CurrencyT<AccountId>,684 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,685>(686 Weight,687 Currency::Balance,688 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,689);690impl<691 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,692 AssetId: Get<MultiLocation>,693 AccountId,694 Currency: CurrencyT<AccountId>,695 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,696 > WeightTrader697 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>698{699 fn new() -> Self {700 Self(0, Zero::zero(), PhantomData)701 }702703 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {704 let amount = WeightToFee::calc(&weight);705 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;706707 // location to this parachain through relay chain708 let option1: xcm::v1::AssetId = Concrete(MultiLocation {709 parents: 1,710 interior: X1(Parachain(ParachainInfo::parachain_id().into())),711 });712 // direct location713 let option2: xcm::v1::AssetId = Concrete(MultiLocation {714 parents: 0,715 interior: Here,716 });717718 let required = if payment.fungible.contains_key(&option1) {719 (option1, u128_amount).into()720 } else if payment.fungible.contains_key(&option2) {721 (option2, u128_amount).into()722 } else {723 (Concrete(MultiLocation::default()), u128_amount).into()724 };725726 let unused = payment727 .checked_sub(required)728 .map_err(|_| XcmError::TooExpensive)?;729 self.0 = self.0.saturating_add(weight);730 self.1 = self.1.saturating_add(amount);731 Ok(unused)732 }733734 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {735 let weight = weight.min(self.0);736 let amount = WeightToFee::calc(&weight);737 self.0 -= weight;738 self.1 = self.1.saturating_sub(amount);739 let amount: u128 = amount.saturated_into();740 if amount > 0 {741 Some((AssetId::get(), amount).into())742 } else {743 None744 }745 }746}747impl<748 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,749 AssetId: Get<MultiLocation>,750 AccountId,751 Currency: CurrencyT<AccountId>,752 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,753 > Drop754 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>755{756 fn drop(&mut self) {757 OnUnbalanced::on_unbalanced(Currency::issue(self.1));758 }759}760761pub struct XcmConfig;762impl Config for XcmConfig {763 type Call = Call;764 type XcmSender = XcmRouter;765 // How to withdraw and deposit an asset.766 type AssetTransactor = LocalAssetTransactor;767 type OriginConverter = XcmOriginToTransactDispatchOrigin;768 type IsReserve = NativeAsset;769 type IsTeleporter = (); // Teleportation is disabled770 type LocationInverter = LocationInverter<Ancestry>;771 type Barrier = Barrier;772 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;773 type Trader = UsingOnlySelfCurrencyComponents<774 IdentityFee<Balance>,775 RelayLocation,776 AccountId,777 Balances,778 (),779 >;780 type ResponseHandler = (); // Don't handle responses for now.781 type SubscriptionService = PolkadotXcm;782783 type AssetTrap = PolkadotXcm;784 type AssetClaims = PolkadotXcm;785}786787// parameter_types! {788// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;789// }790791/// No local origins on this chain are allowed to dispatch XCM sends/executions.792pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);793794/// The means for routing XCM messages which are not for local execution into the right message795/// queues.796pub type XcmRouter = (797 // Two routers - use UMP to communicate with the relay chain:798 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,799 // ..and XCMP to communicate with the sibling chains.800 XcmpQueue,801);802803impl pallet_evm_coder_substrate::Config for Runtime {804 type GasWeightMapping = FixedGasWeightMapping;805}806807impl pallet_xcm::Config for Runtime {808 type Event = Event;809 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;810 type XcmRouter = XcmRouter;811 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;812 type XcmExecuteFilter = Everything;813 type XcmExecutor = XcmExecutor<XcmConfig>;814 type XcmTeleportFilter = Everything;815 type XcmReserveTransferFilter = Everything;816 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;817 type LocationInverter = LocationInverter<Ancestry>;818 type Origin = Origin;819 type Call = Call;820 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;821 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;822}823824impl cumulus_pallet_xcm::Config for Runtime {825 type Event = Event;826 type XcmExecutor = XcmExecutor<XcmConfig>;827}828829impl cumulus_pallet_xcmp_queue::Config for Runtime {830 type WeightInfo = ();831 type Event = Event;832 type XcmExecutor = XcmExecutor<XcmConfig>;833 type ChannelInfo = ParachainSystem;834 type VersionWrapper = ();835 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;836 type ControllerOrigin = EnsureRoot<AccountId>;837 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;838}839840impl cumulus_pallet_dmp_queue::Config for Runtime {841 type Event = Event;842 type XcmExecutor = XcmExecutor<XcmConfig>;843 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;844}845846impl pallet_aura::Config for Runtime {847 type AuthorityId = AuraId;848 type DisabledValidators = ();849 type MaxAuthorities = MaxAuthorities;850}851852parameter_types! {853 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();854 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;855}856857impl pallet_common::Config for Runtime {858 type Event = Event;859860 type Currency = Balances;861 type CollectionCreationPrice = CollectionCreationPrice;862 type TreasuryAccountId = TreasuryAccountId;863 type CollectionDispatch = CollectionDispatchT<Self>;864865 type EvmTokenAddressMapping = EvmTokenAddressMapping;866 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;867}868869impl pallet_structure::Config for Runtime {870 type Event = Event;871 type Call = Call;872 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;873}874875impl pallet_evm::account::Config for Runtime {876 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;877 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;878 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;879}880881impl pallet_fungible::Config for Runtime {882 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;883}884impl pallet_refungible::Config for Runtime {885 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;886}887impl pallet_nonfungible::Config for Runtime {888 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;889}890/* TODO free RMRK!891impl pallet_proxy_rmrk_core::Config for Runtime {892 type Event = Event;893}894895impl pallet_proxy_rmrk_equip::Config for Runtime {896 type Event = Event;897}*/898899impl pallet_unique::Config for Runtime {900 type Event = Event;901 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;902 type CommonWeightInfo = CommonWeights<Self>;903}904905parameter_types! {906 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied907}908909/// Used for the pallet inflation910impl pallet_inflation::Config for Runtime {911 type Currency = Balances;912 type TreasuryAccountId = TreasuryAccountId;913 type InflationBlockInterval = InflationBlockInterval;914 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;915}916917// parameter_types! {918// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *919// RuntimeBlockWeights::get().max_block;920// pub const MaxScheduledPerBlock: u32 = 50;921// }922923type EvmSponsorshipHandler = (924 UniqueEthSponsorshipHandler<Runtime>,925 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,926);927type SponsorshipHandler = (928 UniqueSponsorshipHandler<Runtime>,929 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,930 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,931);932933// impl pallet_unq_scheduler::Config for Runtime {934// type Event = Event;935// type Origin = Origin;936// type PalletsOrigin = OriginCaller;937// type Call = Call;938// type MaximumWeight = MaximumSchedulerWeight;939// type ScheduleOrigin = EnsureSigned<AccountId>;940// type MaxScheduledPerBlock = MaxScheduledPerBlock;941// type SponsorshipHandler = SponsorshipHandler;942// type WeightInfo = ();943// }944945impl pallet_evm_transaction_payment::Config for Runtime {946 type EvmSponsorshipHandler = EvmSponsorshipHandler;947 type Currency = Balances;948}949950impl pallet_charge_transaction::Config for Runtime {951 type SponsorshipHandler = SponsorshipHandler;952}953954// impl pallet_contract_helpers::Config for Runtime {955// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;956// }957958parameter_types! {959 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049960 pub const HelpersContractAddress: H160 = H160([961 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,962 ]);963 964 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f965 pub const EvmCollectionHelperAddress: H160 = H160([966 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,967 ]);968}969970impl pallet_evm_contract_helpers::Config for Runtime {971 type ContractAddress = HelpersContractAddress;972 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;973}974975impl pallet_unique::eth::Config for Runtime {976 type ContractAddress = EvmCollectionHelperAddress;977}978979construct_runtime!(980 pub enum Runtime where981 Block = Block,982 NodeBlock = opaque::Block,983 UncheckedExtrinsic = UncheckedExtrinsic984 {985 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,986 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,987988 Aura: pallet_aura::{Pallet, Config<T>} = 22,989 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,990991 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,992 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,993 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,994 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,995 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,996 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,997 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,998 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,999 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1000 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10011002 // XCM helpers.1003 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1004 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1005 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1006 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10071008 // Unique Pallets1009 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1010 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1011 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1012 // free = 631013 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1014 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1015 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1016 Fungible: pallet_fungible::{Pallet, Storage} = 67,1017 Refungible: pallet_refungible::{Pallet, Storage} = 68,1018 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1019 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1020 /* TODO free RMRK!1021 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1022 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,*/10231024 // Frontier1025 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1026 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10271028 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1029 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1030 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1031 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1032 }1033);10341035pub struct TransactionConverter;10361037impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1038 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1039 UncheckedExtrinsic::new_unsigned(1040 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1041 )1042 }1043}10441045impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1046 fn convert_transaction(1047 &self,1048 transaction: pallet_ethereum::Transaction,1049 ) -> opaque::UncheckedExtrinsic {1050 let extrinsic = UncheckedExtrinsic::new_unsigned(1051 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1052 );1053 let encoded = extrinsic.encode();1054 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1055 .expect("Encoded extrinsic is always valid")1056 }1057}10581059/// The address format for describing accounts.1060pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1061/// Block header type as expected by this runtime.1062pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1063/// Block type as expected by this runtime.1064pub type Block = generic::Block<Header, UncheckedExtrinsic>;1065/// A Block signed with a Justification1066pub type SignedBlock = generic::SignedBlock<Block>;1067/// BlockId type as expected by this runtime.1068pub type BlockId = generic::BlockId<Block>;1069/// The SignedExtension to the basic transaction logic.1070pub type SignedExtra = (1071 frame_system::CheckSpecVersion<Runtime>,1072 // system::CheckTxVersion<Runtime>,1073 frame_system::CheckGenesis<Runtime>,1074 frame_system::CheckEra<Runtime>,1075 frame_system::CheckNonce<Runtime>,1076 frame_system::CheckWeight<Runtime>,1077 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1078 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1079 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1080);1081/// Unchecked extrinsic type as expected by this runtime.1082pub type UncheckedExtrinsic =1083 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1084/// Extrinsic type that has already been checked.1085pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1086/// Executive: handles dispatch to the various modules.1087pub type Executive = frame_executive::Executive<1088 Runtime,1089 Block,1090 frame_system::ChainContext<Runtime>,1091 Runtime,1092 AllPalletsReversedWithSystemFirst,1093>;10941095impl_opaque_keys! {1096 pub struct SessionKeys {1097 pub aura: Aura,1098 }1099}11001101impl fp_self_contained::SelfContainedCall for Call {1102 type SignedInfo = H160;11031104 fn is_self_contained(&self) -> bool {1105 match self {1106 Call::Ethereum(call) => call.is_self_contained(),1107 _ => false,1108 }1109 }11101111 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1112 match self {1113 Call::Ethereum(call) => call.check_self_contained(),1114 _ => None,1115 }1116 }11171118 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1119 match self {1120 Call::Ethereum(call) => call.validate_self_contained(info),1121 _ => None,1122 }1123 }11241125 fn pre_dispatch_self_contained(1126 &self,1127 info: &Self::SignedInfo,1128 ) -> Option<Result<(), TransactionValidityError>> {1129 match self {1130 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1131 _ => None,1132 }1133 }11341135 fn apply_self_contained(1136 self,1137 info: Self::SignedInfo,1138 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1139 match self {1140 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1141 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1142 )),1143 _ => None,1144 }1145 }1146}11471148macro_rules! dispatch_unique_runtime {1149 ($collection:ident.$method:ident($($name:ident),*)) => {{1150 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1151 let dispatch = collection.as_dyn();11521153 Ok::<_, DispatchError>(dispatch.$method($($name),*))1154 }};1155}11561157impl_common_runtime_apis!();11581159struct CheckInherents;11601161impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1162 fn check_inherents(1163 block: &Block,1164 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1165 ) -> sp_inherents::CheckInherentsResult {1166 let relay_chain_slot = relay_state_proof1167 .read_slot()1168 .expect("Could not read the relay chain slot from the proof");11691170 let inherent_data =1171 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1172 relay_chain_slot,1173 sp_std::time::Duration::from_secs(6),1174 )1175 .create_inherent_data()1176 .expect("Could not create the timestamp inherent data");11771178 inherent_data.check_extrinsics(block)1179 }1180}11811182cumulus_pallet_parachain_system::register_validate_block!(1183 Runtime = Runtime,1184 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1185 CheckInherents = CheckInherents,1186);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_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};82use fp_rpc::TransactionStatus;83use sp_runtime::{84 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85 transaction_validity::TransactionValidityError,86 SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;90pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use up_data_structs::mapping::{CrossTokenAddressMapping, EvmTokenAddressMapping};96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 impl_common_runtime_apis,120 types::*,121 constants::*,122 dispatch::{CollectionDispatchT, CollectionDispatch},123 sponsoring::UniqueSponsorshipHandler,124 eth_sponsoring::UniqueEthSponsorshipHandler,125 weights::CommonWeights,126};127128pub const RUNTIME_NAME: &str = "quartz";129pub const TOKEN_SYMBOL: &str = "QTZ";130131type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;132133impl RuntimeInstance for Runtime {134 type CrossAccountId = self::CrossAccountId;135136 type TransactionConverter = self::TransactionConverter;137138 fn get_transaction_converter() -> TransactionConverter {139 TransactionConverter140 }141}142143/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know144/// the specifics of the runtime. They can then be made to be agnostic over specific formats145/// of data like extrinsics, allowing for them to continue syncing the network through upgrades146/// to even the core data structures.147pub mod opaque {148 use sp_std::prelude::*;149 use sp_runtime::impl_opaque_keys;150 use super::Aura;151152 pub use unique_runtime_common::types::*;153154 impl_opaque_keys! {155 pub struct SessionKeys {156 pub aura: Aura,157 }158 }159}160161/// This runtime version.162pub const VERSION: RuntimeVersion = RuntimeVersion {163 spec_name: create_runtime_str!(RUNTIME_NAME),164 impl_name: create_runtime_str!(RUNTIME_NAME),165 authoring_version: 1,166 spec_version: 921000,167 impl_version: 0,168 apis: RUNTIME_API_VERSIONS,169 transaction_version: 1,170 state_version: 0,171};172173#[derive(codec::Encode, codec::Decode)]174pub enum XCMPMessage<XAccountId, XBalance> {175 /// Transfer tokens to the given account from the Parachain account.176 TransferToken(XAccountId, XBalance),177}178179/// The version information used to identify this runtime when compiled natively.180#[cfg(feature = "std")]181pub fn native_version() -> NativeVersion {182 NativeVersion {183 runtime_version: VERSION,184 can_author_with: Default::default(),185 }186}187188type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;189190pub struct DealWithFees;191impl OnUnbalanced<NegativeImbalance> for DealWithFees {192 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {193 if let Some(fees) = fees_then_tips.next() {194 // for fees, 100% to treasury195 let mut split = fees.ration(100, 0);196 if let Some(tips) = fees_then_tips.next() {197 // for tips, if any, 100% to treasury198 tips.ration_merge_into(100, 0, &mut split);199 }200 Treasury::on_unbalanced(split.0);201 // Author::on_unbalanced(split.1);202 }203 }204}205206parameter_types! {207 pub const BlockHashCount: BlockNumber = 2400;208 pub RuntimeBlockLength: BlockLength =209 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);210 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);211 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;212 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()213 .base_block(BlockExecutionWeight::get())214 .for_class(DispatchClass::all(), |weights| {215 weights.base_extrinsic = ExtrinsicBaseWeight::get();216 })217 .for_class(DispatchClass::Normal, |weights| {218 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);219 })220 .for_class(DispatchClass::Operational, |weights| {221 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);222 // Operational transactions have some extra reserved space, so that they223 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.224 weights.reserved = Some(225 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT226 );227 })228 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)229 .build_or_panic();230 pub const Version: RuntimeVersion = VERSION;231 pub const SS58Prefix: u8 = 255;232}233234parameter_types! {235 pub const ChainId: u64 = 8881;236}237238pub struct FixedFee;239impl FeeCalculator for FixedFee {240 fn min_gas_price() -> U256 {241 MIN_GAS_PRICE.into()242 }243}244245// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case246// (contract, which only writes a lot of data),247// approximating on top of our real store write weight248parameter_types! {249 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;250 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;251 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();252}253254/// Limiting EVM execution to 50% of block for substrate users and management tasks255/// EVM transaction consumes more weight than substrate's, so we can't rely on them being256/// scheduled fairly257const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);258parameter_types! {259 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());260}261262pub enum FixedGasWeightMapping {}263impl GasWeightMapping for FixedGasWeightMapping {264 fn gas_to_weight(gas: u64) -> Weight {265 gas.saturating_mul(WeightPerGas::get())266 }267 fn weight_to_gas(weight: Weight) -> u64 {268 weight / WeightPerGas::get()269 }270}271272impl pallet_evm::Config for Runtime {273 type BlockGasLimit = BlockGasLimit;274 type FeeCalculator = FixedFee;275 type GasWeightMapping = FixedGasWeightMapping;276 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;277 type CallOrigin = EnsureAddressTruncated<Self>;278 type WithdrawOrigin = EnsureAddressTruncated<Self>;279 type AddressMapping = HashedAddressMapping<Self::Hashing>;280 type PrecompilesType = ();281 type PrecompilesValue = ();282 type Currency = Balances;283 type Event = Event;284 type OnMethodCall = (285 pallet_evm_migration::OnMethodCall<Self>,286 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,287 CollectionDispatchT<Self>,288 pallet_unique::eth::CollectionHelperOnMethodCall<Self>,289 );290 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;291 type ChainId = ChainId;292 type Runner = pallet_evm::runner::stack::Runner<Self>;293 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;294 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;295 type FindAuthor = EthereumFindAuthor<Aura>;296}297298impl pallet_evm_migration::Config for Runtime {299 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;300}301302pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);303impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {304 fn find_author<'a, I>(digests: I) -> Option<H160>305 where306 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,307 {308 if let Some(author_index) = F::find_author(digests) {309 let authority_id = Aura::authorities()[author_index as usize].clone();310 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));311 }312 None313 }314}315316impl pallet_ethereum::Config for Runtime {317 type Event = Event;318 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;319}320321impl pallet_randomness_collective_flip::Config for Runtime {}322323impl frame_system::Config for Runtime {324 /// The data to be stored in an account.325 type AccountData = pallet_balances::AccountData<Balance>;326 /// The identifier used to distinguish between accounts.327 type AccountId = AccountId;328 /// The basic call filter to use in dispatchable.329 type BaseCallFilter = Everything;330 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).331 type BlockHashCount = BlockHashCount;332 /// The maximum length of a block (in bytes).333 type BlockLength = RuntimeBlockLength;334 /// The index type for blocks.335 type BlockNumber = BlockNumber;336 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.337 type BlockWeights = RuntimeBlockWeights;338 /// The aggregated dispatch type that is available for extrinsics.339 type Call = Call;340 /// The weight of database operations that the runtime can invoke.341 type DbWeight = RocksDbWeight;342 /// The ubiquitous event type.343 type Event = Event;344 /// The type for hashing blocks and tries.345 type Hash = Hash;346 /// The hashing algorithm used.347 type Hashing = BlakeTwo256;348 /// The header type.349 type Header = generic::Header<BlockNumber, BlakeTwo256>;350 /// The index type for storing how many extrinsics an account has signed.351 type Index = Index;352 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.353 type Lookup = AccountIdLookup<AccountId, ()>;354 /// What to do if an account is fully reaped from the system.355 type OnKilledAccount = ();356 /// What to do if a new account is created.357 type OnNewAccount = ();358 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;359 /// The ubiquitous origin type.360 type Origin = Origin;361 /// This type is being generated by `construct_runtime!`.362 type PalletInfo = PalletInfo;363 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.364 type SS58Prefix = SS58Prefix;365 /// Weight information for the extrinsics of this pallet.366 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;367 /// Version of the runtime.368 type Version = Version;369 type MaxConsumers = ConstU32<16>;370}371372parameter_types! {373 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;374}375376impl pallet_timestamp::Config for Runtime {377 /// A timestamp: milliseconds since the unix epoch.378 type Moment = u64;379 type OnTimestampSet = ();380 type MinimumPeriod = MinimumPeriod;381 type WeightInfo = ();382}383384parameter_types! {385 // pub const ExistentialDeposit: u128 = 500;386 pub const ExistentialDeposit: u128 = 0;387 pub const MaxLocks: u32 = 50;388}389390impl pallet_balances::Config for Runtime {391 type MaxLocks = MaxLocks;392 type MaxReserves = ();393 type ReserveIdentifier = [u8; 8];394 /// The type for recording an account's balance.395 type Balance = Balance;396 /// The ubiquitous event type.397 type Event = Event;398 type DustRemoval = Treasury;399 type ExistentialDeposit = ExistentialDeposit;400 type AccountStore = System;401 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;402}403404pub const fn deposit(items: u32, bytes: u32) -> Balance {405 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE406}407408/*409parameter_types! {410 pub TombstoneDeposit: Balance = deposit(411 1,412 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,413 );414 pub DepositPerContract: Balance = TombstoneDeposit::get();415 pub const DepositPerStorageByte: Balance = deposit(0, 1);416 pub const DepositPerStorageItem: Balance = deposit(1, 0);417 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);418 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;419 pub const SignedClaimHandicap: u32 = 2;420 pub const MaxDepth: u32 = 32;421 pub const MaxValueSize: u32 = 16 * 1024;422 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb423 // The lazy deletion runs inside on_initialize.424 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *425 RuntimeBlockWeights::get().max_block;426 // The weight needed for decoding the queue should be less or equal than a fifth427 // of the overall weight dedicated to the lazy deletion.428 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (429 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -430 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)431 )) / 5) as u32;432 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();433}434435impl pallet_contracts::Config for Runtime {436 type Time = Timestamp;437 type Randomness = RandomnessCollectiveFlip;438 type Currency = Balances;439 type Event = Event;440 type RentPayment = ();441 type SignedClaimHandicap = SignedClaimHandicap;442 type TombstoneDeposit = TombstoneDeposit;443 type DepositPerContract = DepositPerContract;444 type DepositPerStorageByte = DepositPerStorageByte;445 type DepositPerStorageItem = DepositPerStorageItem;446 type RentFraction = RentFraction;447 type SurchargeReward = SurchargeReward;448 type WeightPrice = pallet_transaction_payment::Pallet<Self>;449 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;450 type ChainExtension = NFTExtension;451 type DeletionQueueDepth = DeletionQueueDepth;452 type DeletionWeightLimit = DeletionWeightLimit;453 type Schedule = Schedule;454 type CallStack = [pallet_contracts::Frame<Self>; 31];455}456*/457458parameter_types! {459 /// This value increases the priority of `Operational` transactions by adding460 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.461 pub const OperationalFeeMultiplier: u8 = 5;462}463464/// Linear implementor of `WeightToFeePolynomial`465pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);466467impl<T> WeightToFeePolynomial for LinearFee<T>468where469 T: BaseArithmetic + From<u32> + Copy + Unsigned,470{471 type Balance = T;472473 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {474 smallvec!(WeightToFeeCoefficient {475 // Targeting 0.1 Unique per NFT transfer476 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),477 coeff_frac: Perbill::zero(),478 negative: false,479 degree: 1,480 })481 }482}483484impl pallet_transaction_payment::Config for Runtime {485 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;486 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;487 type OperationalFeeMultiplier = OperationalFeeMultiplier;488 type WeightToFee = LinearFee<Balance>;489 type FeeMultiplierUpdate = ();490}491492parameter_types! {493 pub const ProposalBond: Permill = Permill::from_percent(5);494 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;495 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;496 pub const SpendPeriod: BlockNumber = 5 * MINUTES;497 pub const Burn: Permill = Permill::from_percent(0);498 pub const TipCountdown: BlockNumber = 1 * DAYS;499 pub const TipFindersFee: Percent = Percent::from_percent(20);500 pub const TipReportDepositBase: Balance = 1 * UNIQUE;501 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;502 pub const BountyDepositBase: Balance = 1 * UNIQUE;503 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;504 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");505 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;506 pub const MaximumReasonLength: u32 = 16384;507 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);508 pub const BountyValueMinimum: Balance = 5 * UNIQUE;509 pub const MaxApprovals: u32 = 100;510}511512impl pallet_treasury::Config for Runtime {513 type PalletId = TreasuryModuleId;514 type Currency = Balances;515 type ApproveOrigin = EnsureRoot<AccountId>;516 type RejectOrigin = EnsureRoot<AccountId>;517 type Event = Event;518 type OnSlash = ();519 type ProposalBond = ProposalBond;520 type ProposalBondMinimum = ProposalBondMinimum;521 type ProposalBondMaximum = ProposalBondMaximum;522 type SpendPeriod = SpendPeriod;523 type Burn = Burn;524 type BurnDestination = ();525 type SpendFunds = ();526 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;527 type MaxApprovals = MaxApprovals;528}529530impl pallet_sudo::Config for Runtime {531 type Event = Event;532 type Call = Call;533}534535pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);536537impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider538 for RelayChainBlockNumberProvider<T>539{540 type BlockNumber = BlockNumber;541542 fn current_block_number() -> Self::BlockNumber {543 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()544 .map(|d| d.relay_parent_number)545 .unwrap_or_default()546 }547}548549parameter_types! {550 pub const MinVestedTransfer: Balance = 10 * UNIQUE;551 pub const MaxVestingSchedules: u32 = 28;552}553554impl orml_vesting::Config for Runtime {555 type Event = Event;556 type Currency = pallet_balances::Pallet<Runtime>;557 type MinVestedTransfer = MinVestedTransfer;558 type VestedTransferOrigin = EnsureSigned<AccountId>;559 type WeightInfo = ();560 type MaxVestingSchedules = MaxVestingSchedules;561 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;562}563564parameter_types! {565 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;566 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;567}568569impl cumulus_pallet_parachain_system::Config for Runtime {570 type Event = Event;571 type SelfParaId = parachain_info::Pallet<Self>;572 type OnSystemEvent = ();573 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<574 // MaxDownwardMessageWeight,575 // XcmExecutor<XcmConfig>,576 // Call,577 // >;578 type OutboundXcmpMessageSource = XcmpQueue;579 type DmpMessageHandler = DmpQueue;580 type ReservedDmpWeight = ReservedDmpWeight;581 type ReservedXcmpWeight = ReservedXcmpWeight;582 type XcmpMessageHandler = XcmpQueue;583}584585impl parachain_info::Config for Runtime {}586587impl cumulus_pallet_aura_ext::Config for Runtime {}588589parameter_types! {590 pub const RelayLocation: MultiLocation = MultiLocation::parent();591 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;592 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();593 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();594}595596/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used597/// when determining ownership of accounts for asset transacting and when attempting to use XCM598/// `Transact` in order to determine the dispatch Origin.599pub type LocationToAccountId = (600 // The parent (Relay-chain) origin converts to the default `AccountId`.601 ParentIsPreset<AccountId>,602 // Sibling parachain origins convert to AccountId via the `ParaId::into`.603 SiblingParachainConvertsVia<Sibling, AccountId>,604 // Straight up local `AccountId32` origins just alias directly to `AccountId`.605 AccountId32Aliases<RelayNetwork, AccountId>,606);607608pub struct OnlySelfCurrency;609impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {610 fn matches_fungible(a: &MultiAsset) -> Option<B> {611 match (&a.id, &a.fun) {612 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),613 _ => None,614 }615 }616}617618/// Means for transacting assets on this chain.619pub type LocalAssetTransactor = CurrencyAdapter<620 // Use this currency:621 Balances,622 // Use this currency when it is a fungible asset matching the given location or name:623 OnlySelfCurrency,624 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:625 LocationToAccountId,626 // Our chain's account ID type (we can't get away without mentioning it explicitly):627 AccountId,628 // We don't track any teleports.629 (),630>;631632/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,633/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can634/// biases the kind of local `Origin` it will become.635pub type XcmOriginToTransactDispatchOrigin = (636 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location637 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for638 // foreign chains who want to have a local sovereign account on this chain which they control.639 SovereignSignedViaLocation<LocationToAccountId, Origin>,640 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when641 // recognised.642 RelayChainAsNative<RelayOrigin, Origin>,643 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when644 // recognised.645 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,646 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a647 // transaction from the Root origin.648 ParentAsSuperuser<Origin>,649 // Native signed account converter; this just converts an `AccountId32` origin into a normal650 // `Origin::Signed` origin of the same 32-byte value.651 SignedAccountId32AsNative<RelayNetwork, Origin>,652 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.653 XcmPassthrough<Origin>,654);655656parameter_types! {657 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.658 pub UnitWeightCost: Weight = 1_000_000;659 // 1200 UNIQUEs buy 1 second of weight.660 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);661 pub const MaxInstructions: u32 = 100;662 pub const MaxAuthorities: u32 = 100_000;663}664665match_types! {666 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {667 MultiLocation { parents: 1, interior: Here } |668 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }669 };670}671672pub type Barrier = (673 TakeWeightCredit,674 AllowTopLevelPaidExecutionFrom<Everything>,675 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,676 // ^^^ Parent & its unit plurality gets free execution677);678679pub struct UsingOnlySelfCurrencyComponents<680 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,681 AssetId: Get<MultiLocation>,682 AccountId,683 Currency: CurrencyT<AccountId>,684 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,685>(686 Weight,687 Currency::Balance,688 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,689);690impl<691 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,692 AssetId: Get<MultiLocation>,693 AccountId,694 Currency: CurrencyT<AccountId>,695 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,696 > WeightTrader697 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>698{699 fn new() -> Self {700 Self(0, Zero::zero(), PhantomData)701 }702703 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {704 let amount = WeightToFee::calc(&weight);705 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;706707 // location to this parachain through relay chain708 let option1: xcm::v1::AssetId = Concrete(MultiLocation {709 parents: 1,710 interior: X1(Parachain(ParachainInfo::parachain_id().into())),711 });712 // direct location713 let option2: xcm::v1::AssetId = Concrete(MultiLocation {714 parents: 0,715 interior: Here,716 });717718 let required = if payment.fungible.contains_key(&option1) {719 (option1, u128_amount).into()720 } else if payment.fungible.contains_key(&option2) {721 (option2, u128_amount).into()722 } else {723 (Concrete(MultiLocation::default()), u128_amount).into()724 };725726 let unused = payment727 .checked_sub(required)728 .map_err(|_| XcmError::TooExpensive)?;729 self.0 = self.0.saturating_add(weight);730 self.1 = self.1.saturating_add(amount);731 Ok(unused)732 }733734 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {735 let weight = weight.min(self.0);736 let amount = WeightToFee::calc(&weight);737 self.0 -= weight;738 self.1 = self.1.saturating_sub(amount);739 let amount: u128 = amount.saturated_into();740 if amount > 0 {741 Some((AssetId::get(), amount).into())742 } else {743 None744 }745 }746}747impl<748 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,749 AssetId: Get<MultiLocation>,750 AccountId,751 Currency: CurrencyT<AccountId>,752 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,753 > Drop754 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>755{756 fn drop(&mut self) {757 OnUnbalanced::on_unbalanced(Currency::issue(self.1));758 }759}760761pub struct XcmConfig;762impl Config for XcmConfig {763 type Call = Call;764 type XcmSender = XcmRouter;765 // How to withdraw and deposit an asset.766 type AssetTransactor = LocalAssetTransactor;767 type OriginConverter = XcmOriginToTransactDispatchOrigin;768 type IsReserve = NativeAsset;769 type IsTeleporter = (); // Teleportation is disabled770 type LocationInverter = LocationInverter<Ancestry>;771 type Barrier = Barrier;772 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;773 type Trader = UsingOnlySelfCurrencyComponents<774 IdentityFee<Balance>,775 RelayLocation,776 AccountId,777 Balances,778 (),779 >;780 type ResponseHandler = (); // Don't handle responses for now.781 type SubscriptionService = PolkadotXcm;782783 type AssetTrap = PolkadotXcm;784 type AssetClaims = PolkadotXcm;785}786787// parameter_types! {788// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;789// }790791/// No local origins on this chain are allowed to dispatch XCM sends/executions.792pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);793794/// The means for routing XCM messages which are not for local execution into the right message795/// queues.796pub type XcmRouter = (797 // Two routers - use UMP to communicate with the relay chain:798 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,799 // ..and XCMP to communicate with the sibling chains.800 XcmpQueue,801);802803impl pallet_evm_coder_substrate::Config for Runtime {804 type GasWeightMapping = FixedGasWeightMapping;805}806807impl pallet_xcm::Config for Runtime {808 type Event = Event;809 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;810 type XcmRouter = XcmRouter;811 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;812 type XcmExecuteFilter = Everything;813 type XcmExecutor = XcmExecutor<XcmConfig>;814 type XcmTeleportFilter = Everything;815 type XcmReserveTransferFilter = Everything;816 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;817 type LocationInverter = LocationInverter<Ancestry>;818 type Origin = Origin;819 type Call = Call;820 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;821 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;822}823824impl cumulus_pallet_xcm::Config for Runtime {825 type Event = Event;826 type XcmExecutor = XcmExecutor<XcmConfig>;827}828829impl cumulus_pallet_xcmp_queue::Config for Runtime {830 type WeightInfo = ();831 type Event = Event;832 type XcmExecutor = XcmExecutor<XcmConfig>;833 type ChannelInfo = ParachainSystem;834 type VersionWrapper = ();835 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;836 type ControllerOrigin = EnsureRoot<AccountId>;837 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;838}839840impl cumulus_pallet_dmp_queue::Config for Runtime {841 type Event = Event;842 type XcmExecutor = XcmExecutor<XcmConfig>;843 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;844}845846impl pallet_aura::Config for Runtime {847 type AuthorityId = AuraId;848 type DisabledValidators = ();849 type MaxAuthorities = MaxAuthorities;850}851852parameter_types! {853 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();854 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;855}856857impl pallet_common::Config for Runtime {858 type Event = Event;859860 type Currency = Balances;861 type CollectionCreationPrice = CollectionCreationPrice;862 type TreasuryAccountId = TreasuryAccountId;863 type CollectionDispatch = CollectionDispatchT<Self>;864865 type EvmTokenAddressMapping = EvmTokenAddressMapping;866 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;867}868869impl pallet_structure::Config for Runtime {870 type Event = Event;871 type Call = Call;872 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;873}874875impl pallet_evm::account::Config for Runtime {876 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;877 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;878 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;879}880881impl pallet_fungible::Config for Runtime {882 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;883}884impl pallet_refungible::Config for Runtime {885 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;886}887impl pallet_nonfungible::Config for Runtime {888 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;889}890/* TODO free RMRK!891impl pallet_proxy_rmrk_core::Config for Runtime {892 type Event = Event;893}894895impl pallet_proxy_rmrk_equip::Config for Runtime {896 type Event = Event;897}*/898899impl pallet_unique::Config for Runtime {900 type Event = Event;901 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;902 type CommonWeightInfo = CommonWeights<Self>;903 type ContractAddress = EvmCollectionHelperAddress;904}905906parameter_types! {907 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied908}909910/// Used for the pallet inflation911impl pallet_inflation::Config for Runtime {912 type Currency = Balances;913 type TreasuryAccountId = TreasuryAccountId;914 type InflationBlockInterval = InflationBlockInterval;915 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;916}917918// parameter_types! {919// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *920// RuntimeBlockWeights::get().max_block;921// pub const MaxScheduledPerBlock: u32 = 50;922// }923924type EvmSponsorshipHandler = (925 UniqueEthSponsorshipHandler<Runtime>,926 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,927);928type SponsorshipHandler = (929 UniqueSponsorshipHandler<Runtime>,930 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,931 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,932);933934// impl pallet_unq_scheduler::Config for Runtime {935// type Event = Event;936// type Origin = Origin;937// type PalletsOrigin = OriginCaller;938// type Call = Call;939// type MaximumWeight = MaximumSchedulerWeight;940// type ScheduleOrigin = EnsureSigned<AccountId>;941// type MaxScheduledPerBlock = MaxScheduledPerBlock;942// type SponsorshipHandler = SponsorshipHandler;943// type WeightInfo = ();944// }945946impl pallet_evm_transaction_payment::Config for Runtime {947 type EvmSponsorshipHandler = EvmSponsorshipHandler;948 type Currency = Balances;949}950951impl pallet_charge_transaction::Config for Runtime {952 type SponsorshipHandler = SponsorshipHandler;953}954955// impl pallet_contract_helpers::Config for Runtime {956// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;957// }958959parameter_types! {960 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049961 pub const HelpersContractAddress: H160 = H160([962 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,963 ]);964 965 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f966 pub const EvmCollectionHelperAddress: H160 = H160([967 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,968 ]);969}970971impl pallet_evm_contract_helpers::Config for Runtime {972 type ContractAddress = HelpersContractAddress;973 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;974}975976construct_runtime!(977 pub enum Runtime where978 Block = Block,979 NodeBlock = opaque::Block,980 UncheckedExtrinsic = UncheckedExtrinsic981 {982 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,983 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,984985 Aura: pallet_aura::{Pallet, Config<T>} = 22,986 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,987988 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,989 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,990 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,991 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,992 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,993 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,994 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,995 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,996 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,997 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,998999 // XCM helpers.1000 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1001 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1002 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1003 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10041005 // Unique Pallets1006 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1007 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1008 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1009 // free = 631010 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1011 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1012 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1013 Fungible: pallet_fungible::{Pallet, Storage} = 67,1014 Refungible: pallet_refungible::{Pallet, Storage} = 68,1015 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1016 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1017 /* TODO free RMRK!1018 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1019 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,*/10201021 // Frontier1022 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1023 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10241025 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1026 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1027 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1028 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1029 }1030);10311032pub struct TransactionConverter;10331034impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1035 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1036 UncheckedExtrinsic::new_unsigned(1037 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1038 )1039 }1040}10411042impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1043 fn convert_transaction(1044 &self,1045 transaction: pallet_ethereum::Transaction,1046 ) -> opaque::UncheckedExtrinsic {1047 let extrinsic = UncheckedExtrinsic::new_unsigned(1048 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1049 );1050 let encoded = extrinsic.encode();1051 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1052 .expect("Encoded extrinsic is always valid")1053 }1054}10551056/// The address format for describing accounts.1057pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1058/// Block header type as expected by this runtime.1059pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1060/// Block type as expected by this runtime.1061pub type Block = generic::Block<Header, UncheckedExtrinsic>;1062/// A Block signed with a Justification1063pub type SignedBlock = generic::SignedBlock<Block>;1064/// BlockId type as expected by this runtime.1065pub type BlockId = generic::BlockId<Block>;1066/// The SignedExtension to the basic transaction logic.1067pub type SignedExtra = (1068 frame_system::CheckSpecVersion<Runtime>,1069 // system::CheckTxVersion<Runtime>,1070 frame_system::CheckGenesis<Runtime>,1071 frame_system::CheckEra<Runtime>,1072 frame_system::CheckNonce<Runtime>,1073 frame_system::CheckWeight<Runtime>,1074 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1075 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1076 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1077);1078/// Unchecked extrinsic type as expected by this runtime.1079pub type UncheckedExtrinsic =1080 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1081/// Extrinsic type that has already been checked.1082pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1083/// Executive: handles dispatch to the various modules.1084pub type Executive = frame_executive::Executive<1085 Runtime,1086 Block,1087 frame_system::ChainContext<Runtime>,1088 Runtime,1089 AllPalletsReversedWithSystemFirst,1090>;10911092impl_opaque_keys! {1093 pub struct SessionKeys {1094 pub aura: Aura,1095 }1096}10971098impl fp_self_contained::SelfContainedCall for Call {1099 type SignedInfo = H160;11001101 fn is_self_contained(&self) -> bool {1102 match self {1103 Call::Ethereum(call) => call.is_self_contained(),1104 _ => false,1105 }1106 }11071108 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1109 match self {1110 Call::Ethereum(call) => call.check_self_contained(),1111 _ => None,1112 }1113 }11141115 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1116 match self {1117 Call::Ethereum(call) => call.validate_self_contained(info),1118 _ => None,1119 }1120 }11211122 fn pre_dispatch_self_contained(1123 &self,1124 info: &Self::SignedInfo,1125 ) -> Option<Result<(), TransactionValidityError>> {1126 match self {1127 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1128 _ => None,1129 }1130 }11311132 fn apply_self_contained(1133 self,1134 info: Self::SignedInfo,1135 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1136 match self {1137 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1138 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1139 )),1140 _ => None,1141 }1142 }1143}11441145macro_rules! dispatch_unique_runtime {1146 ($collection:ident.$method:ident($($name:ident),*)) => {{1147 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1148 let dispatch = collection.as_dyn();11491150 Ok::<_, DispatchError>(dispatch.$method($($name),*))1151 }};1152}11531154impl_common_runtime_apis!();11551156struct CheckInherents;11571158impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1159 fn check_inherents(1160 block: &Block,1161 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1162 ) -> sp_inherents::CheckInherentsResult {1163 let relay_chain_slot = relay_state_proof1164 .read_slot()1165 .expect("Could not read the relay chain slot from the proof");11661167 let inherent_data =1168 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1169 relay_chain_slot,1170 sp_std::time::Duration::from_secs(6),1171 )1172 .create_inherent_data()1173 .expect("Could not create the timestamp inherent data");11741175 inherent_data.check_extrinsics(block)1176 }1177}11781179cumulus_pallet_parachain_system::register_validate_block!(1180 Runtime = Runtime,1181 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1182 CheckInherents = CheckInherents,1183);runtime/tests/src/lib.rsdiffbeforeafterboth--- a/runtime/tests/src/lib.rs
+++ b/runtime/tests/src/lib.rs
@@ -16,7 +16,7 @@
#![allow(clippy::from_over_into)]
-use sp_core::{H256, U256};
+use sp_core::{H160, H256, U256};
use frame_support::{
parameter_types,
traits::{Everything, ConstU32, ConstU64},
@@ -245,10 +245,18 @@
type WeightInfo = ();
}
+parameter_types! {
+ // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
+ pub const EvmCollectionHelperAddress: H160 = H160([
+ 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
+ ]);
+}
+
impl pallet_unique::Config for Test {
type Event = ();
type WeightInfo = ();
type CommonWeightInfo = CommonWeights<Self>;
+ type ContractAddress = EvmCollectionHelperAddress;
}
// Build genesis storage according to the mock runtime.
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -905,6 +905,7 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
+ type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -975,10 +976,6 @@
impl pallet_evm_contract_helpers::Config for Runtime {
type ContractAddress = HelpersContractAddress;
type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;
-}
-
-impl pallet_unique::eth::Config for Runtime {
- type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(