difftreelog
refactor move token address mapping to trait
in: master
6 files changed
pallets/common/src/eth.rsdiffbeforeafterboth--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -19,18 +19,12 @@
// 0x17c4e6453Cc49AAAaEACA894e6D9683e00000001 - collection 1
// TODO: Unhardcode prefix
-const ETH_ACCOUNT_PREFIX: [u8; 16] = [
+const ETH_COLLECTION_PREFIX: [u8; 16] = [
0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
];
-// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 2
-// TODO: Unhardcode prefix
-const ETH_ACCOUNT_TOKEN_PREFIX: [u8; 12] = [
- 0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
-];
-
pub fn map_eth_to_id(eth: &H160) -> Option<CollectionId> {
- if eth[0..16] != ETH_ACCOUNT_PREFIX {
+ if eth[0..16] != ETH_COLLECTION_PREFIX {
return None;
}
let mut id_bytes = [0; 4];
@@ -39,28 +33,7 @@
}
pub fn collection_id_to_address(id: CollectionId) -> H160 {
let mut out = [0; 20];
- out[0..16].copy_from_slice(Ð_ACCOUNT_PREFIX);
+ out[0..16].copy_from_slice(Ð_COLLECTION_PREFIX);
out[16..20].copy_from_slice(&u32::to_be_bytes(id.0));
- H160(out)
-}
-
-pub fn map_eth_to_token_id(eth: &H160) -> Option<(CollectionId, TokenId)> {
- if eth[0..12] != ETH_ACCOUNT_TOKEN_PREFIX {
- return None;
- }
- let mut id_bytes = [0; 4];
- let mut token_id_bytes = [0; 4];
- id_bytes.copy_from_slice(ð[12..16]);
- token_id_bytes.copy_from_slice(ð[16..20]);
- Some((
- CollectionId(u32::from_be_bytes(id_bytes)),
- TokenId(u32::from_be_bytes(token_id_bytes)),
- ))
-}
-pub fn collection_token_id_to_address(id: CollectionId, token: TokenId) -> H160 {
- let mut out = [0; 20];
- out[0..12].copy_from_slice(Ð_ACCOUNT_TOKEN_PREFIX);
- out[12..16].copy_from_slice(&u32::to_be_bytes(id.0));
- out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
H160(out)
}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -165,8 +165,10 @@
use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};
use pallet_evm::account;
use dispatch::CollectionDispatch;
+ use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};
+ use frame_system::pallet_prelude::*;
use frame_support::traits::Currency;
- use up_data_structs::TokenId;
+ use up_data_structs::{TokenId, mapping::TokenAddressMapping};
use scale_info::TypeInfo;
use up_evm_mapping::CrossAccountId;
@@ -185,6 +187,9 @@
type CollectionDispatch: CollectionDispatch<Self>;
type TreasuryAccountId: Get<Self::AccountId>;
+
+ type EvmTokenAddressMapping: TokenAddressMapping<H160>;
+ type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;
}
#[pallet::pallet]
primitives/data-structs/src/lib.rsdiffbeforeafterboth--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -20,34 +20,23 @@
convert::{TryFrom, TryInto},
fmt,
};
-use frame_support::storage::bounded_btree_map::BoundedBTreeMap;
-use sp_std::collections::btree_map::BTreeMap;
+use frame_support::{
+ storage::{bounded_btree_map::BoundedBTreeMap, bounded_btree_set::BoundedBTreeSet},
+ traits::ConstU16,
+};
+use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
#[cfg(feature = "serde")]
-pub use serde::{Serialize, Deserialize};
+use serde::{Serialize, Deserialize};
use sp_core::U256;
use sp_runtime::{ArithmeticError, sp_std::prelude::Vec};
use codec::{Decode, Encode, EncodeLike, MaxEncodedLen};
-pub use frame_support::{
- BoundedVec, construct_runtime, decl_event, decl_module, decl_storage, decl_error,
- dispatch::DispatchResult,
- ensure, fail, parameter_types,
- traits::{
- Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
- Randomness, IsSubType, WithdrawReasons,
- },
- weights::{
- constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
- DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,
- WeightToFeePolynomial, DispatchClass,
- },
- StorageValue, transactional,
- pallet_prelude::ConstU32,
-};
+use frame_support::{BoundedVec, traits::ConstU32};
use derivative::Derivative;
use scale_info::TypeInfo;
+pub mod mapping;
mod migration;
pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
primitives/data-structs/src/mapping.rsdiffbeforeafterboth--- /dev/null
+++ b/primitives/data-structs/src/mapping.rs
@@ -0,0 +1,63 @@
+use core::marker::PhantomData;
+
+use sp_core::H160;
+
+use crate::{CollectionId, TokenId};
+use up_evm_mapping::CrossAccountId;
+
+pub trait TokenAddressMapping<Address> {
+ fn token_to_address(collection: CollectionId, token: TokenId) -> Address;
+ fn address_to_token(address: &Address) -> Option<(CollectionId, TokenId)>;
+ fn is_token_address(address: &Address) -> bool;
+}
+
+pub struct EvmTokenAddressMapping;
+
+/// 0xf8238ccfff8ed887463fd5e00000000100000002 - collection 1, token 2
+const ETH_COLLECTION_TOKEN_PREFIX: [u8; 12] = [
+ 0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+];
+
+impl TokenAddressMapping<H160> for EvmTokenAddressMapping {
+ fn token_to_address(collection: CollectionId, token: TokenId) -> H160 {
+ let mut out = [0; 20];
+ out[0..12].copy_from_slice(Ð_COLLECTION_TOKEN_PREFIX);
+ out[12..16].copy_from_slice(&u32::to_be_bytes(collection.0));
+ out[16..20].copy_from_slice(&u32::to_be_bytes(token.0));
+ H160(out)
+ }
+
+ fn address_to_token(eth: &H160) -> Option<(CollectionId, TokenId)> {
+ if eth[0..12] != ETH_COLLECTION_TOKEN_PREFIX {
+ return None;
+ }
+ let mut id_bytes = [0; 4];
+ let mut token_id_bytes = [0; 4];
+ id_bytes.copy_from_slice(ð[12..16]);
+ token_id_bytes.copy_from_slice(ð[16..20]);
+ Some((
+ CollectionId(u32::from_be_bytes(id_bytes)),
+ TokenId(u32::from_be_bytes(token_id_bytes)),
+ ))
+ }
+
+ fn is_token_address(address: &H160) -> bool {
+ address[0..12] == ETH_COLLECTION_TOKEN_PREFIX
+ }
+}
+
+pub struct CrossTokenAddressMapping<A>(PhantomData<A>);
+
+impl<A, C: CrossAccountId<A>> TokenAddressMapping<C> for CrossTokenAddressMapping<A> {
+ fn token_to_address(collection: CollectionId, token: TokenId) -> C {
+ C::from_eth(EvmTokenAddressMapping::token_to_address(collection, token))
+ }
+
+ fn address_to_token(address: &C) -> Option<(CollectionId, TokenId)> {
+ EvmTokenAddressMapping::address_to_token(address.as_eth())
+ }
+
+ fn is_token_address(address: &C) -> bool {
+ EvmTokenAddressMapping::is_token_address(address.as_eth())
+ }
+}
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};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};70// use pallet_contracts::weights::WeightInfo;71// #[cfg(any(feature = "std", test))]72use frame_system::{73 self as frame_system, EnsureRoot, EnsureSigned,74 limits::{BlockWeights, BlockLength},75};76use sp_arithmetic::{77 traits::{BaseArithmetic, Unsigned},78};79use smallvec::smallvec;80use codec::{Encode, Decode};81use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};82use fp_rpc::TransactionStatus;83use sp_runtime::{84 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},85 transaction_validity::TransactionValidityError,86 SaturatedConversion,87};8889// pub use pallet_timestamp::Call as TimestampCall;90pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9192// Polkadot imports93use pallet_xcm::XcmPassthrough;94use polkadot_parachain::primitives::Sibling;95use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};96use xcm_builder::{97 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,98 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,99 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,100 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,101 ParentIsPreset,102};103use xcm_executor::{Config, XcmExecutor, Assets};104use sp_std::{marker::PhantomData};105106use xcm::latest::{107 // Xcm,108 AssetId::{Concrete},109 Fungibility::Fungible as XcmFungible,110 MultiAsset,111 Error as XcmError,112};113use xcm_executor::traits::{MatchesFungible, WeightTrader};114//use xcm_executor::traits::MatchesFungible;115use sp_runtime::traits::CheckedConversion;116117use unique_runtime_common::{118 impl_common_runtime_apis,119 types::*,120 constants::*,121 dispatch::{CollectionDispatchT, CollectionDispatch},122};123124pub const RUNTIME_NAME: &str = "opal";125pub const TOKEN_SYMBOL: &str = "OPL";126127type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;128129impl RuntimeInstance for Runtime {130 type CrossAccountId = self::CrossAccountId;131 type TransactionConverter = self::TransactionConverter;132133 fn get_transaction_converter() -> TransactionConverter {134 TransactionConverter135 }136}137138/// The type for looking up accounts. We don't expect more than 4 billion of them, but you139/// never know...140pub type AccountIndex = u32;141142/// Balance of an account.143pub type Balance = u128;144145/// Index of a transaction in the chain.146pub type Index = u32;147148/// A hash of some data used by the chain.149pub type Hash = sp_core::H256;150151/// Digest item type.152pub type DigestItem = generic::DigestItem;153154/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know155/// the specifics of the runtime. They can then be made to be agnostic over specific formats156/// of data like extrinsics, allowing for them to continue syncing the network through upgrades157/// to even the core data structures.158pub mod opaque {159 use sp_std::prelude::*;160 use sp_runtime::impl_opaque_keys;161 use super::Aura;162163 pub use unique_runtime_common::types::*;164165 impl_opaque_keys! {166 pub struct SessionKeys {167 pub aura: Aura,168 }169 }170}171172/// This runtime version.173pub const VERSION: RuntimeVersion = RuntimeVersion {174 spec_name: create_runtime_str!(RUNTIME_NAME),175 impl_name: create_runtime_str!(RUNTIME_NAME),176 authoring_version: 1,177 spec_version: 920000,178 impl_version: 0,179 apis: RUNTIME_API_VERSIONS,180 transaction_version: 1,181 state_version: 0,182};183184#[derive(codec::Encode, codec::Decode)]185pub enum XCMPMessage<XAccountId, XBalance> {186 /// Transfer tokens to the given account from the Parachain account.187 TransferToken(XAccountId, XBalance),188}189190/// The version information used to identify this runtime when compiled natively.191#[cfg(feature = "std")]192pub fn native_version() -> NativeVersion {193 NativeVersion {194 runtime_version: VERSION,195 can_author_with: Default::default(),196 }197}198199type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;200201pub struct DealWithFees;202impl OnUnbalanced<NegativeImbalance> for DealWithFees {203 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {204 if let Some(fees) = fees_then_tips.next() {205 // for fees, 100% to treasury206 let mut split = fees.ration(100, 0);207 if let Some(tips) = fees_then_tips.next() {208 // for tips, if any, 100% to treasury209 tips.ration_merge_into(100, 0, &mut split);210 }211 Treasury::on_unbalanced(split.0);212 // Author::on_unbalanced(split.1);213 }214 }215}216217parameter_types! {218 pub const BlockHashCount: BlockNumber = 2400;219 pub RuntimeBlockLength: BlockLength =220 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);221 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);222 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;223 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()224 .base_block(BlockExecutionWeight::get())225 .for_class(DispatchClass::all(), |weights| {226 weights.base_extrinsic = ExtrinsicBaseWeight::get();227 })228 .for_class(DispatchClass::Normal, |weights| {229 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);230 })231 .for_class(DispatchClass::Operational, |weights| {232 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);233 // Operational transactions have some extra reserved space, so that they234 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.235 weights.reserved = Some(236 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT237 );238 })239 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)240 .build_or_panic();241 pub const Version: RuntimeVersion = VERSION;242 pub const SS58Prefix: u8 = 42;243}244245parameter_types! {246 pub const ChainId: u64 = 8882;247}248249pub struct FixedFee;250impl FeeCalculator for FixedFee {251 fn min_gas_price() -> U256 {252 MIN_GAS_PRICE.into()253 }254}255256// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case257// (contract, which only writes a lot of data),258// approximating on top of our real store write weight259parameter_types! {260 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;261 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;262 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();263}264265/// Limiting EVM execution to 50% of block for substrate users and management tasks266/// EVM transaction consumes more weight than substrate's, so we can't rely on them being267/// scheduled fairly268const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);269parameter_types! {270 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());271}272273pub enum FixedGasWeightMapping {}274impl GasWeightMapping for FixedGasWeightMapping {275 fn gas_to_weight(gas: u64) -> Weight {276 gas.saturating_mul(WeightPerGas::get())277 }278 fn weight_to_gas(weight: Weight) -> u64 {279 weight / WeightPerGas::get()280 }281}282283impl pallet_evm::account::Config for Runtime {284 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;285 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;286 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;287}288289impl pallet_evm::Config for Runtime {290 type BlockGasLimit = BlockGasLimit;291 type FeeCalculator = FixedFee;292 type GasWeightMapping = FixedGasWeightMapping;293 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;294 type CallOrigin = EnsureAddressTruncated;295 type WithdrawOrigin = EnsureAddressTruncated;296 type AddressMapping = HashedAddressMapping<Self::Hashing>;297 type PrecompilesType = ();298 type PrecompilesValue = ();299 type Currency = Balances;300 type Event = Event;301 type OnMethodCall = (302 pallet_evm_migration::OnMethodCall<Self>,303 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,304 CollectionDispatchT<Self>,305 );306 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;307 type ChainId = ChainId;308 type Runner = pallet_evm::runner::stack::Runner<Self>;309 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;310 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;311 type FindAuthor = EthereumFindAuthor<Aura>;312}313314impl pallet_evm_migration::Config for Runtime {315 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;316}317318pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);319impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {320 fn find_author<'a, I>(digests: I) -> Option<H160>321 where322 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,323 {324 if let Some(author_index) = F::find_author(digests) {325 let authority_id = Aura::authorities()[author_index as usize].clone();326 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));327 }328 None329 }330}331332impl pallet_ethereum::Config for Runtime {333 type Event = Event;334 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;335}336337impl pallet_randomness_collective_flip::Config for Runtime {}338339impl frame_system::Config for Runtime {340 /// The data to be stored in an account.341 type AccountData = pallet_balances::AccountData<Balance>;342 /// The identifier used to distinguish between accounts.343 type AccountId = AccountId;344 /// The basic call filter to use in dispatchable.345 type BaseCallFilter = Everything;346 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).347 type BlockHashCount = BlockHashCount;348 /// The maximum length of a block (in bytes).349 type BlockLength = RuntimeBlockLength;350 /// The index type for blocks.351 type BlockNumber = BlockNumber;352 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.353 type BlockWeights = RuntimeBlockWeights;354 /// The aggregated dispatch type that is available for extrinsics.355 type Call = Call;356 /// The weight of database operations that the runtime can invoke.357 type DbWeight = RocksDbWeight;358 /// The ubiquitous event type.359 type Event = Event;360 /// The type for hashing blocks and tries.361 type Hash = Hash;362 /// The hashing algorithm used.363 type Hashing = BlakeTwo256;364 /// The header type.365 type Header = generic::Header<BlockNumber, BlakeTwo256>;366 /// The index type for storing how many extrinsics an account has signed.367 type Index = Index;368 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.369 type Lookup = AccountIdLookup<AccountId, ()>;370 /// What to do if an account is fully reaped from the system.371 type OnKilledAccount = ();372 /// What to do if a new account is created.373 type OnNewAccount = ();374 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;375 /// The ubiquitous origin type.376 type Origin = Origin;377 /// This type is being generated by `construct_runtime!`.378 type PalletInfo = PalletInfo;379 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.380 type SS58Prefix = SS58Prefix;381 /// Weight information for the extrinsics of this pallet.382 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;383 /// Version of the runtime.384 type Version = Version;385 type MaxConsumers = ConstU32<16>;386}387388parameter_types! {389 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;390}391392impl pallet_timestamp::Config for Runtime {393 /// A timestamp: milliseconds since the unix epoch.394 type Moment = u64;395 type OnTimestampSet = ();396 type MinimumPeriod = MinimumPeriod;397 type WeightInfo = ();398}399400parameter_types! {401 // pub const ExistentialDeposit: u128 = 500;402 pub const ExistentialDeposit: u128 = 0;403 pub const MaxLocks: u32 = 50;404}405406impl pallet_balances::Config for Runtime {407 type MaxLocks = MaxLocks;408 type MaxReserves = ();409 type ReserveIdentifier = [u8; 8];410 /// The type for recording an account's balance.411 type Balance = Balance;412 /// The ubiquitous event type.413 type Event = Event;414 type DustRemoval = Treasury;415 type ExistentialDeposit = ExistentialDeposit;416 type AccountStore = System;417 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;418}419420pub const fn deposit(items: u32, bytes: u32) -> Balance {421 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE422}423424/*425parameter_types! {426 pub TombstoneDeposit: Balance = deposit(427 1,428 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,429 );430 pub DepositPerContract: Balance = TombstoneDeposit::get();431 pub const DepositPerStorageByte: Balance = deposit(0, 1);432 pub const DepositPerStorageItem: Balance = deposit(1, 0);433 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);434 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;435 pub const SignedClaimHandicap: u32 = 2;436 pub const MaxDepth: u32 = 32;437 pub const MaxValueSize: u32 = 16 * 1024;438 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb439 // The lazy deletion runs inside on_initialize.440 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *441 RuntimeBlockWeights::get().max_block;442 // The weight needed for decoding the queue should be less or equal than a fifth443 // of the overall weight dedicated to the lazy deletion.444 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (445 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -446 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)447 )) / 5) as u32;448 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();449}450451impl pallet_contracts::Config for Runtime {452 type Time = Timestamp;453 type Randomness = RandomnessCollectiveFlip;454 type Currency = Balances;455 type Event = Event;456 type RentPayment = ();457 type SignedClaimHandicap = SignedClaimHandicap;458 type TombstoneDeposit = TombstoneDeposit;459 type DepositPerContract = DepositPerContract;460 type DepositPerStorageByte = DepositPerStorageByte;461 type DepositPerStorageItem = DepositPerStorageItem;462 type RentFraction = RentFraction;463 type SurchargeReward = SurchargeReward;464 type WeightPrice = pallet_transaction_payment::Pallet<Self>;465 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;466 type ChainExtension = NFTExtension;467 type DeletionQueueDepth = DeletionQueueDepth;468 type DeletionWeightLimit = DeletionWeightLimit;469 type Schedule = Schedule;470 type CallStack = [pallet_contracts::Frame<Self>; 31];471}472*/473474parameter_types! {475 /// This value increases the priority of `Operational` transactions by adding476 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.477 pub const OperationalFeeMultiplier: u8 = 5;478}479480/// Linear implementor of `WeightToFeePolynomial`481pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);482483impl<T> WeightToFeePolynomial for LinearFee<T>484where485 T: BaseArithmetic + From<u32> + Copy + Unsigned,486{487 type Balance = T;488489 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {490 smallvec!(WeightToFeeCoefficient {491 // Targeting 0.1 Unique per NFT transfer492 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),493 coeff_frac: Perbill::zero(),494 negative: false,495 degree: 1,496 })497 }498}499500impl pallet_transaction_payment::Config for Runtime {501 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;502 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;503 type OperationalFeeMultiplier = OperationalFeeMultiplier;504 type WeightToFee = LinearFee<Balance>;505 type FeeMultiplierUpdate = ();506}507508parameter_types! {509 pub const ProposalBond: Permill = Permill::from_percent(5);510 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;511 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;512 pub const SpendPeriod: BlockNumber = 5 * MINUTES;513 pub const Burn: Permill = Permill::from_percent(0);514 pub const TipCountdown: BlockNumber = 1 * DAYS;515 pub const TipFindersFee: Percent = Percent::from_percent(20);516 pub const TipReportDepositBase: Balance = 1 * UNIQUE;517 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;518 pub const BountyDepositBase: Balance = 1 * UNIQUE;519 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;520 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");521 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;522 pub const MaximumReasonLength: u32 = 16384;523 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);524 pub const BountyValueMinimum: Balance = 5 * UNIQUE;525 pub const MaxApprovals: u32 = 100;526}527528impl pallet_treasury::Config for Runtime {529 type PalletId = TreasuryModuleId;530 type Currency = Balances;531 type ApproveOrigin = EnsureRoot<AccountId>;532 type RejectOrigin = EnsureRoot<AccountId>;533 type Event = Event;534 type OnSlash = ();535 type ProposalBond = ProposalBond;536 type ProposalBondMinimum = ProposalBondMinimum;537 type ProposalBondMaximum = ProposalBondMaximum;538 type SpendPeriod = SpendPeriod;539 type Burn = Burn;540 type BurnDestination = ();541 type SpendFunds = ();542 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;543 type MaxApprovals = MaxApprovals;544}545546impl pallet_sudo::Config for Runtime {547 type Event = Event;548 type Call = Call;549}550551pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);552553impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider554 for RelayChainBlockNumberProvider<T>555{556 type BlockNumber = BlockNumber;557558 fn current_block_number() -> Self::BlockNumber {559 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()560 .map(|d| d.relay_parent_number)561 .unwrap_or_default()562 }563}564565parameter_types! {566 pub const MinVestedTransfer: Balance = 10 * UNIQUE;567 pub const MaxVestingSchedules: u32 = 28;568}569570impl orml_vesting::Config for Runtime {571 type Event = Event;572 type Currency = pallet_balances::Pallet<Runtime>;573 type MinVestedTransfer = MinVestedTransfer;574 type VestedTransferOrigin = EnsureSigned<AccountId>;575 type WeightInfo = ();576 type MaxVestingSchedules = MaxVestingSchedules;577 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;578}579580parameter_types! {581 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;582 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;583}584585impl cumulus_pallet_parachain_system::Config for Runtime {586 type Event = Event;587 type SelfParaId = parachain_info::Pallet<Self>;588 type OnSystemEvent = ();589 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<590 // MaxDownwardMessageWeight,591 // XcmExecutor<XcmConfig>,592 // Call,593 // >;594 type OutboundXcmpMessageSource = XcmpQueue;595 type DmpMessageHandler = DmpQueue;596 type ReservedDmpWeight = ReservedDmpWeight;597 type ReservedXcmpWeight = ReservedXcmpWeight;598 type XcmpMessageHandler = XcmpQueue;599}600601impl parachain_info::Config for Runtime {}602603impl cumulus_pallet_aura_ext::Config for Runtime {}604605parameter_types! {606 pub const RelayLocation: MultiLocation = MultiLocation::parent();607 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;608 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();609 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();610}611612/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used613/// when determining ownership of accounts for asset transacting and when attempting to use XCM614/// `Transact` in order to determine the dispatch Origin.615pub type LocationToAccountId = (616 // The parent (Relay-chain) origin converts to the default `AccountId`.617 ParentIsPreset<AccountId>,618 // Sibling parachain origins convert to AccountId via the `ParaId::into`.619 SiblingParachainConvertsVia<Sibling, AccountId>,620 // Straight up local `AccountId32` origins just alias directly to `AccountId`.621 AccountId32Aliases<RelayNetwork, AccountId>,622);623624pub struct OnlySelfCurrency;625impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {626 fn matches_fungible(a: &MultiAsset) -> Option<B> {627 match (&a.id, &a.fun) {628 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),629 _ => None,630 }631 }632}633634/// Means for transacting assets on this chain.635pub type LocalAssetTransactor = CurrencyAdapter<636 // Use this currency:637 Balances,638 // Use this currency when it is a fungible asset matching the given location or name:639 OnlySelfCurrency,640 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:641 LocationToAccountId,642 // Our chain's account ID type (we can't get away without mentioning it explicitly):643 AccountId,644 // We don't track any teleports.645 (),646>;647648/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,649/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can650/// biases the kind of local `Origin` it will become.651pub type XcmOriginToTransactDispatchOrigin = (652 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location653 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for654 // foreign chains who want to have a local sovereign account on this chain which they control.655 SovereignSignedViaLocation<LocationToAccountId, Origin>,656 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when657 // recognised.658 RelayChainAsNative<RelayOrigin, Origin>,659 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when660 // recognised.661 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,662 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a663 // transaction from the Root origin.664 ParentAsSuperuser<Origin>,665 // Native signed account converter; this just converts an `AccountId32` origin into a normal666 // `Origin::Signed` origin of the same 32-byte value.667 SignedAccountId32AsNative<RelayNetwork, Origin>,668 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.669 XcmPassthrough<Origin>,670);671672parameter_types! {673 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.674 pub UnitWeightCost: Weight = 1_000_000;675 // 1200 UNIQUEs buy 1 second of weight.676 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);677 pub const MaxInstructions: u32 = 100;678 pub const MaxAuthorities: u32 = 100_000;679}680681match_types! {682 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {683 MultiLocation { parents: 1, interior: Here } |684 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }685 };686}687688pub type Barrier = (689 TakeWeightCredit,690 AllowTopLevelPaidExecutionFrom<Everything>,691 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,692 // ^^^ Parent & its unit plurality gets free execution693);694695pub struct UsingOnlySelfCurrencyComponents<696 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,697 AssetId: Get<MultiLocation>,698 AccountId,699 Currency: CurrencyT<AccountId>,700 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,701>(702 Weight,703 Currency::Balance,704 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,705);706impl<707 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,708 AssetId: Get<MultiLocation>,709 AccountId,710 Currency: CurrencyT<AccountId>,711 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,712 > WeightTrader713 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>714{715 fn new() -> Self {716 Self(0, Zero::zero(), PhantomData)717 }718719 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {720 let amount = WeightToFee::calc(&weight);721 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;722723 // location to this parachain through relay chain724 let option1: xcm::v1::AssetId = Concrete(MultiLocation {725 parents: 1,726 interior: X1(Parachain(ParachainInfo::parachain_id().into())),727 });728 // direct location729 let option2: xcm::v1::AssetId = Concrete(MultiLocation {730 parents: 0,731 interior: Here,732 });733734 let required = if payment.fungible.contains_key(&option1) {735 (option1, u128_amount).into()736 } else if payment.fungible.contains_key(&option2) {737 (option2, u128_amount).into()738 } else {739 (Concrete(MultiLocation::default()), u128_amount).into()740 };741742 let unused = payment743 .checked_sub(required)744 .map_err(|_| XcmError::TooExpensive)?;745 self.0 = self.0.saturating_add(weight);746 self.1 = self.1.saturating_add(amount);747 Ok(unused)748 }749750 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {751 let weight = weight.min(self.0);752 let amount = WeightToFee::calc(&weight);753 self.0 -= weight;754 self.1 = self.1.saturating_sub(amount);755 let amount: u128 = amount.saturated_into();756 if amount > 0 {757 Some((AssetId::get(), amount).into())758 } else {759 None760 }761 }762}763impl<764 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,765 AssetId: Get<MultiLocation>,766 AccountId,767 Currency: CurrencyT<AccountId>,768 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,769 > Drop770 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>771{772 fn drop(&mut self) {773 OnUnbalanced::on_unbalanced(Currency::issue(self.1));774 }775}776777pub struct XcmConfig;778impl Config for XcmConfig {779 type Call = Call;780 type XcmSender = XcmRouter;781 // How to withdraw and deposit an asset.782 type AssetTransactor = LocalAssetTransactor;783 type OriginConverter = XcmOriginToTransactDispatchOrigin;784 type IsReserve = NativeAsset;785 type IsTeleporter = (); // Teleportation is disabled786 type LocationInverter = LocationInverter<Ancestry>;787 type Barrier = Barrier;788 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;789 type Trader = UsingOnlySelfCurrencyComponents<790 IdentityFee<Balance>,791 RelayLocation,792 AccountId,793 Balances,794 (),795 >;796 type ResponseHandler = (); // Don't handle responses for now.797 type SubscriptionService = PolkadotXcm;798799 type AssetTrap = PolkadotXcm;800 type AssetClaims = PolkadotXcm;801}802803// parameter_types! {804// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;805// }806807/// No local origins on this chain are allowed to dispatch XCM sends/executions.808pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);809810/// The means for routing XCM messages which are not for local execution into the right message811/// queues.812pub type XcmRouter = (813 // Two routers - use UMP to communicate with the relay chain:814 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,815 // ..and XCMP to communicate with the sibling chains.816 XcmpQueue,817);818819impl pallet_evm_coder_substrate::Config for Runtime {820 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;821 type GasWeightMapping = FixedGasWeightMapping;822}823824impl pallet_xcm::Config for Runtime {825 type Event = Event;826 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;827 type XcmRouter = XcmRouter;828 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;829 type XcmExecuteFilter = Everything;830 type XcmExecutor = XcmExecutor<XcmConfig>;831 type XcmTeleportFilter = Everything;832 type XcmReserveTransferFilter = Everything;833 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;834 type LocationInverter = LocationInverter<Ancestry>;835 type Origin = Origin;836 type Call = Call;837 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;838 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;839}840841impl cumulus_pallet_xcm::Config for Runtime {842 type Event = Event;843 type XcmExecutor = XcmExecutor<XcmConfig>;844}845846impl cumulus_pallet_xcmp_queue::Config for Runtime {847 type WeightInfo = ();848 type Event = Event;849 type XcmExecutor = XcmExecutor<XcmConfig>;850 type ChannelInfo = ParachainSystem;851 type VersionWrapper = ();852 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;853 type ControllerOrigin = EnsureRoot<AccountId>;854 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;855}856857impl cumulus_pallet_dmp_queue::Config for Runtime {858 type Event = Event;859 type XcmExecutor = XcmExecutor<XcmConfig>;860 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;861}862863impl pallet_aura::Config for Runtime {864 type AuthorityId = AuraId;865 type DisabledValidators = ();866 type MaxAuthorities = MaxAuthorities;867}868869parameter_types! {870 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();871 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;872}873874impl pallet_common::Config for Runtime {875 type Event = Event;876 type Currency = Balances;877 type CollectionCreationPrice = CollectionCreationPrice;878 type TreasuryAccountId = TreasuryAccountId;879 type CollectionDispatch = CollectionDispatchT<Self>;880881 type EvmTokenAddressMapping = EvmTokenAddressMapping;882 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;883}884885impl pallet_structure::Config for Runtime {886 type Event = Event;887 type Call = Call;888 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;889}890891impl pallet_fungible::Config for Runtime {892 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;893}894impl pallet_refungible::Config for Runtime {895 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;896}897impl pallet_nonfungible::Config for Runtime {898 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;899}900901impl pallet_unique::Config for Runtime {902 type Event = Event;903 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;904}905906parameter_types! {907 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied908}909910/// Used for the pallet inflation911impl pallet_inflation::Config for Runtime {912 type Currency = Balances;913 type TreasuryAccountId = TreasuryAccountId;914 type InflationBlockInterval = InflationBlockInterval;915 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;916}917918// parameter_types! {919// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *920// RuntimeBlockWeights::get().max_block;921// pub const MaxScheduledPerBlock: u32 = 50;922// }923924type EvmSponsorshipHandler = (925 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,926 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,927);928type SponsorshipHandler = (929 pallet_unique::UniqueSponsorshipHandler<Runtime>,930 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,931 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,932);933934// impl pallet_unq_scheduler::Config for Runtime {935// type Event = Event;936// type Origin = Origin;937// type PalletsOrigin = OriginCaller;938// type Call = Call;939// type MaximumWeight = MaximumSchedulerWeight;940// type ScheduleOrigin = EnsureSigned<AccountId>;941// type MaxScheduledPerBlock = MaxScheduledPerBlock;942// type SponsorshipHandler = SponsorshipHandler;943// type WeightInfo = ();944// }945946impl pallet_evm_transaction_payment::Config for Runtime {947 type EvmSponsorshipHandler = EvmSponsorshipHandler;948 type Currency = Balances;949}950951impl pallet_charge_transaction::Config for Runtime {952 type SponsorshipHandler = SponsorshipHandler;953}954955// impl pallet_contract_helpers::Config for Runtime {956// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;957// }958959parameter_types! {960 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049961 pub const HelpersContractAddress: H160 = H160([962 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,963 ]);964}965966impl pallet_evm_contract_helpers::Config for Runtime {967 type ContractAddress = HelpersContractAddress;968 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;969}970971construct_runtime!(972 pub enum Runtime where973 Block = Block,974 NodeBlock = opaque::Block,975 UncheckedExtrinsic = UncheckedExtrinsic976 {977 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,978 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,979980 Aura: pallet_aura::{Pallet, Config<T>} = 22,981 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,982983 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,984 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,985 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,986 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,987 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,988 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,989 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,990 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,991 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,992 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,993994 // XCM helpers.995 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,996 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,997 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,998 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,9991000 // Unique Pallets1001 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1002 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1003 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1004 // free = 631005 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1006 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1007 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1008 Fungible: pallet_fungible::{Pallet, Storage} = 67,1009 Refungible: pallet_refungible::{Pallet, Storage} = 68,1010 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,10111012 // Frontier1013 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1014 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10151016 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1017 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1018 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1019 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1020 }1021);10221023pub struct TransactionConverter;10241025impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1026 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1027 UncheckedExtrinsic::new_unsigned(1028 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1029 )1030 }1031}10321033impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1034 fn convert_transaction(1035 &self,1036 transaction: pallet_ethereum::Transaction,1037 ) -> opaque::UncheckedExtrinsic {1038 let extrinsic = UncheckedExtrinsic::new_unsigned(1039 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1040 );1041 let encoded = extrinsic.encode();1042 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1043 .expect("Encoded extrinsic is always valid")1044 }1045}10461047/// The address format for describing accounts.1048pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1049/// Block header type as expected by this runtime.1050pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1051/// Block type as expected by this runtime.1052pub type Block = generic::Block<Header, UncheckedExtrinsic>;1053/// A Block signed with a Justification1054pub type SignedBlock = generic::SignedBlock<Block>;1055/// BlockId type as expected by this runtime.1056pub type BlockId = generic::BlockId<Block>;1057/// The SignedExtension to the basic transaction logic.1058pub type SignedExtra = (1059 frame_system::CheckSpecVersion<Runtime>,1060 // system::CheckTxVersion<Runtime>,1061 frame_system::CheckGenesis<Runtime>,1062 frame_system::CheckEra<Runtime>,1063 frame_system::CheckNonce<Runtime>,1064 frame_system::CheckWeight<Runtime>,1065 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1066 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1067);1068/// Unchecked extrinsic type as expected by this runtime.1069pub type UncheckedExtrinsic =1070 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1071/// Extrinsic type that has already been checked.1072pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1073/// Executive: handles dispatch to the various modules.1074pub type Executive = frame_executive::Executive<1075 Runtime,1076 Block,1077 frame_system::ChainContext<Runtime>,1078 Runtime,1079 AllPalletsReversedWithSystemFirst,1080>;10811082impl_opaque_keys! {1083 pub struct SessionKeys {1084 pub aura: Aura,1085 }1086}10871088impl fp_self_contained::SelfContainedCall for Call {1089 type SignedInfo = H160;10901091 fn is_self_contained(&self) -> bool {1092 match self {1093 Call::Ethereum(call) => call.is_self_contained(),1094 _ => false,1095 }1096 }10971098 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1099 match self {1100 Call::Ethereum(call) => call.check_self_contained(),1101 _ => None,1102 }1103 }11041105 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1106 match self {1107 Call::Ethereum(call) => call.validate_self_contained(info),1108 _ => None,1109 }1110 }11111112 fn pre_dispatch_self_contained(1113 &self,1114 info: &Self::SignedInfo,1115 ) -> Option<Result<(), TransactionValidityError>> {1116 match self {1117 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1118 _ => None,1119 }1120 }11211122 fn apply_self_contained(1123 self,1124 info: Self::SignedInfo,1125 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1126 match self {1127 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1128 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1129 )),1130 _ => None,1131 }1132 }1133}11341135macro_rules! dispatch_unique_runtime {1136 ($collection:ident.$method:ident($($name:ident),*)) => {{1137 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1138 let dispatch = collection.as_dyn();11391140 Ok(dispatch.$method($($name),*))1141 }};1142}11431144impl_common_runtime_apis!();11451146struct CheckInherents;11471148impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1149 fn check_inherents(1150 block: &Block,1151 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1152 ) -> sp_inherents::CheckInherentsResult {1153 let relay_chain_slot = relay_state_proof1154 .read_slot()1155 .expect("Could not read the relay chain slot from the proof");11561157 let inherent_data =1158 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1159 relay_chain_slot,1160 sp_std::time::Duration::from_secs(6),1161 )1162 .create_inherent_data()1163 .expect("Could not create the timestamp inherent data");11641165 inherent_data.check_extrinsics(block)1166 }1167}11681169cumulus_pallet_parachain_system::register_validate_block!(1170 Runtime = Runtime,1171 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1172 CheckInherents = CheckInherents,1173);1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.1819#![cfg_attr(not(feature = "std"), no_std)]20// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.21#![recursion_limit = "1024"]22#![allow(clippy::from_over_into, clippy::identity_op)]23#![allow(clippy::fn_to_numeric_cast_with_truncation)]24// Make the WASM binary available.25#[cfg(feature = "std")]26include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));2728use sp_api::impl_runtime_apis;29use sp_core::{crypto::KeyTypeId, OpaqueMetadata, H256, U256, H160};30use sp_runtime::DispatchError;31// #[cfg(any(feature = "std", test))]32// pub use sp_runtime::BuildStorage;3334use sp_runtime::{35 Permill, Perbill, Percent, create_runtime_str, generic, impl_opaque_keys,36 traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, AccountIdConversion, Zero},37 transaction_validity::{TransactionSource, TransactionValidity},38 ApplyExtrinsicResult, RuntimeAppPublic,39};4041use sp_std::prelude::*;4243#[cfg(feature = "std")]44use sp_version::NativeVersion;45use sp_version::RuntimeVersion;46pub use pallet_transaction_payment::{47 Multiplier, TargetedFeeAdjustment, FeeDetails, RuntimeDispatchInfo,48};49// A few exports that help ease life for downstream crates.50pub use pallet_balances::Call as BalancesCall;51pub use pallet_evm::{52 EnsureAddressTruncated, HashedAddressMapping, Runner, account::CrossAccountId as _,53};54pub use frame_support::{55 construct_runtime, match_types,56 dispatch::DispatchResult,57 PalletId, parameter_types, StorageValue, ConsensusEngineId,58 traits::{59 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,60 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,61 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,62 },63 weights::{64 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},65 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,66 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,67 },68};69use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};70use up_data_structs::{CollectionId, TokenId, CollectionStats, Collection};71// use pallet_contracts::weights::WeightInfo;72// #[cfg(any(feature = "std", test))]73use frame_system::{74 self as frame_system, EnsureRoot, EnsureSigned,75 limits::{BlockWeights, BlockLength},76};77use sp_arithmetic::{78 traits::{BaseArithmetic, Unsigned},79};80use smallvec::smallvec;81use codec::{Encode, Decode};82use pallet_evm::{Account as EVMAccount, FeeCalculator, GasWeightMapping};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};124125pub const RUNTIME_NAME: &str = "opal";126pub const TOKEN_SYMBOL: &str = "OPL";127128type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;129130impl RuntimeInstance for Runtime {131 type CrossAccountId = self::CrossAccountId;132 type TransactionConverter = self::TransactionConverter;133134 fn get_transaction_converter() -> TransactionConverter {135 TransactionConverter136 }137}138139/// The type for looking up accounts. We don't expect more than 4 billion of them, but you140/// never know...141pub type AccountIndex = u32;142143/// Balance of an account.144pub type Balance = u128;145146/// Index of a transaction in the chain.147pub type Index = u32;148149/// A hash of some data used by the chain.150pub type Hash = sp_core::H256;151152/// Digest item type.153pub type DigestItem = generic::DigestItem;154155/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know156/// the specifics of the runtime. They can then be made to be agnostic over specific formats157/// of data like extrinsics, allowing for them to continue syncing the network through upgrades158/// to even the core data structures.159pub mod opaque {160 use sp_std::prelude::*;161 use sp_runtime::impl_opaque_keys;162 use super::Aura;163164 pub use unique_runtime_common::types::*;165166 impl_opaque_keys! {167 pub struct SessionKeys {168 pub aura: Aura,169 }170 }171}172173/// This runtime version.174pub const VERSION: RuntimeVersion = RuntimeVersion {175 spec_name: create_runtime_str!(RUNTIME_NAME),176 impl_name: create_runtime_str!(RUNTIME_NAME),177 authoring_version: 1,178 spec_version: 920000,179 impl_version: 0,180 apis: RUNTIME_API_VERSIONS,181 transaction_version: 1,182 state_version: 0,183};184185#[derive(codec::Encode, codec::Decode)]186pub enum XCMPMessage<XAccountId, XBalance> {187 /// Transfer tokens to the given account from the Parachain account.188 TransferToken(XAccountId, XBalance),189}190191/// The version information used to identify this runtime when compiled natively.192#[cfg(feature = "std")]193pub fn native_version() -> NativeVersion {194 NativeVersion {195 runtime_version: VERSION,196 can_author_with: Default::default(),197 }198}199200type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;201202pub struct DealWithFees;203impl OnUnbalanced<NegativeImbalance> for DealWithFees {204 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {205 if let Some(fees) = fees_then_tips.next() {206 // for fees, 100% to treasury207 let mut split = fees.ration(100, 0);208 if let Some(tips) = fees_then_tips.next() {209 // for tips, if any, 100% to treasury210 tips.ration_merge_into(100, 0, &mut split);211 }212 Treasury::on_unbalanced(split.0);213 // Author::on_unbalanced(split.1);214 }215 }216}217218parameter_types! {219 pub const BlockHashCount: BlockNumber = 2400;220 pub RuntimeBlockLength: BlockLength =221 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);222 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);223 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;224 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()225 .base_block(BlockExecutionWeight::get())226 .for_class(DispatchClass::all(), |weights| {227 weights.base_extrinsic = ExtrinsicBaseWeight::get();228 })229 .for_class(DispatchClass::Normal, |weights| {230 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);231 })232 .for_class(DispatchClass::Operational, |weights| {233 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);234 // Operational transactions have some extra reserved space, so that they235 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.236 weights.reserved = Some(237 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT238 );239 })240 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)241 .build_or_panic();242 pub const Version: RuntimeVersion = VERSION;243 pub const SS58Prefix: u8 = 42;244}245246parameter_types! {247 pub const ChainId: u64 = 8882;248}249250pub struct FixedFee;251impl FeeCalculator for FixedFee {252 fn min_gas_price() -> U256 {253 MIN_GAS_PRICE.into()254 }255}256257// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case258// (contract, which only writes a lot of data),259// approximating on top of our real store write weight260parameter_types! {261 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;262 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;263 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();264}265266/// Limiting EVM execution to 50% of block for substrate users and management tasks267/// EVM transaction consumes more weight than substrate's, so we can't rely on them being268/// scheduled fairly269const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);270parameter_types! {271 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());272}273274pub enum FixedGasWeightMapping {}275impl GasWeightMapping for FixedGasWeightMapping {276 fn gas_to_weight(gas: u64) -> Weight {277 gas.saturating_mul(WeightPerGas::get())278 }279 fn weight_to_gas(weight: Weight) -> u64 {280 weight / WeightPerGas::get()281 }282}283284impl pallet_evm::account::Config for Runtime {285 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;286 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;287 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;288}289290impl pallet_evm::Config for Runtime {291 type BlockGasLimit = BlockGasLimit;292 type FeeCalculator = FixedFee;293 type GasWeightMapping = FixedGasWeightMapping;294 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;295 type CallOrigin = EnsureAddressTruncated;296 type WithdrawOrigin = EnsureAddressTruncated;297 type AddressMapping = HashedAddressMapping<Self::Hashing>;298 type PrecompilesType = ();299 type PrecompilesValue = ();300 type Currency = Balances;301 type Event = Event;302 type OnMethodCall = (303 pallet_evm_migration::OnMethodCall<Self>,304 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,305 CollectionDispatchT<Self>,306 );307 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;308 type ChainId = ChainId;309 type Runner = pallet_evm::runner::stack::Runner<Self>;310 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;311 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;312 type FindAuthor = EthereumFindAuthor<Aura>;313}314315impl pallet_evm_migration::Config for Runtime {316 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;317}318319pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);320impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {321 fn find_author<'a, I>(digests: I) -> Option<H160>322 where323 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,324 {325 if let Some(author_index) = F::find_author(digests) {326 let authority_id = Aura::authorities()[author_index as usize].clone();327 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));328 }329 None330 }331}332333impl pallet_ethereum::Config for Runtime {334 type Event = Event;335 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;336}337338impl pallet_randomness_collective_flip::Config for Runtime {}339340impl frame_system::Config for Runtime {341 /// The data to be stored in an account.342 type AccountData = pallet_balances::AccountData<Balance>;343 /// The identifier used to distinguish between accounts.344 type AccountId = AccountId;345 /// The basic call filter to use in dispatchable.346 type BaseCallFilter = Everything;347 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).348 type BlockHashCount = BlockHashCount;349 /// The maximum length of a block (in bytes).350 type BlockLength = RuntimeBlockLength;351 /// The index type for blocks.352 type BlockNumber = BlockNumber;353 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.354 type BlockWeights = RuntimeBlockWeights;355 /// The aggregated dispatch type that is available for extrinsics.356 type Call = Call;357 /// The weight of database operations that the runtime can invoke.358 type DbWeight = RocksDbWeight;359 /// The ubiquitous event type.360 type Event = Event;361 /// The type for hashing blocks and tries.362 type Hash = Hash;363 /// The hashing algorithm used.364 type Hashing = BlakeTwo256;365 /// The header type.366 type Header = generic::Header<BlockNumber, BlakeTwo256>;367 /// The index type for storing how many extrinsics an account has signed.368 type Index = Index;369 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.370 type Lookup = AccountIdLookup<AccountId, ()>;371 /// What to do if an account is fully reaped from the system.372 type OnKilledAccount = ();373 /// What to do if a new account is created.374 type OnNewAccount = ();375 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;376 /// The ubiquitous origin type.377 type Origin = Origin;378 /// This type is being generated by `construct_runtime!`.379 type PalletInfo = PalletInfo;380 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.381 type SS58Prefix = SS58Prefix;382 /// Weight information for the extrinsics of this pallet.383 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;384 /// Version of the runtime.385 type Version = Version;386 type MaxConsumers = ConstU32<16>;387}388389parameter_types! {390 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;391}392393impl pallet_timestamp::Config for Runtime {394 /// A timestamp: milliseconds since the unix epoch.395 type Moment = u64;396 type OnTimestampSet = ();397 type MinimumPeriod = MinimumPeriod;398 type WeightInfo = ();399}400401parameter_types! {402 // pub const ExistentialDeposit: u128 = 500;403 pub const ExistentialDeposit: u128 = 0;404 pub const MaxLocks: u32 = 50;405}406407impl pallet_balances::Config for Runtime {408 type MaxLocks = MaxLocks;409 type MaxReserves = ();410 type ReserveIdentifier = [u8; 8];411 /// The type for recording an account's balance.412 type Balance = Balance;413 /// The ubiquitous event type.414 type Event = Event;415 type DustRemoval = Treasury;416 type ExistentialDeposit = ExistentialDeposit;417 type AccountStore = System;418 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;419}420421pub const fn deposit(items: u32, bytes: u32) -> Balance {422 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE423}424425/*426parameter_types! {427 pub TombstoneDeposit: Balance = deposit(428 1,429 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,430 );431 pub DepositPerContract: Balance = TombstoneDeposit::get();432 pub const DepositPerStorageByte: Balance = deposit(0, 1);433 pub const DepositPerStorageItem: Balance = deposit(1, 0);434 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);435 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;436 pub const SignedClaimHandicap: u32 = 2;437 pub const MaxDepth: u32 = 32;438 pub const MaxValueSize: u32 = 16 * 1024;439 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb440 // The lazy deletion runs inside on_initialize.441 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *442 RuntimeBlockWeights::get().max_block;443 // The weight needed for decoding the queue should be less or equal than a fifth444 // of the overall weight dedicated to the lazy deletion.445 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (446 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -447 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)448 )) / 5) as u32;449 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();450}451452impl pallet_contracts::Config for Runtime {453 type Time = Timestamp;454 type Randomness = RandomnessCollectiveFlip;455 type Currency = Balances;456 type Event = Event;457 type RentPayment = ();458 type SignedClaimHandicap = SignedClaimHandicap;459 type TombstoneDeposit = TombstoneDeposit;460 type DepositPerContract = DepositPerContract;461 type DepositPerStorageByte = DepositPerStorageByte;462 type DepositPerStorageItem = DepositPerStorageItem;463 type RentFraction = RentFraction;464 type SurchargeReward = SurchargeReward;465 type WeightPrice = pallet_transaction_payment::Pallet<Self>;466 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;467 type ChainExtension = NFTExtension;468 type DeletionQueueDepth = DeletionQueueDepth;469 type DeletionWeightLimit = DeletionWeightLimit;470 type Schedule = Schedule;471 type CallStack = [pallet_contracts::Frame<Self>; 31];472}473*/474475parameter_types! {476 /// This value increases the priority of `Operational` transactions by adding477 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.478 pub const OperationalFeeMultiplier: u8 = 5;479}480481/// Linear implementor of `WeightToFeePolynomial`482pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);483484impl<T> WeightToFeePolynomial for LinearFee<T>485where486 T: BaseArithmetic + From<u32> + Copy + Unsigned,487{488 type Balance = T;489490 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {491 smallvec!(WeightToFeeCoefficient {492 // Targeting 0.1 Unique per NFT transfer493 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),494 coeff_frac: Perbill::zero(),495 negative: false,496 degree: 1,497 })498 }499}500501impl pallet_transaction_payment::Config for Runtime {502 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;503 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;504 type OperationalFeeMultiplier = OperationalFeeMultiplier;505 type WeightToFee = LinearFee<Balance>;506 type FeeMultiplierUpdate = ();507}508509parameter_types! {510 pub const ProposalBond: Permill = Permill::from_percent(5);511 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;512 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;513 pub const SpendPeriod: BlockNumber = 5 * MINUTES;514 pub const Burn: Permill = Permill::from_percent(0);515 pub const TipCountdown: BlockNumber = 1 * DAYS;516 pub const TipFindersFee: Percent = Percent::from_percent(20);517 pub const TipReportDepositBase: Balance = 1 * UNIQUE;518 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;519 pub const BountyDepositBase: Balance = 1 * UNIQUE;520 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;521 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");522 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;523 pub const MaximumReasonLength: u32 = 16384;524 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);525 pub const BountyValueMinimum: Balance = 5 * UNIQUE;526 pub const MaxApprovals: u32 = 100;527}528529impl pallet_treasury::Config for Runtime {530 type PalletId = TreasuryModuleId;531 type Currency = Balances;532 type ApproveOrigin = EnsureRoot<AccountId>;533 type RejectOrigin = EnsureRoot<AccountId>;534 type Event = Event;535 type OnSlash = ();536 type ProposalBond = ProposalBond;537 type ProposalBondMinimum = ProposalBondMinimum;538 type ProposalBondMaximum = ProposalBondMaximum;539 type SpendPeriod = SpendPeriod;540 type Burn = Burn;541 type BurnDestination = ();542 type SpendFunds = ();543 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;544 type MaxApprovals = MaxApprovals;545}546547impl pallet_sudo::Config for Runtime {548 type Event = Event;549 type Call = Call;550}551552pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);553554impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider555 for RelayChainBlockNumberProvider<T>556{557 type BlockNumber = BlockNumber;558559 fn current_block_number() -> Self::BlockNumber {560 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()561 .map(|d| d.relay_parent_number)562 .unwrap_or_default()563 }564}565566parameter_types! {567 pub const MinVestedTransfer: Balance = 10 * UNIQUE;568 pub const MaxVestingSchedules: u32 = 28;569}570571impl orml_vesting::Config for Runtime {572 type Event = Event;573 type Currency = pallet_balances::Pallet<Runtime>;574 type MinVestedTransfer = MinVestedTransfer;575 type VestedTransferOrigin = EnsureSigned<AccountId>;576 type WeightInfo = ();577 type MaxVestingSchedules = MaxVestingSchedules;578 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;579}580581parameter_types! {582 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;583 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;584}585586impl cumulus_pallet_parachain_system::Config for Runtime {587 type Event = Event;588 type SelfParaId = parachain_info::Pallet<Self>;589 type OnSystemEvent = ();590 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<591 // MaxDownwardMessageWeight,592 // XcmExecutor<XcmConfig>,593 // Call,594 // >;595 type OutboundXcmpMessageSource = XcmpQueue;596 type DmpMessageHandler = DmpQueue;597 type ReservedDmpWeight = ReservedDmpWeight;598 type ReservedXcmpWeight = ReservedXcmpWeight;599 type XcmpMessageHandler = XcmpQueue;600}601602impl parachain_info::Config for Runtime {}603604impl cumulus_pallet_aura_ext::Config for Runtime {}605606parameter_types! {607 pub const RelayLocation: MultiLocation = MultiLocation::parent();608 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;609 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();610 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();611}612613/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used614/// when determining ownership of accounts for asset transacting and when attempting to use XCM615/// `Transact` in order to determine the dispatch Origin.616pub type LocationToAccountId = (617 // The parent (Relay-chain) origin converts to the default `AccountId`.618 ParentIsPreset<AccountId>,619 // Sibling parachain origins convert to AccountId via the `ParaId::into`.620 SiblingParachainConvertsVia<Sibling, AccountId>,621 // Straight up local `AccountId32` origins just alias directly to `AccountId`.622 AccountId32Aliases<RelayNetwork, AccountId>,623);624625pub struct OnlySelfCurrency;626impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {627 fn matches_fungible(a: &MultiAsset) -> Option<B> {628 match (&a.id, &a.fun) {629 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),630 _ => None,631 }632 }633}634635/// Means for transacting assets on this chain.636pub type LocalAssetTransactor = CurrencyAdapter<637 // Use this currency:638 Balances,639 // Use this currency when it is a fungible asset matching the given location or name:640 OnlySelfCurrency,641 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:642 LocationToAccountId,643 // Our chain's account ID type (we can't get away without mentioning it explicitly):644 AccountId,645 // We don't track any teleports.646 (),647>;648649/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,650/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can651/// biases the kind of local `Origin` it will become.652pub type XcmOriginToTransactDispatchOrigin = (653 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location654 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for655 // foreign chains who want to have a local sovereign account on this chain which they control.656 SovereignSignedViaLocation<LocationToAccountId, Origin>,657 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when658 // recognised.659 RelayChainAsNative<RelayOrigin, Origin>,660 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when661 // recognised.662 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,663 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a664 // transaction from the Root origin.665 ParentAsSuperuser<Origin>,666 // Native signed account converter; this just converts an `AccountId32` origin into a normal667 // `Origin::Signed` origin of the same 32-byte value.668 SignedAccountId32AsNative<RelayNetwork, Origin>,669 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.670 XcmPassthrough<Origin>,671);672673parameter_types! {674 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.675 pub UnitWeightCost: Weight = 1_000_000;676 // 1200 UNIQUEs buy 1 second of weight.677 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);678 pub const MaxInstructions: u32 = 100;679 pub const MaxAuthorities: u32 = 100_000;680}681682match_types! {683 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {684 MultiLocation { parents: 1, interior: Here } |685 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }686 };687}688689pub type Barrier = (690 TakeWeightCredit,691 AllowTopLevelPaidExecutionFrom<Everything>,692 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,693 // ^^^ Parent & its unit plurality gets free execution694);695696pub struct UsingOnlySelfCurrencyComponents<697 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,698 AssetId: Get<MultiLocation>,699 AccountId,700 Currency: CurrencyT<AccountId>,701 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,702>(703 Weight,704 Currency::Balance,705 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,706);707impl<708 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,709 AssetId: Get<MultiLocation>,710 AccountId,711 Currency: CurrencyT<AccountId>,712 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,713 > WeightTrader714 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>715{716 fn new() -> Self {717 Self(0, Zero::zero(), PhantomData)718 }719720 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {721 let amount = WeightToFee::calc(&weight);722 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;723724 // location to this parachain through relay chain725 let option1: xcm::v1::AssetId = Concrete(MultiLocation {726 parents: 1,727 interior: X1(Parachain(ParachainInfo::parachain_id().into())),728 });729 // direct location730 let option2: xcm::v1::AssetId = Concrete(MultiLocation {731 parents: 0,732 interior: Here,733 });734735 let required = if payment.fungible.contains_key(&option1) {736 (option1, u128_amount).into()737 } else if payment.fungible.contains_key(&option2) {738 (option2, u128_amount).into()739 } else {740 (Concrete(MultiLocation::default()), u128_amount).into()741 };742743 let unused = payment744 .checked_sub(required)745 .map_err(|_| XcmError::TooExpensive)?;746 self.0 = self.0.saturating_add(weight);747 self.1 = self.1.saturating_add(amount);748 Ok(unused)749 }750751 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {752 let weight = weight.min(self.0);753 let amount = WeightToFee::calc(&weight);754 self.0 -= weight;755 self.1 = self.1.saturating_sub(amount);756 let amount: u128 = amount.saturated_into();757 if amount > 0 {758 Some((AssetId::get(), amount).into())759 } else {760 None761 }762 }763}764impl<765 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,766 AssetId: Get<MultiLocation>,767 AccountId,768 Currency: CurrencyT<AccountId>,769 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,770 > Drop771 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>772{773 fn drop(&mut self) {774 OnUnbalanced::on_unbalanced(Currency::issue(self.1));775 }776}777778pub struct XcmConfig;779impl Config for XcmConfig {780 type Call = Call;781 type XcmSender = XcmRouter;782 // How to withdraw and deposit an asset.783 type AssetTransactor = LocalAssetTransactor;784 type OriginConverter = XcmOriginToTransactDispatchOrigin;785 type IsReserve = NativeAsset;786 type IsTeleporter = (); // Teleportation is disabled787 type LocationInverter = LocationInverter<Ancestry>;788 type Barrier = Barrier;789 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;790 type Trader = UsingOnlySelfCurrencyComponents<791 IdentityFee<Balance>,792 RelayLocation,793 AccountId,794 Balances,795 (),796 >;797 type ResponseHandler = (); // Don't handle responses for now.798 type SubscriptionService = PolkadotXcm;799800 type AssetTrap = PolkadotXcm;801 type AssetClaims = PolkadotXcm;802}803804// parameter_types! {805// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;806// }807808/// No local origins on this chain are allowed to dispatch XCM sends/executions.809pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);810811/// The means for routing XCM messages which are not for local execution into the right message812/// queues.813pub type XcmRouter = (814 // Two routers - use UMP to communicate with the relay chain:815 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,816 // ..and XCMP to communicate with the sibling chains.817 XcmpQueue,818);819820impl pallet_evm_coder_substrate::Config for Runtime {821 type EthereumTransactionSender = pallet_ethereum::Pallet<Self>;822 type GasWeightMapping = FixedGasWeightMapping;823}824825impl pallet_xcm::Config for Runtime {826 type Event = Event;827 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;828 type XcmRouter = XcmRouter;829 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;830 type XcmExecuteFilter = Everything;831 type XcmExecutor = XcmExecutor<XcmConfig>;832 type XcmTeleportFilter = Everything;833 type XcmReserveTransferFilter = Everything;834 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;835 type LocationInverter = LocationInverter<Ancestry>;836 type Origin = Origin;837 type Call = Call;838 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;839 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;840}841842impl cumulus_pallet_xcm::Config for Runtime {843 type Event = Event;844 type XcmExecutor = XcmExecutor<XcmConfig>;845}846847impl cumulus_pallet_xcmp_queue::Config for Runtime {848 type WeightInfo = ();849 type Event = Event;850 type XcmExecutor = XcmExecutor<XcmConfig>;851 type ChannelInfo = ParachainSystem;852 type VersionWrapper = ();853 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;854 type ControllerOrigin = EnsureRoot<AccountId>;855 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;856}857858impl cumulus_pallet_dmp_queue::Config for Runtime {859 type Event = Event;860 type XcmExecutor = XcmExecutor<XcmConfig>;861 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;862}863864impl pallet_aura::Config for Runtime {865 type AuthorityId = AuraId;866 type DisabledValidators = ();867 type MaxAuthorities = MaxAuthorities;868}869870parameter_types! {871 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();872 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;873}874875impl pallet_common::Config for Runtime {876 type Event = Event;877 type Currency = Balances;878 type CollectionCreationPrice = CollectionCreationPrice;879 type TreasuryAccountId = TreasuryAccountId;880 type CollectionDispatch = CollectionDispatchT<Self>;881882 type EvmTokenAddressMapping = EvmTokenAddressMapping;883 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;884}885886impl pallet_structure::Config for Runtime {887 type Event = Event;888 type Call = Call;889 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;890}891892impl pallet_fungible::Config for Runtime {893 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;894}895impl pallet_refungible::Config for Runtime {896 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;897}898impl pallet_nonfungible::Config for Runtime {899 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;900}901902impl pallet_unique::Config for Runtime {903 type Event = Event;904 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;905}906907parameter_types! {908 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied909}910911/// Used for the pallet inflation912impl pallet_inflation::Config for Runtime {913 type Currency = Balances;914 type TreasuryAccountId = TreasuryAccountId;915 type InflationBlockInterval = InflationBlockInterval;916 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;917}918919// parameter_types! {920// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *921// RuntimeBlockWeights::get().max_block;922// pub const MaxScheduledPerBlock: u32 = 50;923// }924925type EvmSponsorshipHandler = (926 pallet_unique::UniqueEthSponsorshipHandler<Runtime>,927 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,928);929type SponsorshipHandler = (930 pallet_unique::UniqueSponsorshipHandler<Runtime>,931 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,932 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,933);934935// impl pallet_unq_scheduler::Config for Runtime {936// type Event = Event;937// type Origin = Origin;938// type PalletsOrigin = OriginCaller;939// type Call = Call;940// type MaximumWeight = MaximumSchedulerWeight;941// type ScheduleOrigin = EnsureSigned<AccountId>;942// type MaxScheduledPerBlock = MaxScheduledPerBlock;943// type SponsorshipHandler = SponsorshipHandler;944// type WeightInfo = ();945// }946947impl pallet_evm_transaction_payment::Config for Runtime {948 type EvmSponsorshipHandler = EvmSponsorshipHandler;949 type Currency = Balances;950}951952impl pallet_charge_transaction::Config for Runtime {953 type SponsorshipHandler = SponsorshipHandler;954}955956// impl pallet_contract_helpers::Config for Runtime {957// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;958// }959960parameter_types! {961 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049962 pub const HelpersContractAddress: H160 = H160([963 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,964 ]);965}966967impl pallet_evm_contract_helpers::Config for Runtime {968 type ContractAddress = HelpersContractAddress;969 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;970}971972construct_runtime!(973 pub enum Runtime where974 Block = Block,975 NodeBlock = opaque::Block,976 UncheckedExtrinsic = UncheckedExtrinsic977 {978 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,979 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,980981 Aura: pallet_aura::{Pallet, Config<T>} = 22,982 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,983984 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,985 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,986 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,987 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,988 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,989 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,990 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,991 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,992 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,993 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,994995 // XCM helpers.996 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,997 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,998 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,999 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10001001 // Unique Pallets1002 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1003 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1004 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1005 // free = 631006 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1007 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1008 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1009 Fungible: pallet_fungible::{Pallet, Storage} = 67,1010 Refungible: pallet_refungible::{Pallet, Storage} = 68,1011 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,10121013 // Frontier1014 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1015 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10161017 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1018 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1019 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1020 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1021 }1022);10231024pub struct TransactionConverter;10251026impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1027 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1028 UncheckedExtrinsic::new_unsigned(1029 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1030 )1031 }1032}10331034impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1035 fn convert_transaction(1036 &self,1037 transaction: pallet_ethereum::Transaction,1038 ) -> opaque::UncheckedExtrinsic {1039 let extrinsic = UncheckedExtrinsic::new_unsigned(1040 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1041 );1042 let encoded = extrinsic.encode();1043 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1044 .expect("Encoded extrinsic is always valid")1045 }1046}10471048/// The address format for describing accounts.1049pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1050/// Block header type as expected by this runtime.1051pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1052/// Block type as expected by this runtime.1053pub type Block = generic::Block<Header, UncheckedExtrinsic>;1054/// A Block signed with a Justification1055pub type SignedBlock = generic::SignedBlock<Block>;1056/// BlockId type as expected by this runtime.1057pub type BlockId = generic::BlockId<Block>;1058/// The SignedExtension to the basic transaction logic.1059pub type SignedExtra = (1060 frame_system::CheckSpecVersion<Runtime>,1061 // system::CheckTxVersion<Runtime>,1062 frame_system::CheckGenesis<Runtime>,1063 frame_system::CheckEra<Runtime>,1064 frame_system::CheckNonce<Runtime>,1065 frame_system::CheckWeight<Runtime>,1066 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1067 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1068);1069/// Unchecked extrinsic type as expected by this runtime.1070pub type UncheckedExtrinsic =1071 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1072/// Extrinsic type that has already been checked.1073pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1074/// Executive: handles dispatch to the various modules.1075pub type Executive = frame_executive::Executive<1076 Runtime,1077 Block,1078 frame_system::ChainContext<Runtime>,1079 Runtime,1080 AllPalletsReversedWithSystemFirst,1081>;10821083impl_opaque_keys! {1084 pub struct SessionKeys {1085 pub aura: Aura,1086 }1087}10881089impl fp_self_contained::SelfContainedCall for Call {1090 type SignedInfo = H160;10911092 fn is_self_contained(&self) -> bool {1093 match self {1094 Call::Ethereum(call) => call.is_self_contained(),1095 _ => false,1096 }1097 }10981099 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1100 match self {1101 Call::Ethereum(call) => call.check_self_contained(),1102 _ => None,1103 }1104 }11051106 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1107 match self {1108 Call::Ethereum(call) => call.validate_self_contained(info),1109 _ => None,1110 }1111 }11121113 fn pre_dispatch_self_contained(1114 &self,1115 info: &Self::SignedInfo,1116 ) -> Option<Result<(), TransactionValidityError>> {1117 match self {1118 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1119 _ => None,1120 }1121 }11221123 fn apply_self_contained(1124 self,1125 info: Self::SignedInfo,1126 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1127 match self {1128 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1129 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1130 )),1131 _ => None,1132 }1133 }1134}11351136macro_rules! dispatch_unique_runtime {1137 ($collection:ident.$method:ident($($name:ident),*)) => {{1138 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1139 let dispatch = collection.as_dyn();11401141 Ok(dispatch.$method($($name),*))1142 }};1143}11441145impl_common_runtime_apis!();11461147struct CheckInherents;11481149impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1150 fn check_inherents(1151 block: &Block,1152 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1153 ) -> sp_inherents::CheckInherentsResult {1154 let relay_chain_slot = relay_state_proof1155 .read_slot()1156 .expect("Could not read the relay chain slot from the proof");11571158 let inherent_data =1159 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1160 relay_chain_slot,1161 sp_std::time::Duration::from_secs(6),1162 )1163 .create_inherent_data()1164 .expect("Could not create the timestamp inherent data");11651166 inherent_data.check_extrinsics(block)1167 }1168}11691170cumulus_pallet_parachain_system::register_validate_block!(1171 Runtime = Runtime,1172 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1173 CheckInherents = CheckInherents,1174);tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -56,13 +56,27 @@
}
}
-export function collectionIdToAddress(address: number): string {
- if (address >= 0xffffffff || address < 0) throw new Error('id overflow');
+function encodeIntBE(v: number): number[] {
+ if (v >= 0xffffffff || v < 0) throw new Error('id overflow');
+ return [
+ v >> 24,
+ (v >> 16) & 0xff,
+ (v >> 8) & 0xff,
+ v & 0xff,
+ ];
+}
+
+export function collectionIdToAddress(collection: number): string {
const buf = Buffer.from([0x17, 0xc4, 0xe6, 0x45, 0x3c, 0xc4, 0x9a, 0xaa, 0xae, 0xac, 0xa8, 0x94, 0xe6, 0xd9, 0x68, 0x3e,
- address >> 24,
- (address >> 16) & 0xff,
- (address >> 8) & 0xff,
- address & 0xff,
+ ...encodeIntBE(collection),
+ ]);
+ return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
+}
+
+export function tokenIdToAddress(collection: number, token: number): string {
+ const buf = Buffer.from([0xf8, 0x23, 0x8c, 0xcf, 0xff, 0x8e, 0xd8, 0x87, 0x46, 0x3f, 0xd5, 0xe0,
+ ...encodeIntBE(collection),
+ ...encodeIntBE(token),
]);
return Web3.utils.toChecksumAddress('0x' + buf.toString('hex'));
}