difftreelog
Fix unique ss58prefix, remove unneeded comments
in: master
1 file changed
runtime/unique/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::{EnsureAddressTruncated, HashedAddressMapping, Runner};52pub use frame_support::{53 construct_runtime, match_type,54 dispatch::DispatchResult,55 PalletId, parameter_types, StorageValue, ConsensusEngineId,56 traits::{57 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,58 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,59 OnUnbalanced, Randomness, FindAuthor,60 },61 weights::{62 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},63 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,64 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,65 },66};67use up_data_structs::*;68// use pallet_contracts::weights::WeightInfo;69// #[cfg(any(feature = "std", test))]70use frame_system::{71 self as frame_system, EnsureRoot, EnsureSigned,72 limits::{BlockWeights, BlockLength},73};74use sp_arithmetic::{75 traits::{BaseArithmetic, Unsigned},76};77use smallvec::smallvec;78use codec::{Encode, Decode};79use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};80use fp_rpc::TransactionStatus;81use sp_runtime::{82 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},83 transaction_validity::TransactionValidityError,84 SaturatedConversion,85};8687// pub use pallet_timestamp::Call as TimestampCall;88pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8990// Polkadot imports91use pallet_xcm::XcmPassthrough;92use polkadot_parachain::primitives::Sibling;93use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};94use xcm_builder::{95 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,96 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,97 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,98 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,99 ParentIsPreset,100};101use xcm_executor::{Config, XcmExecutor, Assets};102use sp_std::{marker::PhantomData};103104use xcm::latest::{105 // Xcm,106 AssetId::{Concrete},107 Fungibility::Fungible as XcmFungible,108 MultiAsset,109 Error as XcmError,110};111use xcm_executor::traits::{MatchesFungible, WeightTrader};112//use xcm_executor::traits::MatchesFungible;113use sp_runtime::traits::CheckedConversion;114115use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};116117pub const RUNTIME_NAME: &str = "Unique";118119pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;120121/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know122/// the specifics of the runtime. They can then be made to be agnostic over specific formats123/// of data like extrinsics, allowing for them to continue syncing the network through upgrades124/// to even the core data structures.125pub mod opaque {126 use sp_std::prelude::*;127 use sp_runtime::impl_opaque_keys;128 use super::Aura;129130 pub use unique_runtime_common::types::*;131 pub use super::CrossAccountId;132133 impl_opaque_keys! {134 pub struct SessionKeys {135 pub aura: Aura,136 }137 }138}139140/// This runtime version.141pub const VERSION: RuntimeVersion = RuntimeVersion {142 spec_name: create_runtime_str!(RUNTIME_NAME),143 impl_name: create_runtime_str!(RUNTIME_NAME),144 authoring_version: 1,145 spec_version: 917004,146 impl_version: 0,147 apis: RUNTIME_API_VERSIONS,148 transaction_version: 1,149 state_version: 0,150};151152#[derive(codec::Encode, codec::Decode)]153pub enum XCMPMessage<XAccountId, XBalance> {154 /// Transfer tokens to the given account from the Parachain account.155 TransferToken(XAccountId, XBalance),156}157158/// The version information used to identify this runtime when compiled natively.159#[cfg(feature = "std")]160pub fn native_version() -> NativeVersion {161 NativeVersion {162 runtime_version: VERSION,163 can_author_with: Default::default(),164 }165}166167type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;168169pub struct DealWithFees;170impl OnUnbalanced<NegativeImbalance> for DealWithFees {171 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {172 if let Some(fees) = fees_then_tips.next() {173 // for fees, 100% to treasury174 let mut split = fees.ration(100, 0);175 if let Some(tips) = fees_then_tips.next() {176 // for tips, if any, 100% to treasury177 tips.ration_merge_into(100, 0, &mut split);178 }179 Treasury::on_unbalanced(split.0);180 // Author::on_unbalanced(split.1);181 }182 }183}184185parameter_types! {186 pub const BlockHashCount: BlockNumber = 2400;187 pub RuntimeBlockLength: BlockLength =188 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);189 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);190 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;191 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()192 .base_block(BlockExecutionWeight::get())193 .for_class(DispatchClass::all(), |weights| {194 weights.base_extrinsic = ExtrinsicBaseWeight::get();195 })196 .for_class(DispatchClass::Normal, |weights| {197 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);198 })199 .for_class(DispatchClass::Operational, |weights| {200 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);201 // Operational transactions have some extra reserved space, so that they202 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.203 weights.reserved = Some(204 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT205 );206 })207 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)208 .build_or_panic();209 pub const Version: RuntimeVersion = VERSION;210 /*211 FIXME - Unique212 255 - Quartz213 42 - Opal214 */215 pub const SS58Prefix: u8 = 255; // FIXME set valid valud for the Unique runtime216}217218/*2198880 - Unique2208881 - Quartz2218882 - Opal222*/223parameter_types! {224 pub const ChainId: u64 = 8880;225}226227pub struct FixedFee;228impl FeeCalculator for FixedFee {229 fn min_gas_price() -> U256 {230 // Targeting 0.15 UNQ per transfer231 1_018_751_825_264u64.into()232 }233}234235// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case236// (contract, which only writes a lot of data),237// approximating on top of our real store write weight238parameter_types! {239 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;240 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;241 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();242}243244/// Limiting EVM execution to 50% of block for substrate users and management tasks245/// EVM transaction consumes more weight than substrate's, so we can't rely on them being246/// scheduled fairly247const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);248parameter_types! {249 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());250}251252pub enum FixedGasWeightMapping {}253impl GasWeightMapping for FixedGasWeightMapping {254 fn gas_to_weight(gas: u64) -> Weight {255 gas.saturating_mul(WeightPerGas::get())256 }257 fn weight_to_gas(weight: Weight) -> u64 {258 weight / WeightPerGas::get()259 }260}261262impl pallet_evm::Config for Runtime {263 type BlockGasLimit = BlockGasLimit;264 type FeeCalculator = FixedFee;265 type GasWeightMapping = FixedGasWeightMapping;266 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;267 type CallOrigin = EnsureAddressTruncated;268 type WithdrawOrigin = EnsureAddressTruncated;269 type AddressMapping = HashedAddressMapping<Self::Hashing>;270 type PrecompilesType = ();271 type PrecompilesValue = ();272 type Currency = Balances;273 type Event = Event;274 type OnMethodCall = (275 pallet_evm_migration::OnMethodCall<Self>,276 pallet_unique::UniqueErcSupport<Self>,277 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,278 );279 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;280 type ChainId = ChainId;281 type Runner = pallet_evm::runner::stack::Runner<Self>;282 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;283 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;284 type FindAuthor = EthereumFindAuthor<Aura>;285}286287impl pallet_evm_migration::Config for Runtime {288 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;289}290291pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);292impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {293 fn find_author<'a, I>(digests: I) -> Option<H160>294 where295 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,296 {297 if let Some(author_index) = F::find_author(digests) {298 let authority_id = Aura::authorities()[author_index as usize].clone();299 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));300 }301 None302 }303}304305impl pallet_ethereum::Config for Runtime {306 type Event = Event;307 type StateRoot = pallet_ethereum::IntermediateStateRoot;308}309310impl pallet_randomness_collective_flip::Config for Runtime {}311312impl frame_system::Config for Runtime {313 /// The data to be stored in an account.314 type AccountData = pallet_balances::AccountData<Balance>;315 /// The identifier used to distinguish between accounts.316 type AccountId = AccountId;317 /// The basic call filter to use in dispatchable.318 type BaseCallFilter = Everything;319 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).320 type BlockHashCount = BlockHashCount;321 /// The maximum length of a block (in bytes).322 type BlockLength = RuntimeBlockLength;323 /// The index type for blocks.324 type BlockNumber = BlockNumber;325 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.326 type BlockWeights = RuntimeBlockWeights;327 /// The aggregated dispatch type that is available for extrinsics.328 type Call = Call;329 /// The weight of database operations that the runtime can invoke.330 type DbWeight = RocksDbWeight;331 /// The ubiquitous event type.332 type Event = Event;333 /// The type for hashing blocks and tries.334 type Hash = Hash;335 /// The hashing algorithm used.336 type Hashing = BlakeTwo256;337 /// The header type.338 type Header = generic::Header<BlockNumber, BlakeTwo256>;339 /// The index type for storing how many extrinsics an account has signed.340 type Index = Index;341 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.342 type Lookup = AccountIdLookup<AccountId, ()>;343 /// What to do if an account is fully reaped from the system.344 type OnKilledAccount = ();345 /// What to do if a new account is created.346 type OnNewAccount = ();347 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;348 /// The ubiquitous origin type.349 type Origin = Origin;350 /// This type is being generated by `construct_runtime!`.351 type PalletInfo = PalletInfo;352 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.353 type SS58Prefix = SS58Prefix;354 /// Weight information for the extrinsics of this pallet.355 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;356 /// Version of the runtime.357 type Version = Version;358 type MaxConsumers = ConstU32<16>;359}360361parameter_types! {362 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;363}364365impl pallet_timestamp::Config for Runtime {366 /// A timestamp: milliseconds since the unix epoch.367 type Moment = u64;368 type OnTimestampSet = ();369 type MinimumPeriod = MinimumPeriod;370 type WeightInfo = ();371}372373parameter_types! {374 // pub const ExistentialDeposit: u128 = 500;375 pub const ExistentialDeposit: u128 = 0;376 pub const MaxLocks: u32 = 50;377}378379impl pallet_balances::Config for Runtime {380 type MaxLocks = MaxLocks;381 type MaxReserves = ();382 type ReserveIdentifier = [u8; 8];383 /// The type for recording an account's balance.384 type Balance = Balance;385 /// The ubiquitous event type.386 type Event = Event;387 type DustRemoval = Treasury;388 type ExistentialDeposit = ExistentialDeposit;389 type AccountStore = System;390 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;391}392393pub const MICROUNIQUE: Balance = 1_000_000_000_000;394pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;395pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;396pub const UNIQUE: Balance = 100 * CENTIUNIQUE;397398pub const fn deposit(items: u32, bytes: u32) -> Balance {399 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE400}401402/*403parameter_types! {404 pub TombstoneDeposit: Balance = deposit(405 1,406 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,407 );408 pub DepositPerContract: Balance = TombstoneDeposit::get();409 pub const DepositPerStorageByte: Balance = deposit(0, 1);410 pub const DepositPerStorageItem: Balance = deposit(1, 0);411 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);412 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;413 pub const SignedClaimHandicap: u32 = 2;414 pub const MaxDepth: u32 = 32;415 pub const MaxValueSize: u32 = 16 * 1024;416 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb417 // The lazy deletion runs inside on_initialize.418 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *419 RuntimeBlockWeights::get().max_block;420 // The weight needed for decoding the queue should be less or equal than a fifth421 // of the overall weight dedicated to the lazy deletion.422 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (423 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -424 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)425 )) / 5) as u32;426 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();427}428429impl pallet_contracts::Config for Runtime {430 type Time = Timestamp;431 type Randomness = RandomnessCollectiveFlip;432 type Currency = Balances;433 type Event = Event;434 type RentPayment = ();435 type SignedClaimHandicap = SignedClaimHandicap;436 type TombstoneDeposit = TombstoneDeposit;437 type DepositPerContract = DepositPerContract;438 type DepositPerStorageByte = DepositPerStorageByte;439 type DepositPerStorageItem = DepositPerStorageItem;440 type RentFraction = RentFraction;441 type SurchargeReward = SurchargeReward;442 type WeightPrice = pallet_transaction_payment::Pallet<Self>;443 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;444 type ChainExtension = NFTExtension;445 type DeletionQueueDepth = DeletionQueueDepth;446 type DeletionWeightLimit = DeletionWeightLimit;447 type Schedule = Schedule;448 type CallStack = [pallet_contracts::Frame<Self>; 31];449}450*/451452parameter_types! {453 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer454 /// This value increases the priority of `Operational` transactions by adding455 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.456 pub const OperationalFeeMultiplier: u8 = 5;457}458459/// Linear implementor of `WeightToFeePolynomial`460pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);461462impl<T> WeightToFeePolynomial for LinearFee<T>463where464 T: BaseArithmetic + From<u32> + Copy + Unsigned,465{466 type Balance = T;467468 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {469 smallvec!(WeightToFeeCoefficient {470 // Targeting 0.1 Unique per NFT transfer471 coeff_integer: 142_688_000u32.into(),472 coeff_frac: Perbill::zero(),473 negative: false,474 degree: 1,475 })476 }477}478479impl pallet_transaction_payment::Config for Runtime {480 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;481 type TransactionByteFee = TransactionByteFee;482 type OperationalFeeMultiplier = OperationalFeeMultiplier;483 type WeightToFee = LinearFee<Balance>;484 type FeeMultiplierUpdate = ();485}486487parameter_types! {488 pub const ProposalBond: Permill = Permill::from_percent(5);489 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;490 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;491 pub const SpendPeriod: BlockNumber = 5 * MINUTES;492 pub const Burn: Permill = Permill::from_percent(0);493 pub const TipCountdown: BlockNumber = 1 * DAYS;494 pub const TipFindersFee: Percent = Percent::from_percent(20);495 pub const TipReportDepositBase: Balance = 1 * UNIQUE;496 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;497 pub const BountyDepositBase: Balance = 1 * UNIQUE;498 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;499 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");500 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;501 pub const MaximumReasonLength: u32 = 16384;502 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);503 pub const BountyValueMinimum: Balance = 5 * UNIQUE;504 pub const MaxApprovals: u32 = 100;505}506507impl pallet_treasury::Config for Runtime {508 type PalletId = TreasuryModuleId;509 type Currency = Balances;510 type ApproveOrigin = EnsureRoot<AccountId>;511 type RejectOrigin = EnsureRoot<AccountId>;512 type Event = Event;513 type OnSlash = ();514 type ProposalBond = ProposalBond;515 type ProposalBondMinimum = ProposalBondMinimum;516 type ProposalBondMaximum = ProposalBondMaximum;517 type SpendPeriod = SpendPeriod;518 type Burn = Burn;519 type BurnDestination = ();520 type SpendFunds = ();521 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;522 type MaxApprovals = MaxApprovals;523}524525impl pallet_sudo::Config for Runtime {526 type Event = Event;527 type Call = Call;528}529530pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);531532impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider533 for RelayChainBlockNumberProvider<T>534{535 type BlockNumber = BlockNumber;536537 fn current_block_number() -> Self::BlockNumber {538 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()539 .map(|d| d.relay_parent_number)540 .unwrap_or_default()541 }542}543544parameter_types! {545 pub const MinVestedTransfer: Balance = 10 * UNIQUE;546 pub const MaxVestingSchedules: u32 = 28;547}548549impl orml_vesting::Config for Runtime {550 type Event = Event;551 type Currency = pallet_balances::Pallet<Runtime>;552 type MinVestedTransfer = MinVestedTransfer;553 type VestedTransferOrigin = EnsureSigned<AccountId>;554 type WeightInfo = ();555 type MaxVestingSchedules = MaxVestingSchedules;556 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;557}558559parameter_types! {560 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;561 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;562}563564impl cumulus_pallet_parachain_system::Config for Runtime {565 type Event = Event;566 type SelfParaId = parachain_info::Pallet<Self>;567 type OnSystemEvent = ();568 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<569 // MaxDownwardMessageWeight,570 // XcmExecutor<XcmConfig>,571 // Call,572 // >;573 type OutboundXcmpMessageSource = XcmpQueue;574 type DmpMessageHandler = DmpQueue;575 type ReservedDmpWeight = ReservedDmpWeight;576 type ReservedXcmpWeight = ReservedXcmpWeight;577 type XcmpMessageHandler = XcmpQueue;578}579580impl parachain_info::Config for Runtime {}581582impl cumulus_pallet_aura_ext::Config for Runtime {}583584parameter_types! {585 pub const RelayLocation: MultiLocation = MultiLocation::parent();586 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;587 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();588 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();589}590591/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used592/// when determining ownership of accounts for asset transacting and when attempting to use XCM593/// `Transact` in order to determine the dispatch Origin.594pub type LocationToAccountId = (595 // The parent (Relay-chain) origin converts to the default `AccountId`.596 ParentIsPreset<AccountId>,597 // Sibling parachain origins convert to AccountId via the `ParaId::into`.598 SiblingParachainConvertsVia<Sibling, AccountId>,599 // Straight up local `AccountId32` origins just alias directly to `AccountId`.600 AccountId32Aliases<RelayNetwork, AccountId>,601);602603pub struct OnlySelfCurrency;604impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {605 fn matches_fungible(a: &MultiAsset) -> Option<B> {606 match (&a.id, &a.fun) {607 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),608 _ => None,609 }610 }611}612613/// Means for transacting assets on this chain.614pub type LocalAssetTransactor = CurrencyAdapter<615 // Use this currency:616 Balances,617 // Use this currency when it is a fungible asset matching the given location or name:618 OnlySelfCurrency,619 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:620 LocationToAccountId,621 // Our chain's account ID type (we can't get away without mentioning it explicitly):622 AccountId,623 // We don't track any teleports.624 (),625>;626627/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,628/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can629/// biases the kind of local `Origin` it will become.630pub type XcmOriginToTransactDispatchOrigin = (631 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location632 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for633 // foreign chains who want to have a local sovereign account on this chain which they control.634 SovereignSignedViaLocation<LocationToAccountId, Origin>,635 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when636 // recognised.637 RelayChainAsNative<RelayOrigin, Origin>,638 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when639 // recognised.640 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,641 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a642 // transaction from the Root origin.643 ParentAsSuperuser<Origin>,644 // Native signed account converter; this just converts an `AccountId32` origin into a normal645 // `Origin::Signed` origin of the same 32-byte value.646 SignedAccountId32AsNative<RelayNetwork, Origin>,647 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.648 XcmPassthrough<Origin>,649);650651parameter_types! {652 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.653 pub UnitWeightCost: Weight = 1_000_000;654 // 1200 UNIQUEs buy 1 second of weight.655 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);656 pub const MaxInstructions: u32 = 100;657 pub const MaxAuthorities: u32 = 100_000;658}659660match_type! {661 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {662 MultiLocation { parents: 1, interior: Here } |663 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }664 };665}666667pub type Barrier = (668 TakeWeightCredit,669 AllowTopLevelPaidExecutionFrom<Everything>,670 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,671 // ^^^ Parent & its unit plurality gets free execution672);673674pub struct UsingOnlySelfCurrencyComponents<675 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,676 AssetId: Get<MultiLocation>,677 AccountId,678 Currency: CurrencyT<AccountId>,679 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,680>(681 Weight,682 Currency::Balance,683 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,684);685impl<686 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,687 AssetId: Get<MultiLocation>,688 AccountId,689 Currency: CurrencyT<AccountId>,690 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,691 > WeightTrader692 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>693{694 fn new() -> Self {695 Self(0, Zero::zero(), PhantomData)696 }697698 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {699 let amount = WeightToFee::calc(&weight);700 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;701702 // location to this parachain through relay chain703 let option1: xcm::v1::AssetId = Concrete(MultiLocation {704 parents: 1,705 interior: X1(Parachain(ParachainInfo::parachain_id().into())),706 });707 // direct location708 let option2: xcm::v1::AssetId = Concrete(MultiLocation {709 parents: 0,710 interior: Here,711 });712713 let required = if payment.fungible.contains_key(&option1) {714 (option1, u128_amount).into()715 } else if payment.fungible.contains_key(&option2) {716 (option2, u128_amount).into()717 } else {718 (Concrete(MultiLocation::default()), u128_amount).into()719 };720721 let unused = payment722 .checked_sub(required)723 .map_err(|_| XcmError::TooExpensive)?;724 self.0 = self.0.saturating_add(weight);725 self.1 = self.1.saturating_add(amount);726 Ok(unused)727 }728729 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {730 let weight = weight.min(self.0);731 let amount = WeightToFee::calc(&weight);732 self.0 -= weight;733 self.1 = self.1.saturating_sub(amount);734 let amount: u128 = amount.saturated_into();735 if amount > 0 {736 Some((AssetId::get(), amount).into())737 } else {738 None739 }740 }741}742impl<743 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,744 AssetId: Get<MultiLocation>,745 AccountId,746 Currency: CurrencyT<AccountId>,747 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,748 > Drop749 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>750{751 fn drop(&mut self) {752 OnUnbalanced::on_unbalanced(Currency::issue(self.1));753 }754}755756pub struct XcmConfig;757impl Config for XcmConfig {758 type Call = Call;759 type XcmSender = XcmRouter;760 // How to withdraw and deposit an asset.761 type AssetTransactor = LocalAssetTransactor;762 type OriginConverter = XcmOriginToTransactDispatchOrigin;763 type IsReserve = NativeAsset;764 type IsTeleporter = (); // Teleportation is disabled765 type LocationInverter = LocationInverter<Ancestry>;766 type Barrier = Barrier;767 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;768 type Trader = UsingOnlySelfCurrencyComponents<769 IdentityFee<Balance>,770 RelayLocation,771 AccountId,772 Balances,773 (),774 >;775 type ResponseHandler = (); // Don't handle responses for now.776 type SubscriptionService = PolkadotXcm;777778 type AssetTrap = PolkadotXcm;779 type AssetClaims = PolkadotXcm;780}781782// parameter_types! {783// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;784// }785786/// No local origins on this chain are allowed to dispatch XCM sends/executions.787pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);788789/// The means for routing XCM messages which are not for local execution into the right message790/// queues.791pub type XcmRouter = (792 // Two routers - use UMP to communicate with the relay chain:793 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,794 // ..and XCMP to communicate with the sibling chains.795 XcmpQueue,796);797798impl pallet_evm_coder_substrate::Config for Runtime {799 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;800 type GasWeightMapping = FixedGasWeightMapping;801}802803impl pallet_xcm::Config for Runtime {804 type Event = Event;805 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;806 type XcmRouter = XcmRouter;807 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;808 type XcmExecuteFilter = Everything;809 type XcmExecutor = XcmExecutor<XcmConfig>;810 type XcmTeleportFilter = Everything;811 type XcmReserveTransferFilter = Everything;812 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;813 type LocationInverter = LocationInverter<Ancestry>;814 type Origin = Origin;815 type Call = Call;816 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;817 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;818}819820impl cumulus_pallet_xcm::Config for Runtime {821 type Event = Event;822 type XcmExecutor = XcmExecutor<XcmConfig>;823}824825impl cumulus_pallet_xcmp_queue::Config for Runtime {826 type Event = Event;827 type XcmExecutor = XcmExecutor<XcmConfig>;828 type ChannelInfo = ParachainSystem;829 type VersionWrapper = ();830 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;831 type ControllerOrigin = EnsureRoot<AccountId>;832 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;833}834835impl cumulus_pallet_dmp_queue::Config for Runtime {836 type Event = Event;837 type XcmExecutor = XcmExecutor<XcmConfig>;838 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;839}840841impl pallet_aura::Config for Runtime {842 type AuthorityId = AuraId;843 type DisabledValidators = ();844 type MaxAuthorities = MaxAuthorities;845}846847parameter_types! {848 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();849 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;850}851852impl pallet_common::Config for Runtime {853 type Event = Event;854 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;855 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;856 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;857858 type Currency = Balances;859 type CollectionCreationPrice = CollectionCreationPrice;860 type TreasuryAccountId = TreasuryAccountId;861}862863impl pallet_fungible::Config for Runtime {864 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;865}866impl pallet_refungible::Config for Runtime {867 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;868}869impl pallet_nonfungible::Config for Runtime {870 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;871}872873impl pallet_unique::Config for Runtime {874 type Event = Event;875 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;876}877878parameter_types! {879 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied880}881882/// Used for the pallet inflation883impl pallet_inflation::Config for Runtime {884 type Currency = Balances;885 type TreasuryAccountId = TreasuryAccountId;886 type InflationBlockInterval = InflationBlockInterval;887 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;888}889890// parameter_types! {891// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *892// RuntimeBlockWeights::get().max_block;893// pub const MaxScheduledPerBlock: u32 = 50;894// }895896type EvmSponsorshipHandler = (897 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,898 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,899);900type SponsorshipHandler = (901 pallet_unique::UniqueSponsorshipHandler<Runtime>,902 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,903 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,904);905906// impl pallet_unq_scheduler::Config for Runtime {907// type Event = Event;908// type Origin = Origin;909// type PalletsOrigin = OriginCaller;910// type Call = Call;911// type MaximumWeight = MaximumSchedulerWeight;912// type ScheduleOrigin = EnsureSigned<AccountId>;913// type MaxScheduledPerBlock = MaxScheduledPerBlock;914// type SponsorshipHandler = SponsorshipHandler;915// type WeightInfo = ();916// }917918impl pallet_evm_transaction_payment::Config for Runtime {919 type EvmSponsorshipHandler = EvmSponsorshipHandler;920 type Currency = Balances;921 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;922 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;923}924925impl pallet_charge_transaction::Config for Runtime {926 type SponsorshipHandler = SponsorshipHandler;927}928929// impl pallet_contract_helpers::Config for Runtime {930// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;931// }932933parameter_types! {934 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049935 pub const HelpersContractAddress: H160 = H160([936 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,937 ]);938}939940impl pallet_evm_contract_helpers::Config for Runtime {941 type ContractAddress = HelpersContractAddress;942 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;943}944945construct_runtime!(946 pub enum Runtime where947 Block = Block,948 NodeBlock = opaque::Block,949 UncheckedExtrinsic = UncheckedExtrinsic950 {951 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,952 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,953954 Aura: pallet_aura::{Pallet, Config<T>} = 22,955 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,956957 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,958 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,959 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,960 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,961 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,962 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,963 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,964 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,965 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,966 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,967968 // XCM helpers.969 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,970 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,971 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,972 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,973974 // Unique Pallets975 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,976 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,977 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,978 // free = 63979 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,980 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,981 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,982 Fungible: pallet_fungible::{Pallet, Storage} = 67,983 Refungible: pallet_refungible::{Pallet, Storage} = 68,984 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,985986 // Frontier987 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,988 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,989990 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,991 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,992 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,993 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,994 }995);996997pub struct TransactionConverter;998999impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1000 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1001 UncheckedExtrinsic::new_unsigned(1002 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1003 )1004 }1005}10061007impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1008 fn convert_transaction(1009 &self,1010 transaction: pallet_ethereum::Transaction,1011 ) -> opaque::UncheckedExtrinsic {1012 let extrinsic = UncheckedExtrinsic::new_unsigned(1013 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1014 );1015 let encoded = extrinsic.encode();1016 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1017 .expect("Encoded extrinsic is always valid")1018 }1019}10201021/// The address format for describing accounts.1022pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1023/// Block header type as expected by this runtime.1024pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1025/// Block type as expected by this runtime.1026pub type Block = generic::Block<Header, UncheckedExtrinsic>;1027/// A Block signed with a Justification1028pub type SignedBlock = generic::SignedBlock<Block>;1029/// BlockId type as expected by this runtime.1030pub type BlockId = generic::BlockId<Block>;1031/// The SignedExtension to the basic transaction logic.1032pub type SignedExtra = (1033 frame_system::CheckSpecVersion<Runtime>,1034 // system::CheckTxVersion<Runtime>,1035 frame_system::CheckGenesis<Runtime>,1036 frame_system::CheckEra<Runtime>,1037 frame_system::CheckNonce<Runtime>,1038 frame_system::CheckWeight<Runtime>,1039 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1040 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1041);1042/// Unchecked extrinsic type as expected by this runtime.1043pub type UncheckedExtrinsic =1044 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1045/// Extrinsic type that has already been checked.1046pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1047/// Executive: handles dispatch to the various modules.1048pub type Executive = frame_executive::Executive<1049 Runtime,1050 Block,1051 frame_system::ChainContext<Runtime>,1052 Runtime,1053 AllPalletsReversedWithSystemFirst,1054>;10551056impl_opaque_keys! {1057 pub struct SessionKeys {1058 pub aura: Aura,1059 }1060}10611062impl fp_self_contained::SelfContainedCall for Call {1063 type SignedInfo = H160;10641065 fn is_self_contained(&self) -> bool {1066 match self {1067 Call::Ethereum(call) => call.is_self_contained(),1068 _ => false,1069 }1070 }10711072 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1073 match self {1074 Call::Ethereum(call) => call.check_self_contained(),1075 _ => None,1076 }1077 }10781079 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1080 match self {1081 Call::Ethereum(call) => call.validate_self_contained(info),1082 _ => None,1083 }1084 }10851086 fn pre_dispatch_self_contained(1087 &self,1088 info: &Self::SignedInfo,1089 ) -> Option<Result<(), TransactionValidityError>> {1090 match self {1091 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1092 _ => None,1093 }1094 }10951096 fn apply_self_contained(1097 self,1098 info: Self::SignedInfo,1099 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1100 match self {1101 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1102 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1103 )),1104 _ => None,1105 }1106 }1107}11081109macro_rules! dispatch_unique_runtime {1110 ($collection:ident.$method:ident($($name:ident),*)) => {{1111 use pallet_unique::dispatch::Dispatched;11121113 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1114 let dispatch = collection.as_dyn();11151116 Ok(dispatch.$method($($name),*))1117 }};1118}11191120impl_common_runtime_apis!();11211122struct CheckInherents;11231124impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1125 fn check_inherents(1126 block: &Block,1127 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1128 ) -> sp_inherents::CheckInherentsResult {1129 let relay_chain_slot = relay_state_proof1130 .read_slot()1131 .expect("Could not read the relay chain slot from the proof");11321133 let inherent_data =1134 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1135 relay_chain_slot,1136 sp_std::time::Duration::from_secs(6),1137 )1138 .create_inherent_data()1139 .expect("Could not create the timestamp inherent data");11401141 inherent_data.check_extrinsics(block)1142 }1143}11441145cumulus_pallet_parachain_system::register_validate_block!(1146 Runtime = Runtime,1147 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1148 CheckInherents = CheckInherents,1149);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::{EnsureAddressTruncated, HashedAddressMapping, Runner};52pub use frame_support::{53 construct_runtime, match_type,54 dispatch::DispatchResult,55 PalletId, parameter_types, StorageValue, ConsensusEngineId,56 traits::{57 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,58 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,59 OnUnbalanced, Randomness, FindAuthor,60 },61 weights::{62 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},63 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,64 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,65 },66};67use up_data_structs::*;68// use pallet_contracts::weights::WeightInfo;69// #[cfg(any(feature = "std", test))]70use frame_system::{71 self as frame_system, EnsureRoot, EnsureSigned,72 limits::{BlockWeights, BlockLength},73};74use sp_arithmetic::{75 traits::{BaseArithmetic, Unsigned},76};77use smallvec::smallvec;78use codec::{Encode, Decode};79use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping, OnMethodCall};80use fp_rpc::TransactionStatus;81use sp_runtime::{82 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},83 transaction_validity::TransactionValidityError,84 SaturatedConversion,85};8687// pub use pallet_timestamp::Call as TimestampCall;88pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;8990// Polkadot imports91use pallet_xcm::XcmPassthrough;92use polkadot_parachain::primitives::Sibling;93use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};94use xcm_builder::{95 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,96 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,97 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,98 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,99 ParentIsPreset,100};101use xcm_executor::{Config, XcmExecutor, Assets};102use sp_std::{marker::PhantomData};103104use xcm::latest::{105 // Xcm,106 AssetId::{Concrete},107 Fungibility::Fungible as XcmFungible,108 MultiAsset,109 Error as XcmError,110};111use xcm_executor::traits::{MatchesFungible, WeightTrader};112//use xcm_executor::traits::MatchesFungible;113use sp_runtime::traits::CheckedConversion;114115use unique_runtime_common::{impl_common_runtime_apis, types::*, constants::*};116117pub const RUNTIME_NAME: &str = "Unique";118119pub type CrossAccountId = pallet_common::account::BasicCrossAccountId<Runtime>;120121/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know122/// the specifics of the runtime. They can then be made to be agnostic over specific formats123/// of data like extrinsics, allowing for them to continue syncing the network through upgrades124/// to even the core data structures.125pub mod opaque {126 use sp_std::prelude::*;127 use sp_runtime::impl_opaque_keys;128 use super::Aura;129130 pub use unique_runtime_common::types::*;131 pub use super::CrossAccountId;132133 impl_opaque_keys! {134 pub struct SessionKeys {135 pub aura: Aura,136 }137 }138}139140/// This runtime version.141pub const VERSION: RuntimeVersion = RuntimeVersion {142 spec_name: create_runtime_str!(RUNTIME_NAME),143 impl_name: create_runtime_str!(RUNTIME_NAME),144 authoring_version: 1,145 spec_version: 917004,146 impl_version: 0,147 apis: RUNTIME_API_VERSIONS,148 transaction_version: 1,149 state_version: 0,150};151152#[derive(codec::Encode, codec::Decode)]153pub enum XCMPMessage<XAccountId, XBalance> {154 /// Transfer tokens to the given account from the Parachain account.155 TransferToken(XAccountId, XBalance),156}157158/// The version information used to identify this runtime when compiled natively.159#[cfg(feature = "std")]160pub fn native_version() -> NativeVersion {161 NativeVersion {162 runtime_version: VERSION,163 can_author_with: Default::default(),164 }165}166167type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;168169pub struct DealWithFees;170impl OnUnbalanced<NegativeImbalance> for DealWithFees {171 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {172 if let Some(fees) = fees_then_tips.next() {173 // for fees, 100% to treasury174 let mut split = fees.ration(100, 0);175 if let Some(tips) = fees_then_tips.next() {176 // for tips, if any, 100% to treasury177 tips.ration_merge_into(100, 0, &mut split);178 }179 Treasury::on_unbalanced(split.0);180 // Author::on_unbalanced(split.1);181 }182 }183}184185parameter_types! {186 pub const BlockHashCount: BlockNumber = 2400;187 pub RuntimeBlockLength: BlockLength =188 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);189 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);190 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;191 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()192 .base_block(BlockExecutionWeight::get())193 .for_class(DispatchClass::all(), |weights| {194 weights.base_extrinsic = ExtrinsicBaseWeight::get();195 })196 .for_class(DispatchClass::Normal, |weights| {197 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);198 })199 .for_class(DispatchClass::Operational, |weights| {200 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);201 // Operational transactions have some extra reserved space, so that they202 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.203 weights.reserved = Some(204 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT205 );206 })207 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)208 .build_or_panic();209 pub const Version: RuntimeVersion = VERSION;210 pub const SS58Prefix: u8 = 7391;211}212213parameter_types! {214 pub const ChainId: u64 = 8880;215}216217pub struct FixedFee;218impl FeeCalculator for FixedFee {219 fn min_gas_price() -> U256 {220 // Targeting 0.15 UNQ per transfer221 1_018_751_825_264u64.into()222 }223}224225// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case226// (contract, which only writes a lot of data),227// approximating on top of our real store write weight228parameter_types! {229 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;230 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;231 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();232}233234/// Limiting EVM execution to 50% of block for substrate users and management tasks235/// EVM transaction consumes more weight than substrate's, so we can't rely on them being236/// scheduled fairly237const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);238parameter_types! {239 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());240}241242pub enum FixedGasWeightMapping {}243impl GasWeightMapping for FixedGasWeightMapping {244 fn gas_to_weight(gas: u64) -> Weight {245 gas.saturating_mul(WeightPerGas::get())246 }247 fn weight_to_gas(weight: Weight) -> u64 {248 weight / WeightPerGas::get()249 }250}251252impl pallet_evm::Config for Runtime {253 type BlockGasLimit = BlockGasLimit;254 type FeeCalculator = FixedFee;255 type GasWeightMapping = FixedGasWeightMapping;256 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;257 type CallOrigin = EnsureAddressTruncated;258 type WithdrawOrigin = EnsureAddressTruncated;259 type AddressMapping = HashedAddressMapping<Self::Hashing>;260 type PrecompilesType = ();261 type PrecompilesValue = ();262 type Currency = Balances;263 type Event = Event;264 type OnMethodCall = (265 pallet_evm_migration::OnMethodCall<Self>,266 pallet_unique::UniqueErcSupport<Self>,267 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,268 );269 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;270 type ChainId = ChainId;271 type Runner = pallet_evm::runner::stack::Runner<Self>;272 type OnChargeTransaction = pallet_evm_transaction_payment::OnChargeTransaction<Self>;273 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;274 type FindAuthor = EthereumFindAuthor<Aura>;275}276277impl pallet_evm_migration::Config for Runtime {278 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;279}280281pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);282impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {283 fn find_author<'a, I>(digests: I) -> Option<H160>284 where285 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,286 {287 if let Some(author_index) = F::find_author(digests) {288 let authority_id = Aura::authorities()[author_index as usize].clone();289 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));290 }291 None292 }293}294295impl pallet_ethereum::Config for Runtime {296 type Event = Event;297 type StateRoot = pallet_ethereum::IntermediateStateRoot;298}299300impl pallet_randomness_collective_flip::Config for Runtime {}301302impl frame_system::Config for Runtime {303 /// The data to be stored in an account.304 type AccountData = pallet_balances::AccountData<Balance>;305 /// The identifier used to distinguish between accounts.306 type AccountId = AccountId;307 /// The basic call filter to use in dispatchable.308 type BaseCallFilter = Everything;309 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).310 type BlockHashCount = BlockHashCount;311 /// The maximum length of a block (in bytes).312 type BlockLength = RuntimeBlockLength;313 /// The index type for blocks.314 type BlockNumber = BlockNumber;315 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.316 type BlockWeights = RuntimeBlockWeights;317 /// The aggregated dispatch type that is available for extrinsics.318 type Call = Call;319 /// The weight of database operations that the runtime can invoke.320 type DbWeight = RocksDbWeight;321 /// The ubiquitous event type.322 type Event = Event;323 /// The type for hashing blocks and tries.324 type Hash = Hash;325 /// The hashing algorithm used.326 type Hashing = BlakeTwo256;327 /// The header type.328 type Header = generic::Header<BlockNumber, BlakeTwo256>;329 /// The index type for storing how many extrinsics an account has signed.330 type Index = Index;331 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.332 type Lookup = AccountIdLookup<AccountId, ()>;333 /// What to do if an account is fully reaped from the system.334 type OnKilledAccount = ();335 /// What to do if a new account is created.336 type OnNewAccount = ();337 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;338 /// The ubiquitous origin type.339 type Origin = Origin;340 /// This type is being generated by `construct_runtime!`.341 type PalletInfo = PalletInfo;342 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.343 type SS58Prefix = SS58Prefix;344 /// Weight information for the extrinsics of this pallet.345 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;346 /// Version of the runtime.347 type Version = Version;348 type MaxConsumers = ConstU32<16>;349}350351parameter_types! {352 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;353}354355impl pallet_timestamp::Config for Runtime {356 /// A timestamp: milliseconds since the unix epoch.357 type Moment = u64;358 type OnTimestampSet = ();359 type MinimumPeriod = MinimumPeriod;360 type WeightInfo = ();361}362363parameter_types! {364 // pub const ExistentialDeposit: u128 = 500;365 pub const ExistentialDeposit: u128 = 0;366 pub const MaxLocks: u32 = 50;367}368369impl pallet_balances::Config for Runtime {370 type MaxLocks = MaxLocks;371 type MaxReserves = ();372 type ReserveIdentifier = [u8; 8];373 /// The type for recording an account's balance.374 type Balance = Balance;375 /// The ubiquitous event type.376 type Event = Event;377 type DustRemoval = Treasury;378 type ExistentialDeposit = ExistentialDeposit;379 type AccountStore = System;380 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;381}382383pub const MICROUNIQUE: Balance = 1_000_000_000_000;384pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;385pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;386pub const UNIQUE: Balance = 100 * CENTIUNIQUE;387388pub const fn deposit(items: u32, bytes: u32) -> Balance {389 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE390}391392/*393parameter_types! {394 pub TombstoneDeposit: Balance = deposit(395 1,396 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,397 );398 pub DepositPerContract: Balance = TombstoneDeposit::get();399 pub const DepositPerStorageByte: Balance = deposit(0, 1);400 pub const DepositPerStorageItem: Balance = deposit(1, 0);401 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);402 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;403 pub const SignedClaimHandicap: u32 = 2;404 pub const MaxDepth: u32 = 32;405 pub const MaxValueSize: u32 = 16 * 1024;406 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb407 // The lazy deletion runs inside on_initialize.408 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *409 RuntimeBlockWeights::get().max_block;410 // The weight needed for decoding the queue should be less or equal than a fifth411 // of the overall weight dedicated to the lazy deletion.412 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (413 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -414 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)415 )) / 5) as u32;416 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();417}418419impl pallet_contracts::Config for Runtime {420 type Time = Timestamp;421 type Randomness = RandomnessCollectiveFlip;422 type Currency = Balances;423 type Event = Event;424 type RentPayment = ();425 type SignedClaimHandicap = SignedClaimHandicap;426 type TombstoneDeposit = TombstoneDeposit;427 type DepositPerContract = DepositPerContract;428 type DepositPerStorageByte = DepositPerStorageByte;429 type DepositPerStorageItem = DepositPerStorageItem;430 type RentFraction = RentFraction;431 type SurchargeReward = SurchargeReward;432 type WeightPrice = pallet_transaction_payment::Pallet<Self>;433 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;434 type ChainExtension = NFTExtension;435 type DeletionQueueDepth = DeletionQueueDepth;436 type DeletionWeightLimit = DeletionWeightLimit;437 type Schedule = Schedule;438 type CallStack = [pallet_contracts::Frame<Self>; 31];439}440*/441442parameter_types! {443 pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer444 /// This value increases the priority of `Operational` transactions by adding445 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.446 pub const OperationalFeeMultiplier: u8 = 5;447}448449/// Linear implementor of `WeightToFeePolynomial`450pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);451452impl<T> WeightToFeePolynomial for LinearFee<T>453where454 T: BaseArithmetic + From<u32> + Copy + Unsigned,455{456 type Balance = T;457458 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {459 smallvec!(WeightToFeeCoefficient {460 // Targeting 0.1 Unique per NFT transfer461 coeff_integer: 142_688_000u32.into(),462 coeff_frac: Perbill::zero(),463 negative: false,464 degree: 1,465 })466 }467}468469impl pallet_transaction_payment::Config for Runtime {470 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;471 type TransactionByteFee = TransactionByteFee;472 type OperationalFeeMultiplier = OperationalFeeMultiplier;473 type WeightToFee = LinearFee<Balance>;474 type FeeMultiplierUpdate = ();475}476477parameter_types! {478 pub const ProposalBond: Permill = Permill::from_percent(5);479 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;480 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;481 pub const SpendPeriod: BlockNumber = 5 * MINUTES;482 pub const Burn: Permill = Permill::from_percent(0);483 pub const TipCountdown: BlockNumber = 1 * DAYS;484 pub const TipFindersFee: Percent = Percent::from_percent(20);485 pub const TipReportDepositBase: Balance = 1 * UNIQUE;486 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;487 pub const BountyDepositBase: Balance = 1 * UNIQUE;488 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;489 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");490 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;491 pub const MaximumReasonLength: u32 = 16384;492 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);493 pub const BountyValueMinimum: Balance = 5 * UNIQUE;494 pub const MaxApprovals: u32 = 100;495}496497impl pallet_treasury::Config for Runtime {498 type PalletId = TreasuryModuleId;499 type Currency = Balances;500 type ApproveOrigin = EnsureRoot<AccountId>;501 type RejectOrigin = EnsureRoot<AccountId>;502 type Event = Event;503 type OnSlash = ();504 type ProposalBond = ProposalBond;505 type ProposalBondMinimum = ProposalBondMinimum;506 type ProposalBondMaximum = ProposalBondMaximum;507 type SpendPeriod = SpendPeriod;508 type Burn = Burn;509 type BurnDestination = ();510 type SpendFunds = ();511 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;512 type MaxApprovals = MaxApprovals;513}514515impl pallet_sudo::Config for Runtime {516 type Event = Event;517 type Call = Call;518}519520pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);521522impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider523 for RelayChainBlockNumberProvider<T>524{525 type BlockNumber = BlockNumber;526527 fn current_block_number() -> Self::BlockNumber {528 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()529 .map(|d| d.relay_parent_number)530 .unwrap_or_default()531 }532}533534parameter_types! {535 pub const MinVestedTransfer: Balance = 10 * UNIQUE;536 pub const MaxVestingSchedules: u32 = 28;537}538539impl orml_vesting::Config for Runtime {540 type Event = Event;541 type Currency = pallet_balances::Pallet<Runtime>;542 type MinVestedTransfer = MinVestedTransfer;543 type VestedTransferOrigin = EnsureSigned<AccountId>;544 type WeightInfo = ();545 type MaxVestingSchedules = MaxVestingSchedules;546 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;547}548549parameter_types! {550 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;551 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;552}553554impl cumulus_pallet_parachain_system::Config for Runtime {555 type Event = Event;556 type SelfParaId = parachain_info::Pallet<Self>;557 type OnSystemEvent = ();558 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<559 // MaxDownwardMessageWeight,560 // XcmExecutor<XcmConfig>,561 // Call,562 // >;563 type OutboundXcmpMessageSource = XcmpQueue;564 type DmpMessageHandler = DmpQueue;565 type ReservedDmpWeight = ReservedDmpWeight;566 type ReservedXcmpWeight = ReservedXcmpWeight;567 type XcmpMessageHandler = XcmpQueue;568}569570impl parachain_info::Config for Runtime {}571572impl cumulus_pallet_aura_ext::Config for Runtime {}573574parameter_types! {575 pub const RelayLocation: MultiLocation = MultiLocation::parent();576 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;577 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();578 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();579}580581/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used582/// when determining ownership of accounts for asset transacting and when attempting to use XCM583/// `Transact` in order to determine the dispatch Origin.584pub type LocationToAccountId = (585 // The parent (Relay-chain) origin converts to the default `AccountId`.586 ParentIsPreset<AccountId>,587 // Sibling parachain origins convert to AccountId via the `ParaId::into`.588 SiblingParachainConvertsVia<Sibling, AccountId>,589 // Straight up local `AccountId32` origins just alias directly to `AccountId`.590 AccountId32Aliases<RelayNetwork, AccountId>,591);592593pub struct OnlySelfCurrency;594impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {595 fn matches_fungible(a: &MultiAsset) -> Option<B> {596 match (&a.id, &a.fun) {597 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),598 _ => None,599 }600 }601}602603/// Means for transacting assets on this chain.604pub type LocalAssetTransactor = CurrencyAdapter<605 // Use this currency:606 Balances,607 // Use this currency when it is a fungible asset matching the given location or name:608 OnlySelfCurrency,609 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:610 LocationToAccountId,611 // Our chain's account ID type (we can't get away without mentioning it explicitly):612 AccountId,613 // We don't track any teleports.614 (),615>;616617/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,618/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can619/// biases the kind of local `Origin` it will become.620pub type XcmOriginToTransactDispatchOrigin = (621 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location622 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for623 // foreign chains who want to have a local sovereign account on this chain which they control.624 SovereignSignedViaLocation<LocationToAccountId, Origin>,625 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when626 // recognised.627 RelayChainAsNative<RelayOrigin, Origin>,628 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when629 // recognised.630 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,631 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a632 // transaction from the Root origin.633 ParentAsSuperuser<Origin>,634 // Native signed account converter; this just converts an `AccountId32` origin into a normal635 // `Origin::Signed` origin of the same 32-byte value.636 SignedAccountId32AsNative<RelayNetwork, Origin>,637 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.638 XcmPassthrough<Origin>,639);640641parameter_types! {642 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.643 pub UnitWeightCost: Weight = 1_000_000;644 // 1200 UNIQUEs buy 1 second of weight.645 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);646 pub const MaxInstructions: u32 = 100;647 pub const MaxAuthorities: u32 = 100_000;648}649650match_type! {651 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {652 MultiLocation { parents: 1, interior: Here } |653 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }654 };655}656657pub type Barrier = (658 TakeWeightCredit,659 AllowTopLevelPaidExecutionFrom<Everything>,660 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,661 // ^^^ Parent & its unit plurality gets free execution662);663664pub struct UsingOnlySelfCurrencyComponents<665 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,666 AssetId: Get<MultiLocation>,667 AccountId,668 Currency: CurrencyT<AccountId>,669 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,670>(671 Weight,672 Currency::Balance,673 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,674);675impl<676 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,677 AssetId: Get<MultiLocation>,678 AccountId,679 Currency: CurrencyT<AccountId>,680 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,681 > WeightTrader682 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>683{684 fn new() -> Self {685 Self(0, Zero::zero(), PhantomData)686 }687688 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {689 let amount = WeightToFee::calc(&weight);690 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;691692 // location to this parachain through relay chain693 let option1: xcm::v1::AssetId = Concrete(MultiLocation {694 parents: 1,695 interior: X1(Parachain(ParachainInfo::parachain_id().into())),696 });697 // direct location698 let option2: xcm::v1::AssetId = Concrete(MultiLocation {699 parents: 0,700 interior: Here,701 });702703 let required = if payment.fungible.contains_key(&option1) {704 (option1, u128_amount).into()705 } else if payment.fungible.contains_key(&option2) {706 (option2, u128_amount).into()707 } else {708 (Concrete(MultiLocation::default()), u128_amount).into()709 };710711 let unused = payment712 .checked_sub(required)713 .map_err(|_| XcmError::TooExpensive)?;714 self.0 = self.0.saturating_add(weight);715 self.1 = self.1.saturating_add(amount);716 Ok(unused)717 }718719 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {720 let weight = weight.min(self.0);721 let amount = WeightToFee::calc(&weight);722 self.0 -= weight;723 self.1 = self.1.saturating_sub(amount);724 let amount: u128 = amount.saturated_into();725 if amount > 0 {726 Some((AssetId::get(), amount).into())727 } else {728 None729 }730 }731}732impl<733 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,734 AssetId: Get<MultiLocation>,735 AccountId,736 Currency: CurrencyT<AccountId>,737 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,738 > Drop739 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>740{741 fn drop(&mut self) {742 OnUnbalanced::on_unbalanced(Currency::issue(self.1));743 }744}745746pub struct XcmConfig;747impl Config for XcmConfig {748 type Call = Call;749 type XcmSender = XcmRouter;750 // How to withdraw and deposit an asset.751 type AssetTransactor = LocalAssetTransactor;752 type OriginConverter = XcmOriginToTransactDispatchOrigin;753 type IsReserve = NativeAsset;754 type IsTeleporter = (); // Teleportation is disabled755 type LocationInverter = LocationInverter<Ancestry>;756 type Barrier = Barrier;757 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;758 type Trader = UsingOnlySelfCurrencyComponents<759 IdentityFee<Balance>,760 RelayLocation,761 AccountId,762 Balances,763 (),764 >;765 type ResponseHandler = (); // Don't handle responses for now.766 type SubscriptionService = PolkadotXcm;767768 type AssetTrap = PolkadotXcm;769 type AssetClaims = PolkadotXcm;770}771772// parameter_types! {773// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;774// }775776/// No local origins on this chain are allowed to dispatch XCM sends/executions.777pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);778779/// The means for routing XCM messages which are not for local execution into the right message780/// queues.781pub type XcmRouter = (782 // Two routers - use UMP to communicate with the relay chain:783 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,784 // ..and XCMP to communicate with the sibling chains.785 XcmpQueue,786);787788impl pallet_evm_coder_substrate::Config for Runtime {789 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;790 type GasWeightMapping = FixedGasWeightMapping;791}792793impl pallet_xcm::Config for Runtime {794 type Event = Event;795 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;796 type XcmRouter = XcmRouter;797 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;798 type XcmExecuteFilter = Everything;799 type XcmExecutor = XcmExecutor<XcmConfig>;800 type XcmTeleportFilter = Everything;801 type XcmReserveTransferFilter = Everything;802 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;803 type LocationInverter = LocationInverter<Ancestry>;804 type Origin = Origin;805 type Call = Call;806 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;807 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;808}809810impl cumulus_pallet_xcm::Config for Runtime {811 type Event = Event;812 type XcmExecutor = XcmExecutor<XcmConfig>;813}814815impl cumulus_pallet_xcmp_queue::Config for Runtime {816 type Event = Event;817 type XcmExecutor = XcmExecutor<XcmConfig>;818 type ChannelInfo = ParachainSystem;819 type VersionWrapper = ();820 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;821 type ControllerOrigin = EnsureRoot<AccountId>;822 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;823}824825impl cumulus_pallet_dmp_queue::Config for Runtime {826 type Event = Event;827 type XcmExecutor = XcmExecutor<XcmConfig>;828 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;829}830831impl pallet_aura::Config for Runtime {832 type AuthorityId = AuraId;833 type DisabledValidators = ();834 type MaxAuthorities = MaxAuthorities;835}836837parameter_types! {838 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();839 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;840}841842impl pallet_common::Config for Runtime {843 type Event = Event;844 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;845 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;846 type CrossAccountId = pallet_common::account::BasicCrossAccountId<Self>;847848 type Currency = Balances;849 type CollectionCreationPrice = CollectionCreationPrice;850 type TreasuryAccountId = TreasuryAccountId;851}852853impl pallet_fungible::Config for Runtime {854 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;855}856impl pallet_refungible::Config for Runtime {857 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;858}859impl pallet_nonfungible::Config for Runtime {860 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;861}862863impl pallet_unique::Config for Runtime {864 type Event = Event;865 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;866}867868parameter_types! {869 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied870}871872/// Used for the pallet inflation873impl pallet_inflation::Config for Runtime {874 type Currency = Balances;875 type TreasuryAccountId = TreasuryAccountId;876 type InflationBlockInterval = InflationBlockInterval;877 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;878}879880// parameter_types! {881// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *882// RuntimeBlockWeights::get().max_block;883// pub const MaxScheduledPerBlock: u32 = 50;884// }885886type EvmSponsorshipHandler = (887 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,888 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,889);890type SponsorshipHandler = (891 pallet_unique::UniqueSponsorshipHandler<Runtime>,892 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,893 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,894);895896// impl pallet_unq_scheduler::Config for Runtime {897// type Event = Event;898// type Origin = Origin;899// type PalletsOrigin = OriginCaller;900// type Call = Call;901// type MaximumWeight = MaximumSchedulerWeight;902// type ScheduleOrigin = EnsureSigned<AccountId>;903// type MaxScheduledPerBlock = MaxScheduledPerBlock;904// type SponsorshipHandler = SponsorshipHandler;905// type WeightInfo = ();906// }907908impl pallet_evm_transaction_payment::Config for Runtime {909 type EvmSponsorshipHandler = EvmSponsorshipHandler;910 type Currency = Balances;911 type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;912 type EvmBackwardsAddressMapping = up_evm_mapping::MapBackwardsAddressTruncated;913}914915impl pallet_charge_transaction::Config for Runtime {916 type SponsorshipHandler = SponsorshipHandler;917}918919// impl pallet_contract_helpers::Config for Runtime {920// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;921// }922923parameter_types! {924 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049925 pub const HelpersContractAddress: H160 = H160([926 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,927 ]);928}929930impl pallet_evm_contract_helpers::Config for Runtime {931 type ContractAddress = HelpersContractAddress;932 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;933}934935construct_runtime!(936 pub enum Runtime where937 Block = Block,938 NodeBlock = opaque::Block,939 UncheckedExtrinsic = UncheckedExtrinsic940 {941 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,942 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,943944 Aura: pallet_aura::{Pallet, Config<T>} = 22,945 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,946947 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,948 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,949 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,950 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,951 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,952 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,953 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,954 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,955 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,956 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,957958 // XCM helpers.959 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,960 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,961 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,962 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,963964 // Unique Pallets965 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,966 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,967 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,968 // free = 63969 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,970 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,971 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,972 Fungible: pallet_fungible::{Pallet, Storage} = 67,973 Refungible: pallet_refungible::{Pallet, Storage} = 68,974 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,975976 // Frontier977 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,978 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,979980 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,981 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,982 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,983 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,984 }985);986987pub struct TransactionConverter;988989impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {990 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {991 UncheckedExtrinsic::new_unsigned(992 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),993 )994 }995}996997impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {998 fn convert_transaction(999 &self,1000 transaction: pallet_ethereum::Transaction,1001 ) -> opaque::UncheckedExtrinsic {1002 let extrinsic = UncheckedExtrinsic::new_unsigned(1003 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1004 );1005 let encoded = extrinsic.encode();1006 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1007 .expect("Encoded extrinsic is always valid")1008 }1009}10101011/// The address format for describing accounts.1012pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1013/// Block header type as expected by this runtime.1014pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1015/// Block type as expected by this runtime.1016pub type Block = generic::Block<Header, UncheckedExtrinsic>;1017/// A Block signed with a Justification1018pub type SignedBlock = generic::SignedBlock<Block>;1019/// BlockId type as expected by this runtime.1020pub type BlockId = generic::BlockId<Block>;1021/// The SignedExtension to the basic transaction logic.1022pub type SignedExtra = (1023 frame_system::CheckSpecVersion<Runtime>,1024 // system::CheckTxVersion<Runtime>,1025 frame_system::CheckGenesis<Runtime>,1026 frame_system::CheckEra<Runtime>,1027 frame_system::CheckNonce<Runtime>,1028 frame_system::CheckWeight<Runtime>,1029 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1030 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1031);1032/// Unchecked extrinsic type as expected by this runtime.1033pub type UncheckedExtrinsic =1034 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1035/// Extrinsic type that has already been checked.1036pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1037/// Executive: handles dispatch to the various modules.1038pub type Executive = frame_executive::Executive<1039 Runtime,1040 Block,1041 frame_system::ChainContext<Runtime>,1042 Runtime,1043 AllPalletsReversedWithSystemFirst,1044>;10451046impl_opaque_keys! {1047 pub struct SessionKeys {1048 pub aura: Aura,1049 }1050}10511052impl fp_self_contained::SelfContainedCall for Call {1053 type SignedInfo = H160;10541055 fn is_self_contained(&self) -> bool {1056 match self {1057 Call::Ethereum(call) => call.is_self_contained(),1058 _ => false,1059 }1060 }10611062 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1063 match self {1064 Call::Ethereum(call) => call.check_self_contained(),1065 _ => None,1066 }1067 }10681069 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1070 match self {1071 Call::Ethereum(call) => call.validate_self_contained(info),1072 _ => None,1073 }1074 }10751076 fn pre_dispatch_self_contained(1077 &self,1078 info: &Self::SignedInfo,1079 ) -> Option<Result<(), TransactionValidityError>> {1080 match self {1081 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1082 _ => None,1083 }1084 }10851086 fn apply_self_contained(1087 self,1088 info: Self::SignedInfo,1089 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1090 match self {1091 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1092 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1093 )),1094 _ => None,1095 }1096 }1097}10981099macro_rules! dispatch_unique_runtime {1100 ($collection:ident.$method:ident($($name:ident),*)) => {{1101 use pallet_unique::dispatch::Dispatched;11021103 let collection = Dispatched::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1104 let dispatch = collection.as_dyn();11051106 Ok(dispatch.$method($($name),*))1107 }};1108}11091110impl_common_runtime_apis!();11111112struct CheckInherents;11131114impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1115 fn check_inherents(1116 block: &Block,1117 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1118 ) -> sp_inherents::CheckInherentsResult {1119 let relay_chain_slot = relay_state_proof1120 .read_slot()1121 .expect("Could not read the relay chain slot from the proof");11221123 let inherent_data =1124 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1125 relay_chain_slot,1126 sp_std::time::Duration::from_secs(6),1127 )1128 .create_inherent_data()1129 .expect("Could not create the timestamp inherent data");11301131 inherent_data.check_extrinsics(block)1132 }1133}11341135cumulus_pallet_parachain_system::register_validate_block!(1136 Runtime = Runtime,1137 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1138 CheckInherents = CheckInherents,1139);