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);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'));
}