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.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 OnMethodCall, Account as EVMAccount, FeeCalculator, GasWeightMapping,54};55pub use frame_support::{56 construct_runtime, match_types,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,68 },69};70use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};71use up_data_structs::*;72// use pallet_contracts::weights::WeightInfo;73// #[cfg(any(feature = "std", test))]74use frame_system::{75 self as frame_system, EnsureRoot, EnsureSigned,76 limits::{BlockWeights, BlockLength},77};78use sp_arithmetic::{79 traits::{BaseArithmetic, Unsigned},80};81use smallvec::smallvec;82use codec::{Encode, Decode};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;91pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9293// Polkadot imports94use pallet_xcm::XcmPassthrough;95use polkadot_parachain::primitives::Sibling;96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 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 = "opal";129pub const TOKEN_SYMBOL: &str = "OPL";130131type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;132133impl RuntimeInstance for Runtime {134 type CrossAccountId = self::CrossAccountId;135 type TransactionConverter = self::TransactionConverter;136137 fn get_transaction_converter() -> TransactionConverter {138 TransactionConverter139 }140}141142/// The type for looking up accounts. We don't expect more than 4 billion of them, but you143/// never know...144pub type AccountIndex = u32;145146/// Balance of an account.147pub type Balance = u128;148149/// Index of a transaction in the chain.150pub type Index = u32;151152/// A hash of some data used by the chain.153pub type Hash = sp_core::H256;154155/// Digest item type.156pub type DigestItem = generic::DigestItem;157158/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know159/// the specifics of the runtime. They can then be made to be agnostic over specific formats160/// of data like extrinsics, allowing for them to continue syncing the network through upgrades161/// to even the core data structures.162pub mod opaque {163 use sp_std::prelude::*;164 use sp_runtime::impl_opaque_keys;165 use super::Aura;166167 pub use unique_runtime_common::types::*;168169 impl_opaque_keys! {170 pub struct SessionKeys {171 pub aura: Aura,172 }173 }174}175176/// This runtime version.177pub const VERSION: RuntimeVersion = RuntimeVersion {178 spec_name: create_runtime_str!(RUNTIME_NAME),179 impl_name: create_runtime_str!(RUNTIME_NAME),180 authoring_version: 1,181 spec_version: 921000,182 impl_version: 0,183 apis: RUNTIME_API_VERSIONS,184 transaction_version: 1,185 state_version: 0,186};187188#[derive(codec::Encode, codec::Decode)]189pub enum XCMPMessage<XAccountId, XBalance> {190 /// Transfer tokens to the given account from the Parachain account.191 TransferToken(XAccountId, XBalance),192}193194/// The version information used to identify this runtime when compiled natively.195#[cfg(feature = "std")]196pub fn native_version() -> NativeVersion {197 NativeVersion {198 runtime_version: VERSION,199 can_author_with: Default::default(),200 }201}202203type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;204205pub struct DealWithFees;206impl OnUnbalanced<NegativeImbalance> for DealWithFees {207 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {208 if let Some(fees) = fees_then_tips.next() {209 // for fees, 100% to treasury210 let mut split = fees.ration(100, 0);211 if let Some(tips) = fees_then_tips.next() {212 // for tips, if any, 100% to treasury213 tips.ration_merge_into(100, 0, &mut split);214 }215 Treasury::on_unbalanced(split.0);216 // Author::on_unbalanced(split.1);217 }218 }219}220221parameter_types! {222 pub const BlockHashCount: BlockNumber = 2400;223 pub RuntimeBlockLength: BlockLength =224 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228 .base_block(BlockExecutionWeight::get())229 .for_class(DispatchClass::all(), |weights| {230 weights.base_extrinsic = ExtrinsicBaseWeight::get();231 })232 .for_class(DispatchClass::Normal, |weights| {233 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234 })235 .for_class(DispatchClass::Operational, |weights| {236 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237 // Operational transactions have some extra reserved space, so that they238 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239 weights.reserved = Some(240 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241 );242 })243 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244 .build_or_panic();245 pub const Version: RuntimeVersion = VERSION;246 pub const SS58Prefix: u8 = 42;247}248249parameter_types! {250 pub const ChainId: u64 = 8882;251}252253pub struct FixedFee;254impl FeeCalculator for FixedFee {255 fn min_gas_price() -> U256 {256 MIN_GAS_PRICE.into()257 }258}259260// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case261// (contract, which only writes a lot of data),262// approximating on top of our real store write weight263parameter_types! {264 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;265 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;266 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();267}268269/// Limiting EVM execution to 50% of block for substrate users and management tasks270/// EVM transaction consumes more weight than substrate's, so we can't rely on them being271/// scheduled fairly272const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);273parameter_types! {274 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());275}276277pub enum FixedGasWeightMapping {}278impl GasWeightMapping for FixedGasWeightMapping {279 fn gas_to_weight(gas: u64) -> Weight {280 gas.saturating_mul(WeightPerGas::get())281 }282 fn weight_to_gas(weight: Weight) -> u64 {283 weight / WeightPerGas::get()284 }285}286287impl pallet_evm::account::Config for Runtime {288 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;289 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;290 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;291}292293impl pallet_evm::Config for Runtime {294 type BlockGasLimit = BlockGasLimit;295 type FeeCalculator = FixedFee;296 type GasWeightMapping = FixedGasWeightMapping;297 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;298 type CallOrigin = EnsureAddressTruncated<Self>;299 type WithdrawOrigin = EnsureAddressTruncated<Self>;300 type AddressMapping = HashedAddressMapping<Self::Hashing>;301 type PrecompilesType = ();302 type PrecompilesValue = ();303 type Currency = Balances;304 type Event = Event;305 type OnMethodCall = (306 pallet_evm_migration::OnMethodCall<Self>,307 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,308 CollectionDispatchT<Self>,309 pallet_unique::eth::CollectionHelperOnMethodCall<Self>,310 );311 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;312 type ChainId = ChainId;313 type Runner = pallet_evm::runner::stack::Runner<Self>;314 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;315 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;316 type FindAuthor = EthereumFindAuthor<Aura>;317}318319impl pallet_evm_migration::Config for Runtime {320 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;321}322323pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);324impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {325 fn find_author<'a, I>(digests: I) -> Option<H160>326 where327 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,328 {329 if let Some(author_index) = F::find_author(digests) {330 let authority_id = Aura::authorities()[author_index as usize].clone();331 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));332 }333 None334 }335}336337impl pallet_ethereum::Config for Runtime {338 type Event = Event;339 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;340}341342impl pallet_randomness_collective_flip::Config for Runtime {}343344impl frame_system::Config for Runtime {345 /// The data to be stored in an account.346 type AccountData = pallet_balances::AccountData<Balance>;347 /// The identifier used to distinguish between accounts.348 type AccountId = AccountId;349 /// The basic call filter to use in dispatchable.350 type BaseCallFilter = Everything;351 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).352 type BlockHashCount = BlockHashCount;353 /// The maximum length of a block (in bytes).354 type BlockLength = RuntimeBlockLength;355 /// The index type for blocks.356 type BlockNumber = BlockNumber;357 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.358 type BlockWeights = RuntimeBlockWeights;359 /// The aggregated dispatch type that is available for extrinsics.360 type Call = Call;361 /// The weight of database operations that the runtime can invoke.362 type DbWeight = RocksDbWeight;363 /// The ubiquitous event type.364 type Event = Event;365 /// The type for hashing blocks and tries.366 type Hash = Hash;367 /// The hashing algorithm used.368 type Hashing = BlakeTwo256;369 /// The header type.370 type Header = generic::Header<BlockNumber, BlakeTwo256>;371 /// The index type for storing how many extrinsics an account has signed.372 type Index = Index;373 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.374 type Lookup = AccountIdLookup<AccountId, ()>;375 /// What to do if an account is fully reaped from the system.376 type OnKilledAccount = ();377 /// What to do if a new account is created.378 type OnNewAccount = ();379 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;380 /// The ubiquitous origin type.381 type Origin = Origin;382 /// This type is being generated by `construct_runtime!`.383 type PalletInfo = PalletInfo;384 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.385 type SS58Prefix = SS58Prefix;386 /// Weight information for the extrinsics of this pallet.387 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;388 /// Version of the runtime.389 type Version = Version;390 type MaxConsumers = ConstU32<16>;391}392393parameter_types! {394 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;395}396397impl pallet_timestamp::Config for Runtime {398 /// A timestamp: milliseconds since the unix epoch.399 type Moment = u64;400 type OnTimestampSet = ();401 type MinimumPeriod = MinimumPeriod;402 type WeightInfo = ();403}404405parameter_types! {406 // pub const ExistentialDeposit: u128 = 500;407 pub const ExistentialDeposit: u128 = 0;408 pub const MaxLocks: u32 = 50;409}410411impl pallet_balances::Config for Runtime {412 type MaxLocks = MaxLocks;413 type MaxReserves = ();414 type ReserveIdentifier = [u8; 8];415 /// The type for recording an account's balance.416 type Balance = Balance;417 /// The ubiquitous event type.418 type Event = Event;419 type DustRemoval = Treasury;420 type ExistentialDeposit = ExistentialDeposit;421 type AccountStore = System;422 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;423}424425pub const fn deposit(items: u32, bytes: u32) -> Balance {426 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE427}428429/*430parameter_types! {431 pub TombstoneDeposit: Balance = deposit(432 1,433 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,434 );435 pub DepositPerContract: Balance = TombstoneDeposit::get();436 pub const DepositPerStorageByte: Balance = deposit(0, 1);437 pub const DepositPerStorageItem: Balance = deposit(1, 0);438 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);439 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;440 pub const SignedClaimHandicap: u32 = 2;441 pub const MaxDepth: u32 = 32;442 pub const MaxValueSize: u32 = 16 * 1024;443 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb444 // The lazy deletion runs inside on_initialize.445 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *446 RuntimeBlockWeights::get().max_block;447 // The weight needed for decoding the queue should be less or equal than a fifth448 // of the overall weight dedicated to the lazy deletion.449 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (450 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -451 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)452 )) / 5) as u32;453 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();454}455456impl pallet_contracts::Config for Runtime {457 type Time = Timestamp;458 type Randomness = RandomnessCollectiveFlip;459 type Currency = Balances;460 type Event = Event;461 type RentPayment = ();462 type SignedClaimHandicap = SignedClaimHandicap;463 type TombstoneDeposit = TombstoneDeposit;464 type DepositPerContract = DepositPerContract;465 type DepositPerStorageByte = DepositPerStorageByte;466 type DepositPerStorageItem = DepositPerStorageItem;467 type RentFraction = RentFraction;468 type SurchargeReward = SurchargeReward;469 type WeightPrice = pallet_transaction_payment::Pallet<Self>;470 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;471 type ChainExtension = NFTExtension;472 type DeletionQueueDepth = DeletionQueueDepth;473 type DeletionWeightLimit = DeletionWeightLimit;474 type Schedule = Schedule;475 type CallStack = [pallet_contracts::Frame<Self>; 31];476}477*/478479parameter_types! {480 /// This value increases the priority of `Operational` transactions by adding481 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.482 pub const OperationalFeeMultiplier: u8 = 5;483}484485/// Linear implementor of `WeightToFeePolynomial`486pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);487488impl<T> WeightToFeePolynomial for LinearFee<T>489where490 T: BaseArithmetic + From<u32> + Copy + Unsigned,491{492 type Balance = T;493494 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {495 smallvec!(WeightToFeeCoefficient {496 // Targeting 0.1 Unique per NFT transfer497 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),498 coeff_frac: Perbill::zero(),499 negative: false,500 degree: 1,501 })502 }503}504505impl pallet_transaction_payment::Config for Runtime {506 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;507 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;508 type OperationalFeeMultiplier = OperationalFeeMultiplier;509 type WeightToFee = LinearFee<Balance>;510 type FeeMultiplierUpdate = ();511}512513parameter_types! {514 pub const ProposalBond: Permill = Permill::from_percent(5);515 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;516 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;517 pub const SpendPeriod: BlockNumber = 5 * MINUTES;518 pub const Burn: Permill = Permill::from_percent(0);519 pub const TipCountdown: BlockNumber = 1 * DAYS;520 pub const TipFindersFee: Percent = Percent::from_percent(20);521 pub const TipReportDepositBase: Balance = 1 * UNIQUE;522 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;523 pub const BountyDepositBase: Balance = 1 * UNIQUE;524 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;525 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");526 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;527 pub const MaximumReasonLength: u32 = 16384;528 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);529 pub const BountyValueMinimum: Balance = 5 * UNIQUE;530 pub const MaxApprovals: u32 = 100;531}532533impl pallet_treasury::Config for Runtime {534 type PalletId = TreasuryModuleId;535 type Currency = Balances;536 type ApproveOrigin = EnsureRoot<AccountId>;537 type RejectOrigin = EnsureRoot<AccountId>;538 type Event = Event;539 type OnSlash = ();540 type ProposalBond = ProposalBond;541 type ProposalBondMinimum = ProposalBondMinimum;542 type ProposalBondMaximum = ProposalBondMaximum;543 type SpendPeriod = SpendPeriod;544 type Burn = Burn;545 type BurnDestination = ();546 type SpendFunds = ();547 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;548 type MaxApprovals = MaxApprovals;549}550551impl pallet_sudo::Config for Runtime {552 type Event = Event;553 type Call = Call;554}555556pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);557558impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider559 for RelayChainBlockNumberProvider<T>560{561 type BlockNumber = BlockNumber;562563 fn current_block_number() -> Self::BlockNumber {564 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()565 .map(|d| d.relay_parent_number)566 .unwrap_or_default()567 }568}569570parameter_types! {571 pub const MinVestedTransfer: Balance = 10 * UNIQUE;572 pub const MaxVestingSchedules: u32 = 28;573}574575impl orml_vesting::Config for Runtime {576 type Event = Event;577 type Currency = pallet_balances::Pallet<Runtime>;578 type MinVestedTransfer = MinVestedTransfer;579 type VestedTransferOrigin = EnsureSigned<AccountId>;580 type WeightInfo = ();581 type MaxVestingSchedules = MaxVestingSchedules;582 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;583}584585parameter_types! {586 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;587 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;588}589590impl cumulus_pallet_parachain_system::Config for Runtime {591 type Event = Event;592 type SelfParaId = parachain_info::Pallet<Self>;593 type OnSystemEvent = ();594 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<595 // MaxDownwardMessageWeight,596 // XcmExecutor<XcmConfig>,597 // Call,598 // >;599 type OutboundXcmpMessageSource = XcmpQueue;600 type DmpMessageHandler = DmpQueue;601 type ReservedDmpWeight = ReservedDmpWeight;602 type ReservedXcmpWeight = ReservedXcmpWeight;603 type XcmpMessageHandler = XcmpQueue;604}605606impl parachain_info::Config for Runtime {}607608impl cumulus_pallet_aura_ext::Config for Runtime {}609610parameter_types! {611 pub const RelayLocation: MultiLocation = MultiLocation::parent();612 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;613 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();614 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();615}616617/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used618/// when determining ownership of accounts for asset transacting and when attempting to use XCM619/// `Transact` in order to determine the dispatch Origin.620pub type LocationToAccountId = (621 // The parent (Relay-chain) origin converts to the default `AccountId`.622 ParentIsPreset<AccountId>,623 // Sibling parachain origins convert to AccountId via the `ParaId::into`.624 SiblingParachainConvertsVia<Sibling, AccountId>,625 // Straight up local `AccountId32` origins just alias directly to `AccountId`.626 AccountId32Aliases<RelayNetwork, AccountId>,627);628629pub struct OnlySelfCurrency;630impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {631 fn matches_fungible(a: &MultiAsset) -> Option<B> {632 match (&a.id, &a.fun) {633 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),634 _ => None,635 }636 }637}638639/// Means for transacting assets on this chain.640pub type LocalAssetTransactor = CurrencyAdapter<641 // Use this currency:642 Balances,643 // Use this currency when it is a fungible asset matching the given location or name:644 OnlySelfCurrency,645 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:646 LocationToAccountId,647 // Our chain's account ID type (we can't get away without mentioning it explicitly):648 AccountId,649 // We don't track any teleports.650 (),651>;652653/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,654/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can655/// biases the kind of local `Origin` it will become.656pub type XcmOriginToTransactDispatchOrigin = (657 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location658 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for659 // foreign chains who want to have a local sovereign account on this chain which they control.660 SovereignSignedViaLocation<LocationToAccountId, Origin>,661 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when662 // recognised.663 RelayChainAsNative<RelayOrigin, Origin>,664 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when665 // recognised.666 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,667 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a668 // transaction from the Root origin.669 ParentAsSuperuser<Origin>,670 // Native signed account converter; this just converts an `AccountId32` origin into a normal671 // `Origin::Signed` origin of the same 32-byte value.672 SignedAccountId32AsNative<RelayNetwork, Origin>,673 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.674 XcmPassthrough<Origin>,675);676677parameter_types! {678 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.679 pub UnitWeightCost: Weight = 1_000_000;680 // 1200 UNIQUEs buy 1 second of weight.681 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);682 pub const MaxInstructions: u32 = 100;683 pub const MaxAuthorities: u32 = 100_000;684}685686match_types! {687 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {688 MultiLocation { parents: 1, interior: Here } |689 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }690 };691}692693pub type Barrier = (694 TakeWeightCredit,695 AllowTopLevelPaidExecutionFrom<Everything>,696 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,697 // ^^^ Parent & its unit plurality gets free execution698);699700pub struct UsingOnlySelfCurrencyComponents<701 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,702 AssetId: Get<MultiLocation>,703 AccountId,704 Currency: CurrencyT<AccountId>,705 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,706>(707 Weight,708 Currency::Balance,709 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,710);711impl<712 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,713 AssetId: Get<MultiLocation>,714 AccountId,715 Currency: CurrencyT<AccountId>,716 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,717 > WeightTrader718 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>719{720 fn new() -> Self {721 Self(0, Zero::zero(), PhantomData)722 }723724 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {725 let amount = WeightToFee::calc(&weight);726 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;727728 // location to this parachain through relay chain729 let option1: xcm::v1::AssetId = Concrete(MultiLocation {730 parents: 1,731 interior: X1(Parachain(ParachainInfo::parachain_id().into())),732 });733 // direct location734 let option2: xcm::v1::AssetId = Concrete(MultiLocation {735 parents: 0,736 interior: Here,737 });738739 let required = if payment.fungible.contains_key(&option1) {740 (option1, u128_amount).into()741 } else if payment.fungible.contains_key(&option2) {742 (option2, u128_amount).into()743 } else {744 (Concrete(MultiLocation::default()), u128_amount).into()745 };746747 let unused = payment748 .checked_sub(required)749 .map_err(|_| XcmError::TooExpensive)?;750 self.0 = self.0.saturating_add(weight);751 self.1 = self.1.saturating_add(amount);752 Ok(unused)753 }754755 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {756 let weight = weight.min(self.0);757 let amount = WeightToFee::calc(&weight);758 self.0 -= weight;759 self.1 = self.1.saturating_sub(amount);760 let amount: u128 = amount.saturated_into();761 if amount > 0 {762 Some((AssetId::get(), amount).into())763 } else {764 None765 }766 }767}768impl<769 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,770 AssetId: Get<MultiLocation>,771 AccountId,772 Currency: CurrencyT<AccountId>,773 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,774 > Drop775 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>776{777 fn drop(&mut self) {778 OnUnbalanced::on_unbalanced(Currency::issue(self.1));779 }780}781782pub struct XcmConfig;783impl Config for XcmConfig {784 type Call = Call;785 type XcmSender = XcmRouter;786 // How to withdraw and deposit an asset.787 type AssetTransactor = LocalAssetTransactor;788 type OriginConverter = XcmOriginToTransactDispatchOrigin;789 type IsReserve = NativeAsset;790 type IsTeleporter = (); // Teleportation is disabled791 type LocationInverter = LocationInverter<Ancestry>;792 type Barrier = Barrier;793 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;794 type Trader = UsingOnlySelfCurrencyComponents<795 IdentityFee<Balance>,796 RelayLocation,797 AccountId,798 Balances,799 (),800 >;801 type ResponseHandler = (); // Don't handle responses for now.802 type SubscriptionService = PolkadotXcm;803804 type AssetTrap = PolkadotXcm;805 type AssetClaims = PolkadotXcm;806}807808// parameter_types! {809// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;810// }811812/// No local origins on this chain are allowed to dispatch XCM sends/executions.813pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);814815/// The means for routing XCM messages which are not for local execution into the right message816/// queues.817pub type XcmRouter = (818 // Two routers - use UMP to communicate with the relay chain:819 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,820 // ..and XCMP to communicate with the sibling chains.821 XcmpQueue,822);823824impl pallet_evm_coder_substrate::Config for Runtime {825 type GasWeightMapping = FixedGasWeightMapping;826}827828impl pallet_xcm::Config for Runtime {829 type Event = Event;830 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;831 type XcmRouter = XcmRouter;832 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;833 type XcmExecuteFilter = Everything;834 type XcmExecutor = XcmExecutor<XcmConfig>;835 type XcmTeleportFilter = Everything;836 type XcmReserveTransferFilter = Everything;837 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;838 type LocationInverter = LocationInverter<Ancestry>;839 type Origin = Origin;840 type Call = Call;841 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;842 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;843}844845impl cumulus_pallet_xcm::Config for Runtime {846 type Event = Event;847 type XcmExecutor = XcmExecutor<XcmConfig>;848}849850impl cumulus_pallet_xcmp_queue::Config for Runtime {851 type WeightInfo = ();852 type Event = Event;853 type XcmExecutor = XcmExecutor<XcmConfig>;854 type ChannelInfo = ParachainSystem;855 type VersionWrapper = ();856 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;857 type ControllerOrigin = EnsureRoot<AccountId>;858 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;859}860861impl cumulus_pallet_dmp_queue::Config for Runtime {862 type Event = Event;863 type XcmExecutor = XcmExecutor<XcmConfig>;864 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;865}866867impl pallet_aura::Config for Runtime {868 type AuthorityId = AuraId;869 type DisabledValidators = ();870 type MaxAuthorities = MaxAuthorities;871}872873parameter_types! {874 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();875 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;876}877878impl pallet_common::Config for Runtime {879 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;880 type Event = Event;881 type Currency = Balances;882 type CollectionCreationPrice = CollectionCreationPrice;883 type TreasuryAccountId = TreasuryAccountId;884 type CollectionDispatch = CollectionDispatchT<Self>;885886 type EvmTokenAddressMapping = EvmTokenAddressMapping;887 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;888}889890impl pallet_structure::Config for Runtime {891 type Event = Event;892 type Call = Call;893 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;894}895896impl pallet_fungible::Config for Runtime {897 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;898}899impl pallet_refungible::Config for Runtime {900 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;901}902impl pallet_nonfungible::Config for Runtime {903 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;904}905906/*907TODO free RMRK!908impl pallet_proxy_rmrk_core::Config for Runtime {909 type Event = Event;910}911912impl pallet_proxy_rmrk_equip::Config for Runtime {913 type Event = Event;914}*/915916impl pallet_unique::Config for Runtime {917 type Event = Event;918 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;919 type CommonWeightInfo = CommonWeights<Self>;920}921922parameter_types! {923 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied924}925926/// Used for the pallet inflation927impl pallet_inflation::Config for Runtime {928 type Currency = Balances;929 type TreasuryAccountId = TreasuryAccountId;930 type InflationBlockInterval = InflationBlockInterval;931 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;932}933934// parameter_types! {935// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *936// RuntimeBlockWeights::get().max_block;937// pub const MaxScheduledPerBlock: u32 = 50;938// }939940type EvmSponsorshipHandler = (941 UniqueEthSponsorshipHandler<Runtime>,942 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,943);944type SponsorshipHandler = (945 UniqueSponsorshipHandler<Runtime>,946 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,947 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,948);949950// impl pallet_unq_scheduler::Config for Runtime {951// type Event = Event;952// type Origin = Origin;953// type PalletsOrigin = OriginCaller;954// type Call = Call;955// type MaximumWeight = MaximumSchedulerWeight;956// type ScheduleOrigin = EnsureSigned<AccountId>;957// type MaxScheduledPerBlock = MaxScheduledPerBlock;958// type SponsorshipHandler = SponsorshipHandler;959// type WeightInfo = ();960// }961962impl pallet_evm_transaction_payment::Config for Runtime {963 type EvmSponsorshipHandler = EvmSponsorshipHandler;964 type Currency = Balances;965}966967impl pallet_charge_transaction::Config for Runtime {968 type SponsorshipHandler = SponsorshipHandler;969}970971// impl pallet_contract_helpers::Config for Runtime {972// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;973// }974975parameter_types! {976 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049977 pub const HelpersContractAddress: H160 = H160([978 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,979 ]);980981 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f982 pub const EvmCollectionHelperAddress: H160 = H160([983 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,984 ]);985}986987impl pallet_evm_contract_helpers::Config for Runtime {988 type ContractAddress = HelpersContractAddress;989 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;990}991992impl pallet_unique::eth::Config for Runtime {993 type ContractAddress = EvmCollectionHelperAddress;994}995996construct_runtime!(997 pub enum Runtime where998 Block = Block,999 NodeBlock = opaque::Block,1000 UncheckedExtrinsic = UncheckedExtrinsic1001 {1002 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1003 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,10041005 Aura: pallet_aura::{Pallet, Config<T>} = 22,1006 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10071008 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1009 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1010 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1011 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1012 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1013 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1014 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1015 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1016 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1017 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10181019 // XCM helpers.1020 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1021 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1022 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1023 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10241025 // Unique Pallets1026 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1027 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1028 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1029 // free = 631030 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1031 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1032 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1033 Fungible: pallet_fungible::{Pallet, Storage} = 67,1034 Refungible: pallet_refungible::{Pallet, Storage} = 68,1035 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1036 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1037 /* TODO free RMRK!1038 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1039 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,1040 */10411042 // Frontier1043 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1044 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10451046 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1047 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1048 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1049 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1050 }1051);10521053pub struct TransactionConverter;10541055impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1056 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1057 UncheckedExtrinsic::new_unsigned(1058 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1059 )1060 }1061}10621063impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1064 fn convert_transaction(1065 &self,1066 transaction: pallet_ethereum::Transaction,1067 ) -> opaque::UncheckedExtrinsic {1068 let extrinsic = UncheckedExtrinsic::new_unsigned(1069 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1070 );1071 let encoded = extrinsic.encode();1072 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1073 .expect("Encoded extrinsic is always valid")1074 }1075}10761077/// The address format for describing accounts.1078pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1079/// Block header type as expected by this runtime.1080pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1081/// Block type as expected by this runtime.1082pub type Block = generic::Block<Header, UncheckedExtrinsic>;1083/// A Block signed with a Justification1084pub type SignedBlock = generic::SignedBlock<Block>;1085/// BlockId type as expected by this runtime.1086pub type BlockId = generic::BlockId<Block>;1087/// The SignedExtension to the basic transaction logic.1088pub type SignedExtra = (1089 frame_system::CheckSpecVersion<Runtime>,1090 // system::CheckTxVersion<Runtime>,1091 frame_system::CheckGenesis<Runtime>,1092 frame_system::CheckEra<Runtime>,1093 frame_system::CheckNonce<Runtime>,1094 frame_system::CheckWeight<Runtime>,1095 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1096 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1097 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1098);1099/// Unchecked extrinsic type as expected by this runtime.1100pub type UncheckedExtrinsic =1101 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1102/// Extrinsic type that has already been checked.1103pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1104/// Executive: handles dispatch to the various modules.1105pub type Executive = frame_executive::Executive<1106 Runtime,1107 Block,1108 frame_system::ChainContext<Runtime>,1109 Runtime,1110 AllPalletsReversedWithSystemFirst,1111>;11121113impl_opaque_keys! {1114 pub struct SessionKeys {1115 pub aura: Aura,1116 }1117}11181119impl fp_self_contained::SelfContainedCall for Call {1120 type SignedInfo = H160;11211122 fn is_self_contained(&self) -> bool {1123 match self {1124 Call::Ethereum(call) => call.is_self_contained(),1125 _ => false,1126 }1127 }11281129 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1130 match self {1131 Call::Ethereum(call) => call.check_self_contained(),1132 _ => None,1133 }1134 }11351136 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1137 match self {1138 Call::Ethereum(call) => call.validate_self_contained(info),1139 _ => None,1140 }1141 }11421143 fn pre_dispatch_self_contained(1144 &self,1145 info: &Self::SignedInfo,1146 ) -> Option<Result<(), TransactionValidityError>> {1147 match self {1148 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1149 _ => None,1150 }1151 }11521153 fn apply_self_contained(1154 self,1155 info: Self::SignedInfo,1156 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1157 match self {1158 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1159 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1160 )),1161 _ => None,1162 }1163 }1164}11651166macro_rules! dispatch_unique_runtime {1167 ($collection:ident.$method:ident($($name:ident),*)) => {{1168 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1169 let dispatch = collection.as_dyn();11701171 Ok::<_, DispatchError>(dispatch.$method($($name),*))1172 }};1173}11741175impl_common_runtime_apis!();11761177struct CheckInherents;11781179impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1180 fn check_inherents(1181 block: &Block,1182 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1183 ) -> sp_inherents::CheckInherentsResult {1184 let relay_chain_slot = relay_state_proof1185 .read_slot()1186 .expect("Could not read the relay chain slot from the proof");11871188 let inherent_data =1189 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1190 relay_chain_slot,1191 sp_std::time::Duration::from_secs(6),1192 )1193 .create_inherent_data()1194 .expect("Could not create the timestamp inherent data");11951196 inherent_data.check_extrinsics(block)1197 }1198}11991200cumulus_pallet_parachain_system::register_validate_block!(1201 Runtime = Runtime,1202 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1203 CheckInherents = CheckInherents,1204);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 OnMethodCall, Account as EVMAccount, FeeCalculator, GasWeightMapping,54};55pub use frame_support::{56 construct_runtime, match_types,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,68 },69};70use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};71use up_data_structs::*;72// use pallet_contracts::weights::WeightInfo;73// #[cfg(any(feature = "std", test))]74use frame_system::{75 self as frame_system, EnsureRoot, EnsureSigned,76 limits::{BlockWeights, BlockLength},77};78use sp_arithmetic::{79 traits::{BaseArithmetic, Unsigned},80};81use smallvec::smallvec;82use codec::{Encode, Decode};83use fp_rpc::TransactionStatus;84use sp_runtime::{85 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},86 transaction_validity::TransactionValidityError,87 SaturatedConversion,88};8990// pub use pallet_timestamp::Call as TimestampCall;91pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9293// Polkadot imports94use pallet_xcm::XcmPassthrough;95use polkadot_parachain::primitives::Sibling;96use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};97use xcm_builder::{98 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,99 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,100 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,101 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,102 ParentIsPreset,103};104use xcm_executor::{Config, XcmExecutor, Assets};105use sp_std::{marker::PhantomData};106107use xcm::latest::{108 // Xcm,109 AssetId::{Concrete},110 Fungibility::Fungible as XcmFungible,111 MultiAsset,112 Error as XcmError,113};114use xcm_executor::traits::{MatchesFungible, WeightTrader};115//use xcm_executor::traits::MatchesFungible;116use sp_runtime::traits::CheckedConversion;117118use unique_runtime_common::{119 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 = "opal";129pub const TOKEN_SYMBOL: &str = "OPL";130131type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;132133impl RuntimeInstance for Runtime {134 type CrossAccountId = self::CrossAccountId;135 type TransactionConverter = self::TransactionConverter;136137 fn get_transaction_converter() -> TransactionConverter {138 TransactionConverter139 }140}141142/// The type for looking up accounts. We don't expect more than 4 billion of them, but you143/// never know...144pub type AccountIndex = u32;145146/// Balance of an account.147pub type Balance = u128;148149/// Index of a transaction in the chain.150pub type Index = u32;151152/// A hash of some data used by the chain.153pub type Hash = sp_core::H256;154155/// Digest item type.156pub type DigestItem = generic::DigestItem;157158/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know159/// the specifics of the runtime. They can then be made to be agnostic over specific formats160/// of data like extrinsics, allowing for them to continue syncing the network through upgrades161/// to even the core data structures.162pub mod opaque {163 use sp_std::prelude::*;164 use sp_runtime::impl_opaque_keys;165 use super::Aura;166167 pub use unique_runtime_common::types::*;168169 impl_opaque_keys! {170 pub struct SessionKeys {171 pub aura: Aura,172 }173 }174}175176/// This runtime version.177pub const VERSION: RuntimeVersion = RuntimeVersion {178 spec_name: create_runtime_str!(RUNTIME_NAME),179 impl_name: create_runtime_str!(RUNTIME_NAME),180 authoring_version: 1,181 spec_version: 921000,182 impl_version: 0,183 apis: RUNTIME_API_VERSIONS,184 transaction_version: 1,185 state_version: 0,186};187188#[derive(codec::Encode, codec::Decode)]189pub enum XCMPMessage<XAccountId, XBalance> {190 /// Transfer tokens to the given account from the Parachain account.191 TransferToken(XAccountId, XBalance),192}193194/// The version information used to identify this runtime when compiled natively.195#[cfg(feature = "std")]196pub fn native_version() -> NativeVersion {197 NativeVersion {198 runtime_version: VERSION,199 can_author_with: Default::default(),200 }201}202203type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;204205pub struct DealWithFees;206impl OnUnbalanced<NegativeImbalance> for DealWithFees {207 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {208 if let Some(fees) = fees_then_tips.next() {209 // for fees, 100% to treasury210 let mut split = fees.ration(100, 0);211 if let Some(tips) = fees_then_tips.next() {212 // for tips, if any, 100% to treasury213 tips.ration_merge_into(100, 0, &mut split);214 }215 Treasury::on_unbalanced(split.0);216 // Author::on_unbalanced(split.1);217 }218 }219}220221parameter_types! {222 pub const BlockHashCount: BlockNumber = 2400;223 pub RuntimeBlockLength: BlockLength =224 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);225 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);226 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;227 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()228 .base_block(BlockExecutionWeight::get())229 .for_class(DispatchClass::all(), |weights| {230 weights.base_extrinsic = ExtrinsicBaseWeight::get();231 })232 .for_class(DispatchClass::Normal, |weights| {233 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);234 })235 .for_class(DispatchClass::Operational, |weights| {236 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);237 // Operational transactions have some extra reserved space, so that they238 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.239 weights.reserved = Some(240 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT241 );242 })243 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)244 .build_or_panic();245 pub const Version: RuntimeVersion = VERSION;246 pub const SS58Prefix: u8 = 42;247}248249parameter_types! {250 pub const ChainId: u64 = 8882;251}252253pub struct FixedFee;254impl FeeCalculator for FixedFee {255 fn min_gas_price() -> U256 {256 MIN_GAS_PRICE.into()257 }258}259260// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case261// (contract, which only writes a lot of data),262// approximating on top of our real store write weight263parameter_types! {264 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;265 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;266 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();267}268269/// Limiting EVM execution to 50% of block for substrate users and management tasks270/// EVM transaction consumes more weight than substrate's, so we can't rely on them being271/// scheduled fairly272const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);273parameter_types! {274 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());275}276277pub enum FixedGasWeightMapping {}278impl GasWeightMapping for FixedGasWeightMapping {279 fn gas_to_weight(gas: u64) -> Weight {280 gas.saturating_mul(WeightPerGas::get())281 }282 fn weight_to_gas(weight: Weight) -> u64 {283 weight / WeightPerGas::get()284 }285}286287impl pallet_evm::account::Config for Runtime {288 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;289 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;290 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;291}292293impl pallet_evm::Config for Runtime {294 type BlockGasLimit = BlockGasLimit;295 type FeeCalculator = FixedFee;296 type GasWeightMapping = FixedGasWeightMapping;297 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;298 type CallOrigin = EnsureAddressTruncated<Self>;299 type WithdrawOrigin = EnsureAddressTruncated<Self>;300 type AddressMapping = HashedAddressMapping<Self::Hashing>;301 type PrecompilesType = ();302 type PrecompilesValue = ();303 type Currency = Balances;304 type Event = Event;305 type OnMethodCall = (306 pallet_evm_migration::OnMethodCall<Self>,307 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,308 CollectionDispatchT<Self>,309 pallet_unique::eth::CollectionHelperOnMethodCall<Self>,310 );311 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;312 type ChainId = ChainId;313 type Runner = pallet_evm::runner::stack::Runner<Self>;314 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;315 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;316 type FindAuthor = EthereumFindAuthor<Aura>;317}318319impl pallet_evm_migration::Config for Runtime {320 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;321}322323pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);324impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {325 fn find_author<'a, I>(digests: I) -> Option<H160>326 where327 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,328 {329 if let Some(author_index) = F::find_author(digests) {330 let authority_id = Aura::authorities()[author_index as usize].clone();331 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));332 }333 None334 }335}336337impl pallet_ethereum::Config for Runtime {338 type Event = Event;339 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;340}341342impl pallet_randomness_collective_flip::Config for Runtime {}343344impl frame_system::Config for Runtime {345 /// The data to be stored in an account.346 type AccountData = pallet_balances::AccountData<Balance>;347 /// The identifier used to distinguish between accounts.348 type AccountId = AccountId;349 /// The basic call filter to use in dispatchable.350 type BaseCallFilter = Everything;351 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).352 type BlockHashCount = BlockHashCount;353 /// The maximum length of a block (in bytes).354 type BlockLength = RuntimeBlockLength;355 /// The index type for blocks.356 type BlockNumber = BlockNumber;357 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.358 type BlockWeights = RuntimeBlockWeights;359 /// The aggregated dispatch type that is available for extrinsics.360 type Call = Call;361 /// The weight of database operations that the runtime can invoke.362 type DbWeight = RocksDbWeight;363 /// The ubiquitous event type.364 type Event = Event;365 /// The type for hashing blocks and tries.366 type Hash = Hash;367 /// The hashing algorithm used.368 type Hashing = BlakeTwo256;369 /// The header type.370 type Header = generic::Header<BlockNumber, BlakeTwo256>;371 /// The index type for storing how many extrinsics an account has signed.372 type Index = Index;373 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.374 type Lookup = AccountIdLookup<AccountId, ()>;375 /// What to do if an account is fully reaped from the system.376 type OnKilledAccount = ();377 /// What to do if a new account is created.378 type OnNewAccount = ();379 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;380 /// The ubiquitous origin type.381 type Origin = Origin;382 /// This type is being generated by `construct_runtime!`.383 type PalletInfo = PalletInfo;384 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.385 type SS58Prefix = SS58Prefix;386 /// Weight information for the extrinsics of this pallet.387 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;388 /// Version of the runtime.389 type Version = Version;390 type MaxConsumers = ConstU32<16>;391}392393parameter_types! {394 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;395}396397impl pallet_timestamp::Config for Runtime {398 /// A timestamp: milliseconds since the unix epoch.399 type Moment = u64;400 type OnTimestampSet = ();401 type MinimumPeriod = MinimumPeriod;402 type WeightInfo = ();403}404405parameter_types! {406 // pub const ExistentialDeposit: u128 = 500;407 pub const ExistentialDeposit: u128 = 0;408 pub const MaxLocks: u32 = 50;409}410411impl pallet_balances::Config for Runtime {412 type MaxLocks = MaxLocks;413 type MaxReserves = ();414 type ReserveIdentifier = [u8; 8];415 /// The type for recording an account's balance.416 type Balance = Balance;417 /// The ubiquitous event type.418 type Event = Event;419 type DustRemoval = Treasury;420 type ExistentialDeposit = ExistentialDeposit;421 type AccountStore = System;422 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;423}424425pub const fn deposit(items: u32, bytes: u32) -> Balance {426 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE427}428429/*430parameter_types! {431 pub TombstoneDeposit: Balance = deposit(432 1,433 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,434 );435 pub DepositPerContract: Balance = TombstoneDeposit::get();436 pub const DepositPerStorageByte: Balance = deposit(0, 1);437 pub const DepositPerStorageItem: Balance = deposit(1, 0);438 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);439 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;440 pub const SignedClaimHandicap: u32 = 2;441 pub const MaxDepth: u32 = 32;442 pub const MaxValueSize: u32 = 16 * 1024;443 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb444 // The lazy deletion runs inside on_initialize.445 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *446 RuntimeBlockWeights::get().max_block;447 // The weight needed for decoding the queue should be less or equal than a fifth448 // of the overall weight dedicated to the lazy deletion.449 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (450 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -451 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)452 )) / 5) as u32;453 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();454}455456impl pallet_contracts::Config for Runtime {457 type Time = Timestamp;458 type Randomness = RandomnessCollectiveFlip;459 type Currency = Balances;460 type Event = Event;461 type RentPayment = ();462 type SignedClaimHandicap = SignedClaimHandicap;463 type TombstoneDeposit = TombstoneDeposit;464 type DepositPerContract = DepositPerContract;465 type DepositPerStorageByte = DepositPerStorageByte;466 type DepositPerStorageItem = DepositPerStorageItem;467 type RentFraction = RentFraction;468 type SurchargeReward = SurchargeReward;469 type WeightPrice = pallet_transaction_payment::Pallet<Self>;470 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;471 type ChainExtension = NFTExtension;472 type DeletionQueueDepth = DeletionQueueDepth;473 type DeletionWeightLimit = DeletionWeightLimit;474 type Schedule = Schedule;475 type CallStack = [pallet_contracts::Frame<Self>; 31];476}477*/478479parameter_types! {480 /// This value increases the priority of `Operational` transactions by adding481 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.482 pub const OperationalFeeMultiplier: u8 = 5;483}484485/// Linear implementor of `WeightToFeePolynomial`486pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);487488impl<T> WeightToFeePolynomial for LinearFee<T>489where490 T: BaseArithmetic + From<u32> + Copy + Unsigned,491{492 type Balance = T;493494 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {495 smallvec!(WeightToFeeCoefficient {496 // Targeting 0.1 Unique per NFT transfer497 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),498 coeff_frac: Perbill::zero(),499 negative: false,500 degree: 1,501 })502 }503}504505impl pallet_transaction_payment::Config for Runtime {506 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;507 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;508 type OperationalFeeMultiplier = OperationalFeeMultiplier;509 type WeightToFee = LinearFee<Balance>;510 type FeeMultiplierUpdate = ();511}512513parameter_types! {514 pub const ProposalBond: Permill = Permill::from_percent(5);515 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;516 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;517 pub const SpendPeriod: BlockNumber = 5 * MINUTES;518 pub const Burn: Permill = Permill::from_percent(0);519 pub const TipCountdown: BlockNumber = 1 * DAYS;520 pub const TipFindersFee: Percent = Percent::from_percent(20);521 pub const TipReportDepositBase: Balance = 1 * UNIQUE;522 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;523 pub const BountyDepositBase: Balance = 1 * UNIQUE;524 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;525 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");526 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;527 pub const MaximumReasonLength: u32 = 16384;528 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);529 pub const BountyValueMinimum: Balance = 5 * UNIQUE;530 pub const MaxApprovals: u32 = 100;531}532533impl pallet_treasury::Config for Runtime {534 type PalletId = TreasuryModuleId;535 type Currency = Balances;536 type ApproveOrigin = EnsureRoot<AccountId>;537 type RejectOrigin = EnsureRoot<AccountId>;538 type Event = Event;539 type OnSlash = ();540 type ProposalBond = ProposalBond;541 type ProposalBondMinimum = ProposalBondMinimum;542 type ProposalBondMaximum = ProposalBondMaximum;543 type SpendPeriod = SpendPeriod;544 type Burn = Burn;545 type BurnDestination = ();546 type SpendFunds = ();547 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;548 type MaxApprovals = MaxApprovals;549}550551impl pallet_sudo::Config for Runtime {552 type Event = Event;553 type Call = Call;554}555556pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);557558impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider559 for RelayChainBlockNumberProvider<T>560{561 type BlockNumber = BlockNumber;562563 fn current_block_number() -> Self::BlockNumber {564 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()565 .map(|d| d.relay_parent_number)566 .unwrap_or_default()567 }568}569570parameter_types! {571 pub const MinVestedTransfer: Balance = 10 * UNIQUE;572 pub const MaxVestingSchedules: u32 = 28;573}574575impl orml_vesting::Config for Runtime {576 type Event = Event;577 type Currency = pallet_balances::Pallet<Runtime>;578 type MinVestedTransfer = MinVestedTransfer;579 type VestedTransferOrigin = EnsureSigned<AccountId>;580 type WeightInfo = ();581 type MaxVestingSchedules = MaxVestingSchedules;582 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;583}584585parameter_types! {586 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;587 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;588}589590impl cumulus_pallet_parachain_system::Config for Runtime {591 type Event = Event;592 type SelfParaId = parachain_info::Pallet<Self>;593 type OnSystemEvent = ();594 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<595 // MaxDownwardMessageWeight,596 // XcmExecutor<XcmConfig>,597 // Call,598 // >;599 type OutboundXcmpMessageSource = XcmpQueue;600 type DmpMessageHandler = DmpQueue;601 type ReservedDmpWeight = ReservedDmpWeight;602 type ReservedXcmpWeight = ReservedXcmpWeight;603 type XcmpMessageHandler = XcmpQueue;604}605606impl parachain_info::Config for Runtime {}607608impl cumulus_pallet_aura_ext::Config for Runtime {}609610parameter_types! {611 pub const RelayLocation: MultiLocation = MultiLocation::parent();612 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;613 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();614 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();615}616617/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used618/// when determining ownership of accounts for asset transacting and when attempting to use XCM619/// `Transact` in order to determine the dispatch Origin.620pub type LocationToAccountId = (621 // The parent (Relay-chain) origin converts to the default `AccountId`.622 ParentIsPreset<AccountId>,623 // Sibling parachain origins convert to AccountId via the `ParaId::into`.624 SiblingParachainConvertsVia<Sibling, AccountId>,625 // Straight up local `AccountId32` origins just alias directly to `AccountId`.626 AccountId32Aliases<RelayNetwork, AccountId>,627);628629pub struct OnlySelfCurrency;630impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {631 fn matches_fungible(a: &MultiAsset) -> Option<B> {632 match (&a.id, &a.fun) {633 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),634 _ => None,635 }636 }637}638639/// Means for transacting assets on this chain.640pub type LocalAssetTransactor = CurrencyAdapter<641 // Use this currency:642 Balances,643 // Use this currency when it is a fungible asset matching the given location or name:644 OnlySelfCurrency,645 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:646 LocationToAccountId,647 // Our chain's account ID type (we can't get away without mentioning it explicitly):648 AccountId,649 // We don't track any teleports.650 (),651>;652653/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,654/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can655/// biases the kind of local `Origin` it will become.656pub type XcmOriginToTransactDispatchOrigin = (657 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location658 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for659 // foreign chains who want to have a local sovereign account on this chain which they control.660 SovereignSignedViaLocation<LocationToAccountId, Origin>,661 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when662 // recognised.663 RelayChainAsNative<RelayOrigin, Origin>,664 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when665 // recognised.666 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,667 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a668 // transaction from the Root origin.669 ParentAsSuperuser<Origin>,670 // Native signed account converter; this just converts an `AccountId32` origin into a normal671 // `Origin::Signed` origin of the same 32-byte value.672 SignedAccountId32AsNative<RelayNetwork, Origin>,673 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.674 XcmPassthrough<Origin>,675);676677parameter_types! {678 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.679 pub UnitWeightCost: Weight = 1_000_000;680 // 1200 UNIQUEs buy 1 second of weight.681 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);682 pub const MaxInstructions: u32 = 100;683 pub const MaxAuthorities: u32 = 100_000;684}685686match_types! {687 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {688 MultiLocation { parents: 1, interior: Here } |689 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }690 };691}692693pub type Barrier = (694 TakeWeightCredit,695 AllowTopLevelPaidExecutionFrom<Everything>,696 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,697 // ^^^ Parent & its unit plurality gets free execution698);699700pub struct UsingOnlySelfCurrencyComponents<701 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,702 AssetId: Get<MultiLocation>,703 AccountId,704 Currency: CurrencyT<AccountId>,705 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,706>(707 Weight,708 Currency::Balance,709 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,710);711impl<712 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,713 AssetId: Get<MultiLocation>,714 AccountId,715 Currency: CurrencyT<AccountId>,716 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,717 > WeightTrader718 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>719{720 fn new() -> Self {721 Self(0, Zero::zero(), PhantomData)722 }723724 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {725 let amount = WeightToFee::calc(&weight);726 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;727728 // location to this parachain through relay chain729 let option1: xcm::v1::AssetId = Concrete(MultiLocation {730 parents: 1,731 interior: X1(Parachain(ParachainInfo::parachain_id().into())),732 });733 // direct location734 let option2: xcm::v1::AssetId = Concrete(MultiLocation {735 parents: 0,736 interior: Here,737 });738739 let required = if payment.fungible.contains_key(&option1) {740 (option1, u128_amount).into()741 } else if payment.fungible.contains_key(&option2) {742 (option2, u128_amount).into()743 } else {744 (Concrete(MultiLocation::default()), u128_amount).into()745 };746747 let unused = payment748 .checked_sub(required)749 .map_err(|_| XcmError::TooExpensive)?;750 self.0 = self.0.saturating_add(weight);751 self.1 = self.1.saturating_add(amount);752 Ok(unused)753 }754755 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {756 let weight = weight.min(self.0);757 let amount = WeightToFee::calc(&weight);758 self.0 -= weight;759 self.1 = self.1.saturating_sub(amount);760 let amount: u128 = amount.saturated_into();761 if amount > 0 {762 Some((AssetId::get(), amount).into())763 } else {764 None765 }766 }767}768impl<769 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,770 AssetId: Get<MultiLocation>,771 AccountId,772 Currency: CurrencyT<AccountId>,773 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,774 > Drop775 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>776{777 fn drop(&mut self) {778 OnUnbalanced::on_unbalanced(Currency::issue(self.1));779 }780}781782pub struct XcmConfig;783impl Config for XcmConfig {784 type Call = Call;785 type XcmSender = XcmRouter;786 // How to withdraw and deposit an asset.787 type AssetTransactor = LocalAssetTransactor;788 type OriginConverter = XcmOriginToTransactDispatchOrigin;789 type IsReserve = NativeAsset;790 type IsTeleporter = (); // Teleportation is disabled791 type LocationInverter = LocationInverter<Ancestry>;792 type Barrier = Barrier;793 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;794 type Trader = UsingOnlySelfCurrencyComponents<795 IdentityFee<Balance>,796 RelayLocation,797 AccountId,798 Balances,799 (),800 >;801 type ResponseHandler = (); // Don't handle responses for now.802 type SubscriptionService = PolkadotXcm;803804 type AssetTrap = PolkadotXcm;805 type AssetClaims = PolkadotXcm;806}807808// parameter_types! {809// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;810// }811812/// No local origins on this chain are allowed to dispatch XCM sends/executions.813pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);814815/// The means for routing XCM messages which are not for local execution into the right message816/// queues.817pub type XcmRouter = (818 // Two routers - use UMP to communicate with the relay chain:819 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,820 // ..and XCMP to communicate with the sibling chains.821 XcmpQueue,822);823824impl pallet_evm_coder_substrate::Config for Runtime {825 type GasWeightMapping = FixedGasWeightMapping;826}827828impl pallet_xcm::Config for Runtime {829 type Event = Event;830 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;831 type XcmRouter = XcmRouter;832 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;833 type XcmExecuteFilter = Everything;834 type XcmExecutor = XcmExecutor<XcmConfig>;835 type XcmTeleportFilter = Everything;836 type XcmReserveTransferFilter = Everything;837 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;838 type LocationInverter = LocationInverter<Ancestry>;839 type Origin = Origin;840 type Call = Call;841 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;842 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;843}844845impl cumulus_pallet_xcm::Config for Runtime {846 type Event = Event;847 type XcmExecutor = XcmExecutor<XcmConfig>;848}849850impl cumulus_pallet_xcmp_queue::Config for Runtime {851 type WeightInfo = ();852 type Event = Event;853 type XcmExecutor = XcmExecutor<XcmConfig>;854 type ChannelInfo = ParachainSystem;855 type VersionWrapper = ();856 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;857 type ControllerOrigin = EnsureRoot<AccountId>;858 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;859}860861impl cumulus_pallet_dmp_queue::Config for Runtime {862 type Event = Event;863 type XcmExecutor = XcmExecutor<XcmConfig>;864 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;865}866867impl pallet_aura::Config for Runtime {868 type AuthorityId = AuraId;869 type DisabledValidators = ();870 type MaxAuthorities = MaxAuthorities;871}872873parameter_types! {874 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();875 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;876}877878impl pallet_common::Config for Runtime {879 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;880 type Event = Event;881 type Currency = Balances;882 type CollectionCreationPrice = CollectionCreationPrice;883 type TreasuryAccountId = TreasuryAccountId;884 type CollectionDispatch = CollectionDispatchT<Self>;885886 type EvmTokenAddressMapping = EvmTokenAddressMapping;887 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;888}889890impl pallet_structure::Config for Runtime {891 type Event = Event;892 type Call = Call;893 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;894}895896impl pallet_fungible::Config for Runtime {897 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;898}899impl pallet_refungible::Config for Runtime {900 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;901}902impl pallet_nonfungible::Config for Runtime {903 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;904}905906/*907TODO free RMRK!908impl pallet_proxy_rmrk_core::Config for Runtime {909 type Event = Event;910}911912impl pallet_proxy_rmrk_equip::Config for Runtime {913 type Event = Event;914}*/915916impl pallet_unique::Config for Runtime {917 type Event = Event;918 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;919 type CommonWeightInfo = CommonWeights<Self>;920 type ContractAddress = EvmCollectionHelperAddress;921}922923parameter_types! {924 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied925}926927/// Used for the pallet inflation928impl pallet_inflation::Config for Runtime {929 type Currency = Balances;930 type TreasuryAccountId = TreasuryAccountId;931 type InflationBlockInterval = InflationBlockInterval;932 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;933}934935// parameter_types! {936// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *937// RuntimeBlockWeights::get().max_block;938// pub const MaxScheduledPerBlock: u32 = 50;939// }940941type EvmSponsorshipHandler = (942 UniqueEthSponsorshipHandler<Runtime>,943 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,944);945type SponsorshipHandler = (946 UniqueSponsorshipHandler<Runtime>,947 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,948 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,949);950951// impl pallet_unq_scheduler::Config for Runtime {952// type Event = Event;953// type Origin = Origin;954// type PalletsOrigin = OriginCaller;955// type Call = Call;956// type MaximumWeight = MaximumSchedulerWeight;957// type ScheduleOrigin = EnsureSigned<AccountId>;958// type MaxScheduledPerBlock = MaxScheduledPerBlock;959// type SponsorshipHandler = SponsorshipHandler;960// type WeightInfo = ();961// }962963impl pallet_evm_transaction_payment::Config for Runtime {964 type EvmSponsorshipHandler = EvmSponsorshipHandler;965 type Currency = Balances;966}967968impl pallet_charge_transaction::Config for Runtime {969 type SponsorshipHandler = SponsorshipHandler;970}971972// impl pallet_contract_helpers::Config for Runtime {973// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;974// }975976parameter_types! {977 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049978 pub const HelpersContractAddress: H160 = H160([979 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,980 ]);981982 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f983 pub const EvmCollectionHelperAddress: H160 = H160([984 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,985 ]);986}987988impl pallet_evm_contract_helpers::Config for Runtime {989 type ContractAddress = HelpersContractAddress;990 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;991}992993construct_runtime!(994 pub enum Runtime where995 Block = Block,996 NodeBlock = opaque::Block,997 UncheckedExtrinsic = UncheckedExtrinsic998 {999 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1000 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,10011002 Aura: pallet_aura::{Pallet, Config<T>} = 22,1003 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10041005 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1006 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1007 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1008 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1009 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1010 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1011 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1012 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1013 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1014 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10151016 // XCM helpers.1017 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1018 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1019 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1020 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10211022 // Unique Pallets1023 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1024 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1025 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1026 // free = 631027 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1028 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1029 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1030 Fungible: pallet_fungible::{Pallet, Storage} = 67,1031 Refungible: pallet_refungible::{Pallet, Storage} = 68,1032 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1033 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1034 /* TODO free RMRK!1035 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1036 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,1037 */10381039 // Frontier1040 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1041 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10421043 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1044 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1045 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1046 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1047 }1048);10491050pub struct TransactionConverter;10511052impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1053 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1054 UncheckedExtrinsic::new_unsigned(1055 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1056 )1057 }1058}10591060impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1061 fn convert_transaction(1062 &self,1063 transaction: pallet_ethereum::Transaction,1064 ) -> opaque::UncheckedExtrinsic {1065 let extrinsic = UncheckedExtrinsic::new_unsigned(1066 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1067 );1068 let encoded = extrinsic.encode();1069 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1070 .expect("Encoded extrinsic is always valid")1071 }1072}10731074/// The address format for describing accounts.1075pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1076/// Block header type as expected by this runtime.1077pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1078/// Block type as expected by this runtime.1079pub type Block = generic::Block<Header, UncheckedExtrinsic>;1080/// A Block signed with a Justification1081pub type SignedBlock = generic::SignedBlock<Block>;1082/// BlockId type as expected by this runtime.1083pub type BlockId = generic::BlockId<Block>;1084/// The SignedExtension to the basic transaction logic.1085pub type SignedExtra = (1086 frame_system::CheckSpecVersion<Runtime>,1087 // system::CheckTxVersion<Runtime>,1088 frame_system::CheckGenesis<Runtime>,1089 frame_system::CheckEra<Runtime>,1090 frame_system::CheckNonce<Runtime>,1091 frame_system::CheckWeight<Runtime>,1092 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1093 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1094 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1095);1096/// Unchecked extrinsic type as expected by this runtime.1097pub type UncheckedExtrinsic =1098 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1099/// Extrinsic type that has already been checked.1100pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1101/// Executive: handles dispatch to the various modules.1102pub type Executive = frame_executive::Executive<1103 Runtime,1104 Block,1105 frame_system::ChainContext<Runtime>,1106 Runtime,1107 AllPalletsReversedWithSystemFirst,1108>;11091110impl_opaque_keys! {1111 pub struct SessionKeys {1112 pub aura: Aura,1113 }1114}11151116impl fp_self_contained::SelfContainedCall for Call {1117 type SignedInfo = H160;11181119 fn is_self_contained(&self) -> bool {1120 match self {1121 Call::Ethereum(call) => call.is_self_contained(),1122 _ => false,1123 }1124 }11251126 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1127 match self {1128 Call::Ethereum(call) => call.check_self_contained(),1129 _ => None,1130 }1131 }11321133 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1134 match self {1135 Call::Ethereum(call) => call.validate_self_contained(info),1136 _ => None,1137 }1138 }11391140 fn pre_dispatch_self_contained(1141 &self,1142 info: &Self::SignedInfo,1143 ) -> Option<Result<(), TransactionValidityError>> {1144 match self {1145 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1146 _ => None,1147 }1148 }11491150 fn apply_self_contained(1151 self,1152 info: Self::SignedInfo,1153 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1154 match self {1155 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1156 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1157 )),1158 _ => None,1159 }1160 }1161}11621163macro_rules! dispatch_unique_runtime {1164 ($collection:ident.$method:ident($($name:ident),*)) => {{1165 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1166 let dispatch = collection.as_dyn();11671168 Ok::<_, DispatchError>(dispatch.$method($($name),*))1169 }};1170}11711172impl_common_runtime_apis!();11731174struct CheckInherents;11751176impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1177 fn check_inherents(1178 block: &Block,1179 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1180 ) -> sp_inherents::CheckInherentsResult {1181 let relay_chain_slot = relay_state_proof1182 .read_slot()1183 .expect("Could not read the relay chain slot from the proof");11841185 let inherent_data =1186 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1187 relay_chain_slot,1188 sp_std::time::Duration::from_secs(6),1189 )1190 .create_inherent_data()1191 .expect("Could not create the timestamp inherent data");11921193 inherent_data.check_extrinsics(block)1194 }1195}11961197cumulus_pallet_parachain_system::register_validate_block!(1198 Runtime = Runtime,1199 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1200 CheckInherents = CheckInherents,1201);runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -900,6 +900,7 @@
type Event = Event;
type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;
type CommonWeightInfo = CommonWeights<Self>;
+ type ContractAddress = EvmCollectionHelperAddress;
}
parameter_types! {
@@ -970,10 +971,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/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!(