difftreelog
CORE-345 Split evm collection to collection and helper
in: master
16 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -18,6 +18,9 @@
COLLECTION_STUBS=./pallets/unique/src/eth/stubs/
COLLECTION_ABI=./tests/src/eth/collectionAbi.json
+COLLECTION_HELPER_STUBS=$(COLLECTION_STUBS)
+COLLECTION_HELPER_ABI=./tests/src/eth/collectionHelperAbi.json
+
TESTS_API=./tests/src/eth/api/
.PHONY: regenerate_solidity
@@ -36,9 +39,13 @@
PACKAGE=pallet-evm-contract-helpers NAME=eth::contract_helpers_impl OUTPUT=$(CONTRACT_HELPERS_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
Collection.sol:
- PACKAGE=pallet-unique NAME=eth::pallet_evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
- PACKAGE=pallet-unique NAME=eth::pallet_evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-unique NAME=eth::evm_collection::collection_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-unique NAME=eth::evm_collection::collection_impl OUTPUT=$(COLLECTION_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+CollectionHelper.sol:
+ PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_iface OUTPUT=$(TESTS_API)/$@ ./.maintain/scripts/generate_sol.sh
+ PACKAGE=pallet-unique NAME=eth::evm_collection::collection_helper_impl OUTPUT=$(COLLECTION_HELPER_STUBS)/$@ ./.maintain/scripts/generate_sol.sh
+
UniqueFungible: UniqueFungible.sol
INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_STUBS)/UniqueFungible.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(FUNGIBLE_EVM_STUBS)/$< OUTPUT=$(FUNGIBLE_EVM_ABI) ./.maintain/scripts/generate_abi.sh
@@ -55,7 +62,11 @@
INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_STUBS)/Collection.raw ./.maintain/scripts/compile_stub.sh
INPUT=$(COLLECTION_STUBS)/$< OUTPUT=$(COLLECTION_ABI) ./.maintain/scripts/generate_abi.sh
-evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection
+CollectionHelper: CollectionHelper.sol
+ INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_STUBS)/CollectionHelper.raw ./.maintain/scripts/compile_stub.sh
+ INPUT=$(COLLECTION_HELPER_STUBS)/$< OUTPUT=$(COLLECTION_HELPER_ABI) ./.maintain/scripts/generate_abi.sh
+
+evm_stubs: UniqueFungible UniqueNFT ContractHelpers Collection CollectionHelper
.PHONY: _bench
_bench:
pallets/unique/src/eth/mod.rsdiffbeforeafterboth--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -112,7 +112,6 @@
use sp_std::{vec::Vec, rc::Rc};
use alloc::format;
- // #[pallet::config]
pub trait Config:
frame_system::Config
+ pallet_evm_coder_substrate::Config
@@ -122,8 +121,8 @@
type ContractAddress: Get<H160>;
}
- struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
- impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+ struct EvmCollectionHelper<T: Config>(Rc<SubstrateRecorder<T>>);
+ impl<T: Config> WithRecorder<T> for EvmCollectionHelper<T> {
fn recorder(&self) -> &SubstrateRecorder<T> {
&self.0
}
@@ -132,19 +131,9 @@
self.0
}
}
-
- #[derive(ToLog)]
- pub enum EthCollectionEvent {
- CollectionCreated {
- #[indexed]
- owner: address,
- #[indexed]
- collection_id: address,
- },
- }
-
- #[solidity_interface(name = "Collection")]
- impl<T: Config> EvmCollection<T> {
+
+ #[solidity_interface(name = "CollectionHelper")]
+ impl<T: Config> EvmCollectionHelper<T> {
fn create_721_collection(
&self,
caller: caller,
@@ -188,14 +177,37 @@
});
Ok(address)
}
+ }
+
+ struct EvmCollection<T: Config>(Rc<SubstrateRecorder<T>>);
+ impl<T: Config> WithRecorder<T> for EvmCollection<T> {
+ fn recorder(&self) -> &SubstrateRecorder<T> {
+ &self.0
+ }
+
+ fn into_recorder(self) -> Rc<SubstrateRecorder<T>> {
+ self.0
+ }
+ }
+
+ #[derive(ToLog)]
+ pub enum EthCollectionEvent {
+ CollectionCreated {
+ #[indexed]
+ owner: address,
+ #[indexed]
+ collection_id: address,
+ },
+ }
+ #[solidity_interface(name = "Collection")]
+ impl<T: Config> EvmCollection<T> {
fn set_sponsor(
&self,
caller: caller,
- collection_address: address,
sponsor: address,
) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
check_is_owner(caller, &collection)?;
let sponsor = T::CrossAccountId::from_eth(sponsor);
@@ -203,8 +215,8 @@
save_eth(collection)
}
- fn confirm_sponsorship(&self, caller: caller, collection_address: address) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ fn confirm_sponsorship(&self, caller: caller) -> Result<void> {
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
let caller = T::CrossAccountId::from_eth(caller);
if !collection.confirm_sponsorship(caller.as_sub()) {
return Err(Error::Revert("Caller is not set as sponsor".into()));
@@ -215,10 +227,9 @@
fn set_limits(
&self,
caller: caller,
- collection_address: address,
limits_json: string,
) -> Result<void> {
- let mut collection = collection_from_address(collection_address, &self.0)?;
+ let mut collection = collection_from_address(self.contract_address(caller).unwrap(), &self.0)?;
check_is_owner(caller, &collection)?;
let limits = serde_json_core::from_str(limits_json.as_ref())
@@ -226,6 +237,10 @@
collection.limits = limits.0;
save_eth(collection)
}
+
+ fn contract_address(&self, _caller: caller) -> Result<address> {
+ Ok(self.0.contract())
+ }
}
fn error_feild_too_long(feild: &str, bound: u32) -> Error {
@@ -251,9 +266,9 @@
.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
Ok(())
}
-
- pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
- impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
+
+ pub struct CollectionHelperOnMethodCall<T: Config>(PhantomData<*const T>);
+ impl<T: Config> OnMethodCall<T> for CollectionHelperOnMethodCall<T> {
fn is_reserved(contract: &sp_core::H160) -> bool {
contract == &T::ContractAddress::get()
}
@@ -273,6 +288,36 @@
return None;
}
+ let helpers = EvmCollectionHelper::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
+ pallet_evm_coder_substrate::call(*source, helpers, value, input)
+ }
+
+ fn get_code(contract: &sp_core::H160) -> Option<Vec<u8>> {
+ (contract == &T::ContractAddress::get())
+ .then(|| include_bytes!("./stubs/CollectionHelper.raw").to_vec())
+ }
+ }
+
+ generate_stubgen!(collection_helper_impl, CollectionHelperCall<()>, true);
+ generate_stubgen!(collection_helper_iface, CollectionHelperCall<()>, false);
+
+ pub struct CollectionOnMethodCall<T: Config>(PhantomData<*const T>);
+ impl<T: Config> OnMethodCall<T> for CollectionOnMethodCall<T> {
+ fn is_reserved(contract: &sp_core::H160) -> bool {
+ contract == &T::ContractAddress::get()
+ }
+
+ fn is_used(contract: &sp_core::H160) -> bool {
+ contract == &T::ContractAddress::get()
+ }
+
+ fn call(
+ source: &sp_core::H160,
+ target: &sp_core::H160,
+ gas_left: u64,
+ input: &[u8],
+ value: sp_core::U256,
+ ) -> Option<PrecompileResult> {
let helpers = EvmCollection::<T>(Rc::new(SubstrateRecorder::<T>::new(*target, gas_left)));
pallet_evm_coder_substrate::call(*source, helpers, value, input)
}
pallets/unique/src/eth/stubs/Collection.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/Collection.soldiffbeforeafterboth--- a/pallets/unique/src/eth/stubs/Collection.sol
+++ b/pallets/unique/src/eth/stubs/Collection.sol
@@ -21,48 +21,32 @@
}
}
-// Selector: 1e95830f
+// Selector: 15cc740e
contract Collection is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) public view returns (address) {
+ // Selector: setSponsor(address) 59753fb1
+ function setSponsor(address sponsor) public view {
require(false, stub_error);
- name;
- description;
- tokenPrefix;
+ sponsor;
dummy;
- return 0x0000000000000000000000000000000000000000;
}
- // Selector: setSponsor(address,address) f01fba93
- function setSponsor(address collectionAddress, address sponsor)
- public
- view
- {
+ // Selector: confirmSponsorship() c8c6a056
+ function confirmSponsorship() public view {
require(false, stub_error);
- collectionAddress;
- sponsor;
dummy;
}
- // Selector: confirmSponsorship(address) abc00001
- function confirmSponsorship(address collectionAddress) public view {
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) public view {
require(false, stub_error);
- collectionAddress;
+ limitsJson;
dummy;
}
- // Selector: setLimits(address,string) d05638cc
- function setLimits(address collectionAddress, string memory limitsJson)
- public
- view
- {
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() public view returns (address) {
require(false, stub_error);
- collectionAddress;
- limitsJson;
dummy;
+ return 0x0000000000000000000000000000000000000000;
}
}
pallets/unique/src/eth/stubs/CollectionHelper.rawdiffbeforeafterbothbinary blob — no preview
pallets/unique/src/eth/stubs/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/pallets/unique/src/eth/stubs/CollectionHelper.sol
@@ -0,0 +1,39 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+contract Dummy {
+ uint8 dummy;
+ string stub_error = "this contract is implemented in native";
+}
+
+contract ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID)
+ external
+ view
+ returns (bool)
+ {
+ require(false, stub_error);
+ interfaceID;
+ return true;
+ }
+}
+
+// Selector: 951c0151
+contract CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) public view returns (address) {
+ require(false, stub_error);
+ name;
+ description;
+ tokenPrefix;
+ dummy;
+ return 0x0000000000000000000000000000000000000000;
+ }
+}
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 _, OnMethodCall,53 Account as EVMAccount, FeeCalculator, GasWeightMapping,54};55pub use frame_support::{56 construct_runtime, match_types,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,68 },69};70use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};71use up_data_structs::*;72// use pallet_contracts::weights::WeightInfo;73// #[cfg(any(feature = "std", test))]74use frame_system::{75 self as frame_system, EnsureRoot, EnsureSigned,76 limits::{BlockWeights, BlockLength},77};78use sp_arithmetic::{79 traits::{BaseArithmetic, Unsigned},80};81use smallvec::smallvec;82use codec::{Encode, Decode};83use pallet_unique::eth::evm_collection;84use fp_rpc::TransactionStatus;85use sp_runtime::{86 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},87 transaction_validity::TransactionValidityError,88 SaturatedConversion,89};9091// pub use pallet_timestamp::Call as TimestampCall;92pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9394// Polkadot imports95use pallet_xcm::XcmPassthrough;96use polkadot_parachain::primitives::Sibling;97use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};98use xcm_builder::{99 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,100 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,101 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,102 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,103 ParentIsPreset,104};105use xcm_executor::{Config, XcmExecutor, Assets};106use sp_std::{marker::PhantomData};107108use xcm::latest::{109 // Xcm,110 AssetId::{Concrete},111 Fungibility::Fungible as XcmFungible,112 MultiAsset,113 Error as XcmError,114};115use xcm_executor::traits::{MatchesFungible, WeightTrader};116//use xcm_executor::traits::MatchesFungible;117use sp_runtime::traits::CheckedConversion;118119use unique_runtime_common::{120 impl_common_runtime_apis,121 types::*,122 constants::*,123 dispatch::{CollectionDispatchT, CollectionDispatch},124 sponsoring::UniqueSponsorshipHandler,125 eth_sponsoring::UniqueEthSponsorshipHandler,126 weights::CommonWeights,127};128129pub const RUNTIME_NAME: &str = "opal";130pub const TOKEN_SYMBOL: &str = "OPL";131132type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;133134impl RuntimeInstance for Runtime {135 type CrossAccountId = self::CrossAccountId;136 type TransactionConverter = self::TransactionConverter;137138 fn get_transaction_converter() -> TransactionConverter {139 TransactionConverter140 }141}142143/// The type for looking up accounts. We don't expect more than 4 billion of them, but you144/// never know...145pub type AccountIndex = u32;146147/// Balance of an account.148pub type Balance = u128;149150/// Index of a transaction in the chain.151pub type Index = u32;152153/// A hash of some data used by the chain.154pub type Hash = sp_core::H256;155156/// Digest item type.157pub type DigestItem = generic::DigestItem;158159/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know160/// the specifics of the runtime. They can then be made to be agnostic over specific formats161/// of data like extrinsics, allowing for them to continue syncing the network through upgrades162/// to even the core data structures.163pub mod opaque {164 use sp_std::prelude::*;165 use sp_runtime::impl_opaque_keys;166 use super::Aura;167168 pub use unique_runtime_common::types::*;169170 impl_opaque_keys! {171 pub struct SessionKeys {172 pub aura: Aura,173 }174 }175}176177/// This runtime version.178pub const VERSION: RuntimeVersion = RuntimeVersion {179 spec_name: create_runtime_str!(RUNTIME_NAME),180 impl_name: create_runtime_str!(RUNTIME_NAME),181 authoring_version: 1,182 spec_version: 920000,183 impl_version: 0,184 apis: RUNTIME_API_VERSIONS,185 transaction_version: 1,186 state_version: 0,187};188189#[derive(codec::Encode, codec::Decode)]190pub enum XCMPMessage<XAccountId, XBalance> {191 /// Transfer tokens to the given account from the Parachain account.192 TransferToken(XAccountId, XBalance),193}194195/// The version information used to identify this runtime when compiled natively.196#[cfg(feature = "std")]197pub fn native_version() -> NativeVersion {198 NativeVersion {199 runtime_version: VERSION,200 can_author_with: Default::default(),201 }202}203204type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;205206pub struct DealWithFees;207impl OnUnbalanced<NegativeImbalance> for DealWithFees {208 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {209 if let Some(fees) = fees_then_tips.next() {210 // for fees, 100% to treasury211 let mut split = fees.ration(100, 0);212 if let Some(tips) = fees_then_tips.next() {213 // for tips, if any, 100% to treasury214 tips.ration_merge_into(100, 0, &mut split);215 }216 Treasury::on_unbalanced(split.0);217 // Author::on_unbalanced(split.1);218 }219 }220}221222parameter_types! {223 pub const BlockHashCount: BlockNumber = 2400;224 pub RuntimeBlockLength: BlockLength =225 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);226 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);227 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;228 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()229 .base_block(BlockExecutionWeight::get())230 .for_class(DispatchClass::all(), |weights| {231 weights.base_extrinsic = ExtrinsicBaseWeight::get();232 })233 .for_class(DispatchClass::Normal, |weights| {234 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);235 })236 .for_class(DispatchClass::Operational, |weights| {237 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);238 // Operational transactions have some extra reserved space, so that they239 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.240 weights.reserved = Some(241 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT242 );243 })244 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)245 .build_or_panic();246 pub const Version: RuntimeVersion = VERSION;247 pub const SS58Prefix: u8 = 42;248}249250parameter_types! {251 pub const ChainId: u64 = 8882;252}253254pub struct FixedFee;255impl FeeCalculator for FixedFee {256 fn min_gas_price() -> U256 {257 MIN_GAS_PRICE.into()258 }259}260261// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case262// (contract, which only writes a lot of data),263// approximating on top of our real store write weight264parameter_types! {265 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;266 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;267 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();268}269270/// Limiting EVM execution to 50% of block for substrate users and management tasks271/// EVM transaction consumes more weight than substrate's, so we can't rely on them being272/// scheduled fairly273const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);274parameter_types! {275 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());276}277278pub enum FixedGasWeightMapping {}279impl GasWeightMapping for FixedGasWeightMapping {280 fn gas_to_weight(gas: u64) -> Weight {281 gas.saturating_mul(WeightPerGas::get())282 }283 fn weight_to_gas(weight: Weight) -> u64 {284 weight / WeightPerGas::get()285 }286}287288impl pallet_evm::account::Config for Runtime {289 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;290 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;291 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;292}293294impl pallet_evm::Config for Runtime {295 type BlockGasLimit = BlockGasLimit;296 type FeeCalculator = FixedFee;297 type GasWeightMapping = FixedGasWeightMapping;298 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;299 type CallOrigin = EnsureAddressTruncated<Self>;300 type WithdrawOrigin = EnsureAddressTruncated<Self>;301 type AddressMapping = HashedAddressMapping<Self::Hashing>;302 type PrecompilesType = ();303 type PrecompilesValue = ();304 type Currency = Balances;305 type Event = Event;306 type OnMethodCall = (307 pallet_evm_migration::OnMethodCall<Self>,308 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,309 CollectionDispatchT<Self>,310 evm_collection::CollectionOnMethodCall<Self>,311 );312 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;313 type ChainId = ChainId;314 type Runner = pallet_evm::runner::stack::Runner<Self>;315 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;316 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;317 type FindAuthor = EthereumFindAuthor<Aura>;318}319320impl pallet_evm_migration::Config for Runtime {321 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;322}323324pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);325impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {326 fn find_author<'a, I>(digests: I) -> Option<H160>327 where328 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,329 {330 if let Some(author_index) = F::find_author(digests) {331 let authority_id = Aura::authorities()[author_index as usize].clone();332 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));333 }334 None335 }336}337338impl pallet_ethereum::Config for Runtime {339 type Event = Event;340 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;341}342343impl pallet_randomness_collective_flip::Config for Runtime {}344345impl frame_system::Config for Runtime {346 /// The data to be stored in an account.347 type AccountData = pallet_balances::AccountData<Balance>;348 /// The identifier used to distinguish between accounts.349 type AccountId = AccountId;350 /// The basic call filter to use in dispatchable.351 type BaseCallFilter = Everything;352 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).353 type BlockHashCount = BlockHashCount;354 /// The maximum length of a block (in bytes).355 type BlockLength = RuntimeBlockLength;356 /// The index type for blocks.357 type BlockNumber = BlockNumber;358 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.359 type BlockWeights = RuntimeBlockWeights;360 /// The aggregated dispatch type that is available for extrinsics.361 type Call = Call;362 /// The weight of database operations that the runtime can invoke.363 type DbWeight = RocksDbWeight;364 /// The ubiquitous event type.365 type Event = Event;366 /// The type for hashing blocks and tries.367 type Hash = Hash;368 /// The hashing algorithm used.369 type Hashing = BlakeTwo256;370 /// The header type.371 type Header = generic::Header<BlockNumber, BlakeTwo256>;372 /// The index type for storing how many extrinsics an account has signed.373 type Index = Index;374 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.375 type Lookup = AccountIdLookup<AccountId, ()>;376 /// What to do if an account is fully reaped from the system.377 type OnKilledAccount = ();378 /// What to do if a new account is created.379 type OnNewAccount = ();380 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;381 /// The ubiquitous origin type.382 type Origin = Origin;383 /// This type is being generated by `construct_runtime!`.384 type PalletInfo = PalletInfo;385 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.386 type SS58Prefix = SS58Prefix;387 /// Weight information for the extrinsics of this pallet.388 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;389 /// Version of the runtime.390 type Version = Version;391 type MaxConsumers = ConstU32<16>;392}393394parameter_types! {395 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;396}397398impl pallet_timestamp::Config for Runtime {399 /// A timestamp: milliseconds since the unix epoch.400 type Moment = u64;401 type OnTimestampSet = ();402 type MinimumPeriod = MinimumPeriod;403 type WeightInfo = ();404}405406parameter_types! {407 // pub const ExistentialDeposit: u128 = 500;408 pub const ExistentialDeposit: u128 = 0;409 pub const MaxLocks: u32 = 50;410}411412impl pallet_balances::Config for Runtime {413 type MaxLocks = MaxLocks;414 type MaxReserves = ();415 type ReserveIdentifier = [u8; 8];416 /// The type for recording an account's balance.417 type Balance = Balance;418 /// The ubiquitous event type.419 type Event = Event;420 type DustRemoval = Treasury;421 type ExistentialDeposit = ExistentialDeposit;422 type AccountStore = System;423 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;424}425426pub const fn deposit(items: u32, bytes: u32) -> Balance {427 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE428}429430/*431parameter_types! {432 pub TombstoneDeposit: Balance = deposit(433 1,434 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,435 );436 pub DepositPerContract: Balance = TombstoneDeposit::get();437 pub const DepositPerStorageByte: Balance = deposit(0, 1);438 pub const DepositPerStorageItem: Balance = deposit(1, 0);439 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);440 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;441 pub const SignedClaimHandicap: u32 = 2;442 pub const MaxDepth: u32 = 32;443 pub const MaxValueSize: u32 = 16 * 1024;444 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb445 // The lazy deletion runs inside on_initialize.446 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *447 RuntimeBlockWeights::get().max_block;448 // The weight needed for decoding the queue should be less or equal than a fifth449 // of the overall weight dedicated to the lazy deletion.450 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (451 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -452 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)453 )) / 5) as u32;454 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();455}456457impl pallet_contracts::Config for Runtime {458 type Time = Timestamp;459 type Randomness = RandomnessCollectiveFlip;460 type Currency = Balances;461 type Event = Event;462 type RentPayment = ();463 type SignedClaimHandicap = SignedClaimHandicap;464 type TombstoneDeposit = TombstoneDeposit;465 type DepositPerContract = DepositPerContract;466 type DepositPerStorageByte = DepositPerStorageByte;467 type DepositPerStorageItem = DepositPerStorageItem;468 type RentFraction = RentFraction;469 type SurchargeReward = SurchargeReward;470 type WeightPrice = pallet_transaction_payment::Pallet<Self>;471 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;472 type ChainExtension = NFTExtension;473 type DeletionQueueDepth = DeletionQueueDepth;474 type DeletionWeightLimit = DeletionWeightLimit;475 type Schedule = Schedule;476 type CallStack = [pallet_contracts::Frame<Self>; 31];477}478*/479480parameter_types! {481 /// This value increases the priority of `Operational` transactions by adding482 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.483 pub const OperationalFeeMultiplier: u8 = 5;484}485486/// Linear implementor of `WeightToFeePolynomial`487pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);488489impl<T> WeightToFeePolynomial for LinearFee<T>490where491 T: BaseArithmetic + From<u32> + Copy + Unsigned,492{493 type Balance = T;494495 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {496 smallvec!(WeightToFeeCoefficient {497 // Targeting 0.1 Unique per NFT transfer498 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),499 coeff_frac: Perbill::zero(),500 negative: false,501 degree: 1,502 })503 }504}505506impl pallet_transaction_payment::Config for Runtime {507 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;508 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;509 type OperationalFeeMultiplier = OperationalFeeMultiplier;510 type WeightToFee = LinearFee<Balance>;511 type FeeMultiplierUpdate = ();512}513514parameter_types! {515 pub const ProposalBond: Permill = Permill::from_percent(5);516 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;517 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;518 pub const SpendPeriod: BlockNumber = 5 * MINUTES;519 pub const Burn: Permill = Permill::from_percent(0);520 pub const TipCountdown: BlockNumber = 1 * DAYS;521 pub const TipFindersFee: Percent = Percent::from_percent(20);522 pub const TipReportDepositBase: Balance = 1 * UNIQUE;523 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;524 pub const BountyDepositBase: Balance = 1 * UNIQUE;525 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;526 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");527 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;528 pub const MaximumReasonLength: u32 = 16384;529 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);530 pub const BountyValueMinimum: Balance = 5 * UNIQUE;531 pub const MaxApprovals: u32 = 100;532}533534impl pallet_treasury::Config for Runtime {535 type PalletId = TreasuryModuleId;536 type Currency = Balances;537 type ApproveOrigin = EnsureRoot<AccountId>;538 type RejectOrigin = EnsureRoot<AccountId>;539 type Event = Event;540 type OnSlash = ();541 type ProposalBond = ProposalBond;542 type ProposalBondMinimum = ProposalBondMinimum;543 type ProposalBondMaximum = ProposalBondMaximum;544 type SpendPeriod = SpendPeriod;545 type Burn = Burn;546 type BurnDestination = ();547 type SpendFunds = ();548 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;549 type MaxApprovals = MaxApprovals;550}551552impl pallet_sudo::Config for Runtime {553 type Event = Event;554 type Call = Call;555}556557pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);558559impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider560 for RelayChainBlockNumberProvider<T>561{562 type BlockNumber = BlockNumber;563564 fn current_block_number() -> Self::BlockNumber {565 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()566 .map(|d| d.relay_parent_number)567 .unwrap_or_default()568 }569}570571parameter_types! {572 pub const MinVestedTransfer: Balance = 10 * UNIQUE;573 pub const MaxVestingSchedules: u32 = 28;574}575576impl orml_vesting::Config for Runtime {577 type Event = Event;578 type Currency = pallet_balances::Pallet<Runtime>;579 type MinVestedTransfer = MinVestedTransfer;580 type VestedTransferOrigin = EnsureSigned<AccountId>;581 type WeightInfo = ();582 type MaxVestingSchedules = MaxVestingSchedules;583 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;584}585586parameter_types! {587 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;588 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;589}590591impl cumulus_pallet_parachain_system::Config for Runtime {592 type Event = Event;593 type SelfParaId = parachain_info::Pallet<Self>;594 type OnSystemEvent = ();595 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<596 // MaxDownwardMessageWeight,597 // XcmExecutor<XcmConfig>,598 // Call,599 // >;600 type OutboundXcmpMessageSource = XcmpQueue;601 type DmpMessageHandler = DmpQueue;602 type ReservedDmpWeight = ReservedDmpWeight;603 type ReservedXcmpWeight = ReservedXcmpWeight;604 type XcmpMessageHandler = XcmpQueue;605}606607impl parachain_info::Config for Runtime {}608609impl cumulus_pallet_aura_ext::Config for Runtime {}610611parameter_types! {612 pub const RelayLocation: MultiLocation = MultiLocation::parent();613 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;614 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();615 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();616}617618/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used619/// when determining ownership of accounts for asset transacting and when attempting to use XCM620/// `Transact` in order to determine the dispatch Origin.621pub type LocationToAccountId = (622 // The parent (Relay-chain) origin converts to the default `AccountId`.623 ParentIsPreset<AccountId>,624 // Sibling parachain origins convert to AccountId via the `ParaId::into`.625 SiblingParachainConvertsVia<Sibling, AccountId>,626 // Straight up local `AccountId32` origins just alias directly to `AccountId`.627 AccountId32Aliases<RelayNetwork, AccountId>,628);629630pub struct OnlySelfCurrency;631impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {632 fn matches_fungible(a: &MultiAsset) -> Option<B> {633 match (&a.id, &a.fun) {634 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),635 _ => None,636 }637 }638}639640/// Means for transacting assets on this chain.641pub type LocalAssetTransactor = CurrencyAdapter<642 // Use this currency:643 Balances,644 // Use this currency when it is a fungible asset matching the given location or name:645 OnlySelfCurrency,646 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:647 LocationToAccountId,648 // Our chain's account ID type (we can't get away without mentioning it explicitly):649 AccountId,650 // We don't track any teleports.651 (),652>;653654/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,655/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can656/// biases the kind of local `Origin` it will become.657pub type XcmOriginToTransactDispatchOrigin = (658 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location659 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for660 // foreign chains who want to have a local sovereign account on this chain which they control.661 SovereignSignedViaLocation<LocationToAccountId, Origin>,662 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when663 // recognised.664 RelayChainAsNative<RelayOrigin, Origin>,665 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when666 // recognised.667 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,668 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a669 // transaction from the Root origin.670 ParentAsSuperuser<Origin>,671 // Native signed account converter; this just converts an `AccountId32` origin into a normal672 // `Origin::Signed` origin of the same 32-byte value.673 SignedAccountId32AsNative<RelayNetwork, Origin>,674 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.675 XcmPassthrough<Origin>,676);677678parameter_types! {679 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.680 pub UnitWeightCost: Weight = 1_000_000;681 // 1200 UNIQUEs buy 1 second of weight.682 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);683 pub const MaxInstructions: u32 = 100;684 pub const MaxAuthorities: u32 = 100_000;685}686687match_types! {688 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {689 MultiLocation { parents: 1, interior: Here } |690 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }691 };692}693694pub type Barrier = (695 TakeWeightCredit,696 AllowTopLevelPaidExecutionFrom<Everything>,697 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,698 // ^^^ Parent & its unit plurality gets free execution699);700701pub struct UsingOnlySelfCurrencyComponents<702 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,703 AssetId: Get<MultiLocation>,704 AccountId,705 Currency: CurrencyT<AccountId>,706 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,707>(708 Weight,709 Currency::Balance,710 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,711);712impl<713 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,714 AssetId: Get<MultiLocation>,715 AccountId,716 Currency: CurrencyT<AccountId>,717 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,718 > WeightTrader719 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>720{721 fn new() -> Self {722 Self(0, Zero::zero(), PhantomData)723 }724725 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {726 let amount = WeightToFee::calc(&weight);727 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;728729 // location to this parachain through relay chain730 let option1: xcm::v1::AssetId = Concrete(MultiLocation {731 parents: 1,732 interior: X1(Parachain(ParachainInfo::parachain_id().into())),733 });734 // direct location735 let option2: xcm::v1::AssetId = Concrete(MultiLocation {736 parents: 0,737 interior: Here,738 });739740 let required = if payment.fungible.contains_key(&option1) {741 (option1, u128_amount).into()742 } else if payment.fungible.contains_key(&option2) {743 (option2, u128_amount).into()744 } else {745 (Concrete(MultiLocation::default()), u128_amount).into()746 };747748 let unused = payment749 .checked_sub(required)750 .map_err(|_| XcmError::TooExpensive)?;751 self.0 = self.0.saturating_add(weight);752 self.1 = self.1.saturating_add(amount);753 Ok(unused)754 }755756 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {757 let weight = weight.min(self.0);758 let amount = WeightToFee::calc(&weight);759 self.0 -= weight;760 self.1 = self.1.saturating_sub(amount);761 let amount: u128 = amount.saturated_into();762 if amount > 0 {763 Some((AssetId::get(), amount).into())764 } else {765 None766 }767 }768}769impl<770 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,771 AssetId: Get<MultiLocation>,772 AccountId,773 Currency: CurrencyT<AccountId>,774 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,775 > Drop776 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>777{778 fn drop(&mut self) {779 OnUnbalanced::on_unbalanced(Currency::issue(self.1));780 }781}782783pub struct XcmConfig;784impl Config for XcmConfig {785 type Call = Call;786 type XcmSender = XcmRouter;787 // How to withdraw and deposit an asset.788 type AssetTransactor = LocalAssetTransactor;789 type OriginConverter = XcmOriginToTransactDispatchOrigin;790 type IsReserve = NativeAsset;791 type IsTeleporter = (); // Teleportation is disabled792 type LocationInverter = LocationInverter<Ancestry>;793 type Barrier = Barrier;794 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;795 type Trader = UsingOnlySelfCurrencyComponents<796 IdentityFee<Balance>,797 RelayLocation,798 AccountId,799 Balances,800 (),801 >;802 type ResponseHandler = (); // Don't handle responses for now.803 type SubscriptionService = PolkadotXcm;804805 type AssetTrap = PolkadotXcm;806 type AssetClaims = PolkadotXcm;807}808809// parameter_types! {810// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;811// }812813/// No local origins on this chain are allowed to dispatch XCM sends/executions.814pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);815816/// The means for routing XCM messages which are not for local execution into the right message817/// queues.818pub type XcmRouter = (819 // Two routers - use UMP to communicate with the relay chain:820 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,821 // ..and XCMP to communicate with the sibling chains.822 XcmpQueue,823);824825impl pallet_evm_coder_substrate::Config for Runtime {826 type GasWeightMapping = FixedGasWeightMapping;827}828829impl pallet_xcm::Config for Runtime {830 type Event = Event;831 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;832 type XcmRouter = XcmRouter;833 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;834 type XcmExecuteFilter = Everything;835 type XcmExecutor = XcmExecutor<XcmConfig>;836 type XcmTeleportFilter = Everything;837 type XcmReserveTransferFilter = Everything;838 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;839 type LocationInverter = LocationInverter<Ancestry>;840 type Origin = Origin;841 type Call = Call;842 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;843 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;844}845846impl cumulus_pallet_xcm::Config for Runtime {847 type Event = Event;848 type XcmExecutor = XcmExecutor<XcmConfig>;849}850851impl cumulus_pallet_xcmp_queue::Config for Runtime {852 type WeightInfo = ();853 type Event = Event;854 type XcmExecutor = XcmExecutor<XcmConfig>;855 type ChannelInfo = ParachainSystem;856 type VersionWrapper = ();857 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;858 type ControllerOrigin = EnsureRoot<AccountId>;859 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;860}861862impl cumulus_pallet_dmp_queue::Config for Runtime {863 type Event = Event;864 type XcmExecutor = XcmExecutor<XcmConfig>;865 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;866}867868impl pallet_aura::Config for Runtime {869 type AuthorityId = AuraId;870 type DisabledValidators = ();871 type MaxAuthorities = MaxAuthorities;872}873874parameter_types! {875 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();876 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;877}878879impl pallet_common::Config for Runtime {880 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;881 type Event = Event;882 type Currency = Balances;883 type CollectionCreationPrice = CollectionCreationPrice;884 type TreasuryAccountId = TreasuryAccountId;885 type CollectionDispatch = CollectionDispatchT<Self>;886887 type EvmTokenAddressMapping = EvmTokenAddressMapping;888 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;889}890891impl pallet_structure::Config for Runtime {892 type Event = Event;893 type Call = Call;894 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;895}896897impl pallet_fungible::Config for Runtime {898 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;899}900impl pallet_refungible::Config for Runtime {901 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;902}903impl pallet_nonfungible::Config for Runtime {904 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;905}906907impl pallet_proxy_rmrk_core::Config for Runtime {908 type Event = Event;909}910911impl pallet_proxy_rmrk_equip::Config for Runtime {912 type Event = Event;913}914915impl pallet_unique::Config for Runtime {916 type Event = Event;917 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;918 type CommonWeightInfo = CommonWeights<Self>;919}920921parameter_types! {922 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied923}924925/// Used for the pallet inflation926impl pallet_inflation::Config for Runtime {927 type Currency = Balances;928 type TreasuryAccountId = TreasuryAccountId;929 type InflationBlockInterval = InflationBlockInterval;930 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;931}932933// parameter_types! {934// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *935// RuntimeBlockWeights::get().max_block;936// pub const MaxScheduledPerBlock: u32 = 50;937// }938939type EvmSponsorshipHandler = (940 UniqueEthSponsorshipHandler<Runtime>,941 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,942);943type SponsorshipHandler = (944 UniqueSponsorshipHandler<Runtime>,945 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,946 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,947);948949// impl pallet_unq_scheduler::Config for Runtime {950// type Event = Event;951// type Origin = Origin;952// type PalletsOrigin = OriginCaller;953// type Call = Call;954// type MaximumWeight = MaximumSchedulerWeight;955// type ScheduleOrigin = EnsureSigned<AccountId>;956// type MaxScheduledPerBlock = MaxScheduledPerBlock;957// type SponsorshipHandler = SponsorshipHandler;958// type WeightInfo = ();959// }960961impl pallet_evm_transaction_payment::Config for Runtime {962 type EvmSponsorshipHandler = EvmSponsorshipHandler;963 type Currency = Balances;964}965966impl pallet_charge_transaction::Config for Runtime {967 type SponsorshipHandler = SponsorshipHandler;968}969970// impl pallet_contract_helpers::Config for Runtime {971// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;972// }973974parameter_types! {975 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049976 pub const HelpersContractAddress: H160 = H160([977 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,978 ]);979980 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f981 pub const EvmCollectionAddress: H160 = H160([982 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,983 ]);984}985986impl pallet_evm_contract_helpers::Config for Runtime {987 type ContractAddress = HelpersContractAddress;988 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;989}990991impl evm_collection::Config for Runtime {992 type ContractAddress = EvmCollectionAddress;993}994995construct_runtime!(996 pub enum Runtime where997 Block = Block,998 NodeBlock = opaque::Block,999 UncheckedExtrinsic = UncheckedExtrinsic1000 {1001 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1002 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,10031004 Aura: pallet_aura::{Pallet, Config<T>} = 22,1005 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10061007 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1008 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1009 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1010 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1011 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1012 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1013 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1014 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1015 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1016 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10171018 // XCM helpers.1019 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1020 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1021 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1022 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10231024 // Unique Pallets1025 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1026 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1027 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1028 // free = 631029 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1030 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1031 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1032 Fungible: pallet_fungible::{Pallet, Storage} = 67,1033 Refungible: pallet_refungible::{Pallet, Storage} = 68,1034 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1035 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1036 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1037 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10381039 // Frontier1040 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1041 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10421043 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1044 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1045 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1046 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1047 }1048);10491050pub struct TransactionConverter;10511052impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1053 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1054 UncheckedExtrinsic::new_unsigned(1055 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1056 )1057 }1058}10591060impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1061 fn convert_transaction(1062 &self,1063 transaction: pallet_ethereum::Transaction,1064 ) -> opaque::UncheckedExtrinsic {1065 let extrinsic = UncheckedExtrinsic::new_unsigned(1066 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1067 );1068 let encoded = extrinsic.encode();1069 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1070 .expect("Encoded extrinsic is always valid")1071 }1072}10731074/// The address format for describing accounts.1075pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1076/// Block header type as expected by this runtime.1077pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1078/// Block type as expected by this runtime.1079pub type Block = generic::Block<Header, UncheckedExtrinsic>;1080/// A Block signed with a Justification1081pub type SignedBlock = generic::SignedBlock<Block>;1082/// BlockId type as expected by this runtime.1083pub type BlockId = generic::BlockId<Block>;1084/// The SignedExtension to the basic transaction logic.1085pub type SignedExtra = (1086 frame_system::CheckSpecVersion<Runtime>,1087 // system::CheckTxVersion<Runtime>,1088 frame_system::CheckGenesis<Runtime>,1089 frame_system::CheckEra<Runtime>,1090 frame_system::CheckNonce<Runtime>,1091 frame_system::CheckWeight<Runtime>,1092 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1093 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1094 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1095);1096/// Unchecked extrinsic type as expected by this runtime.1097pub type UncheckedExtrinsic =1098 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1099/// Extrinsic type that has already been checked.1100pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1101/// Executive: handles dispatch to the various modules.1102pub type Executive = frame_executive::Executive<1103 Runtime,1104 Block,1105 frame_system::ChainContext<Runtime>,1106 Runtime,1107 AllPalletsReversedWithSystemFirst,1108>;11091110impl_opaque_keys! {1111 pub struct SessionKeys {1112 pub aura: Aura,1113 }1114}11151116impl fp_self_contained::SelfContainedCall for Call {1117 type SignedInfo = H160;11181119 fn is_self_contained(&self) -> bool {1120 match self {1121 Call::Ethereum(call) => call.is_self_contained(),1122 _ => false,1123 }1124 }11251126 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1127 match self {1128 Call::Ethereum(call) => call.check_self_contained(),1129 _ => None,1130 }1131 }11321133 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1134 match self {1135 Call::Ethereum(call) => call.validate_self_contained(info),1136 _ => None,1137 }1138 }11391140 fn pre_dispatch_self_contained(1141 &self,1142 info: &Self::SignedInfo,1143 ) -> Option<Result<(), TransactionValidityError>> {1144 match self {1145 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1146 _ => None,1147 }1148 }11491150 fn apply_self_contained(1151 self,1152 info: Self::SignedInfo,1153 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1154 match self {1155 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1156 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1157 )),1158 _ => None,1159 }1160 }1161}11621163macro_rules! dispatch_unique_runtime {1164 ($collection:ident.$method:ident($($name:ident),*)) => {{1165 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1166 let dispatch = collection.as_dyn();11671168 Ok::<_, DispatchError>(dispatch.$method($($name),*))1169 }};1170}11711172impl_common_runtime_apis!();11731174struct CheckInherents;11751176impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1177 fn check_inherents(1178 block: &Block,1179 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1180 ) -> sp_inherents::CheckInherentsResult {1181 let relay_chain_slot = relay_state_proof1182 .read_slot()1183 .expect("Could not read the relay chain slot from the proof");11841185 let inherent_data =1186 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1187 relay_chain_slot,1188 sp_std::time::Duration::from_secs(6),1189 )1190 .create_inherent_data()1191 .expect("Could not create the timestamp inherent data");11921193 inherent_data.check_extrinsics(block)1194 }1195}11961197cumulus_pallet_parachain_system::register_validate_block!(1198 Runtime = Runtime,1199 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1200 CheckInherents = CheckInherents,1201);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 _, OnMethodCall,53 Account as EVMAccount, FeeCalculator, GasWeightMapping,54};55pub use frame_support::{56 construct_runtime, match_types,57 dispatch::DispatchResult,58 PalletId, parameter_types, StorageValue, ConsensusEngineId,59 traits::{60 tokens::currency::Currency as CurrencyT, OnUnbalanced as OnUnbalancedT, Everything,61 Currency, ExistenceRequirement, Get, IsInVec, KeyOwnerProofSystem, LockIdentifier,62 OnUnbalanced, Randomness, FindAuthor, ConstU32, Imbalance,63 },64 weights::{65 constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},66 DispatchClass, DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,67 WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients, ConstantMultiplier,68 },69};70use up_data_structs::mapping::{EvmTokenAddressMapping, CrossTokenAddressMapping};71use up_data_structs::*;72// use pallet_contracts::weights::WeightInfo;73// #[cfg(any(feature = "std", test))]74use frame_system::{75 self as frame_system, EnsureRoot, EnsureSigned,76 limits::{BlockWeights, BlockLength},77};78use sp_arithmetic::{79 traits::{BaseArithmetic, Unsigned},80};81use smallvec::smallvec;82use codec::{Encode, Decode};83use pallet_unique::eth::evm_collection;84use fp_rpc::TransactionStatus;85use sp_runtime::{86 traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf, Saturating},87 transaction_validity::TransactionValidityError,88 SaturatedConversion,89};9091// pub use pallet_timestamp::Call as TimestampCall;92pub use sp_consensus_aura::sr25519::AuthorityId as AuraId;9394// Polkadot imports95use pallet_xcm::XcmPassthrough;96use polkadot_parachain::primitives::Sibling;97use xcm::v1::{BodyId, Junction::*, MultiLocation, NetworkId, Junctions::*};98use xcm_builder::{99 AccountId32Aliases, AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, CurrencyAdapter,100 EnsureXcmOrigin, FixedWeightBounds, LocationInverter, NativeAsset, ParentAsSuperuser,101 RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,102 SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,103 ParentIsPreset,104};105use xcm_executor::{Config, XcmExecutor, Assets};106use sp_std::{marker::PhantomData};107108use xcm::latest::{109 // Xcm,110 AssetId::{Concrete},111 Fungibility::Fungible as XcmFungible,112 MultiAsset,113 Error as XcmError,114};115use xcm_executor::traits::{MatchesFungible, WeightTrader};116//use xcm_executor::traits::MatchesFungible;117use sp_runtime::traits::CheckedConversion;118119use unique_runtime_common::{120 impl_common_runtime_apis,121 types::*,122 constants::*,123 dispatch::{CollectionDispatchT, CollectionDispatch},124 sponsoring::UniqueSponsorshipHandler,125 eth_sponsoring::UniqueEthSponsorshipHandler,126 weights::CommonWeights,127};128129pub const RUNTIME_NAME: &str = "opal";130pub const TOKEN_SYMBOL: &str = "OPL";131132type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Runtime>;133134impl RuntimeInstance for Runtime {135 type CrossAccountId = self::CrossAccountId;136 type TransactionConverter = self::TransactionConverter;137138 fn get_transaction_converter() -> TransactionConverter {139 TransactionConverter140 }141}142143/// The type for looking up accounts. We don't expect more than 4 billion of them, but you144/// never know...145pub type AccountIndex = u32;146147/// Balance of an account.148pub type Balance = u128;149150/// Index of a transaction in the chain.151pub type Index = u32;152153/// A hash of some data used by the chain.154pub type Hash = sp_core::H256;155156/// Digest item type.157pub type DigestItem = generic::DigestItem;158159/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know160/// the specifics of the runtime. They can then be made to be agnostic over specific formats161/// of data like extrinsics, allowing for them to continue syncing the network through upgrades162/// to even the core data structures.163pub mod opaque {164 use sp_std::prelude::*;165 use sp_runtime::impl_opaque_keys;166 use super::Aura;167168 pub use unique_runtime_common::types::*;169170 impl_opaque_keys! {171 pub struct SessionKeys {172 pub aura: Aura,173 }174 }175}176177/// This runtime version.178pub const VERSION: RuntimeVersion = RuntimeVersion {179 spec_name: create_runtime_str!(RUNTIME_NAME),180 impl_name: create_runtime_str!(RUNTIME_NAME),181 authoring_version: 1,182 spec_version: 920000,183 impl_version: 0,184 apis: RUNTIME_API_VERSIONS,185 transaction_version: 1,186 state_version: 0,187};188189#[derive(codec::Encode, codec::Decode)]190pub enum XCMPMessage<XAccountId, XBalance> {191 /// Transfer tokens to the given account from the Parachain account.192 TransferToken(XAccountId, XBalance),193}194195/// The version information used to identify this runtime when compiled natively.196#[cfg(feature = "std")]197pub fn native_version() -> NativeVersion {198 NativeVersion {199 runtime_version: VERSION,200 can_author_with: Default::default(),201 }202}203204type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;205206pub struct DealWithFees;207impl OnUnbalanced<NegativeImbalance> for DealWithFees {208 fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item = NegativeImbalance>) {209 if let Some(fees) = fees_then_tips.next() {210 // for fees, 100% to treasury211 let mut split = fees.ration(100, 0);212 if let Some(tips) = fees_then_tips.next() {213 // for tips, if any, 100% to treasury214 tips.ration_merge_into(100, 0, &mut split);215 }216 Treasury::on_unbalanced(split.0);217 // Author::on_unbalanced(split.1);218 }219 }220}221222parameter_types! {223 pub const BlockHashCount: BlockNumber = 2400;224 pub RuntimeBlockLength: BlockLength =225 BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);226 pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);227 pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;228 pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()229 .base_block(BlockExecutionWeight::get())230 .for_class(DispatchClass::all(), |weights| {231 weights.base_extrinsic = ExtrinsicBaseWeight::get();232 })233 .for_class(DispatchClass::Normal, |weights| {234 weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);235 })236 .for_class(DispatchClass::Operational, |weights| {237 weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);238 // Operational transactions have some extra reserved space, so that they239 // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.240 weights.reserved = Some(241 MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT242 );243 })244 .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)245 .build_or_panic();246 pub const Version: RuntimeVersion = VERSION;247 pub const SS58Prefix: u8 = 42;248}249250parameter_types! {251 pub const ChainId: u64 = 8882;252}253254pub struct FixedFee;255impl FeeCalculator for FixedFee {256 fn min_gas_price() -> U256 {257 MIN_GAS_PRICE.into()258 }259}260261// Assuming slowest ethereum opcode is SSTORE, with gas price of 20000 as our worst case262// (contract, which only writes a lot of data),263// approximating on top of our real store write weight264parameter_types! {265 pub const WritesPerSecond: u64 = WEIGHT_PER_SECOND / <Runtime as frame_system::Config>::DbWeight::get().write;266 pub const GasPerSecond: u64 = WritesPerSecond::get() * 20000;267 pub const WeightPerGas: u64 = WEIGHT_PER_SECOND / GasPerSecond::get();268}269270/// Limiting EVM execution to 50% of block for substrate users and management tasks271/// EVM transaction consumes more weight than substrate's, so we can't rely on them being272/// scheduled fairly273const EVM_DISPATCH_RATIO: Perbill = Perbill::from_percent(50);274parameter_types! {275 pub BlockGasLimit: U256 = U256::from(NORMAL_DISPATCH_RATIO * EVM_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT / WeightPerGas::get());276}277278pub enum FixedGasWeightMapping {}279impl GasWeightMapping for FixedGasWeightMapping {280 fn gas_to_weight(gas: u64) -> Weight {281 gas.saturating_mul(WeightPerGas::get())282 }283 fn weight_to_gas(weight: Weight) -> u64 {284 weight / WeightPerGas::get()285 }286}287288impl pallet_evm::account::Config for Runtime {289 type CrossAccountId = pallet_evm::account::BasicCrossAccountId<Self>;290 type EvmAddressMapping = pallet_evm::HashedAddressMapping<Self::Hashing>;291 type EvmBackwardsAddressMapping = fp_evm_mapping::MapBackwardsAddressTruncated;292}293294impl pallet_evm::Config for Runtime {295 type BlockGasLimit = BlockGasLimit;296 type FeeCalculator = FixedFee;297 type GasWeightMapping = FixedGasWeightMapping;298 type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;299 type CallOrigin = EnsureAddressTruncated<Self>;300 type WithdrawOrigin = EnsureAddressTruncated<Self>;301 type AddressMapping = HashedAddressMapping<Self::Hashing>;302 type PrecompilesType = ();303 type PrecompilesValue = ();304 type Currency = Balances;305 type Event = Event;306 type OnMethodCall = (307 pallet_evm_migration::OnMethodCall<Self>,308 pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,309 CollectionDispatchT<Self>,310 evm_collection::CollectionOnMethodCall<Self>,311 evm_collection::CollectionHelperOnMethodCall<Self>,312 );313 type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;314 type ChainId = ChainId;315 type Runner = pallet_evm::runner::stack::Runner<Self>;316 type OnChargeTransaction = pallet_evm::EVMCurrencyAdapter<Balances, DealWithFees>;317 type TransactionValidityHack = pallet_evm_transaction_payment::TransactionValidityHack<Self>;318 type FindAuthor = EthereumFindAuthor<Aura>;319}320321impl pallet_evm_migration::Config for Runtime {322 type WeightInfo = pallet_evm_migration::weights::SubstrateWeight<Self>;323}324325pub struct EthereumFindAuthor<F>(core::marker::PhantomData<F>);326impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F> {327 fn find_author<'a, I>(digests: I) -> Option<H160>328 where329 I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,330 {331 if let Some(author_index) = F::find_author(digests) {332 let authority_id = Aura::authorities()[author_index as usize].clone();333 return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));334 }335 None336 }337}338339impl pallet_ethereum::Config for Runtime {340 type Event = Event;341 type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;342}343344impl pallet_randomness_collective_flip::Config for Runtime {}345346impl frame_system::Config for Runtime {347 /// The data to be stored in an account.348 type AccountData = pallet_balances::AccountData<Balance>;349 /// The identifier used to distinguish between accounts.350 type AccountId = AccountId;351 /// The basic call filter to use in dispatchable.352 type BaseCallFilter = Everything;353 /// Maximum number of block number to block hash mappings to keep (oldest pruned first).354 type BlockHashCount = BlockHashCount;355 /// The maximum length of a block (in bytes).356 type BlockLength = RuntimeBlockLength;357 /// The index type for blocks.358 type BlockNumber = BlockNumber;359 /// The weight of the overhead invoked on the block import process, independent of the extrinsics included in that block.360 type BlockWeights = RuntimeBlockWeights;361 /// The aggregated dispatch type that is available for extrinsics.362 type Call = Call;363 /// The weight of database operations that the runtime can invoke.364 type DbWeight = RocksDbWeight;365 /// The ubiquitous event type.366 type Event = Event;367 /// The type for hashing blocks and tries.368 type Hash = Hash;369 /// The hashing algorithm used.370 type Hashing = BlakeTwo256;371 /// The header type.372 type Header = generic::Header<BlockNumber, BlakeTwo256>;373 /// The index type for storing how many extrinsics an account has signed.374 type Index = Index;375 /// The lookup mechanism to get account ID from whatever is passed in dispatchers.376 type Lookup = AccountIdLookup<AccountId, ()>;377 /// What to do if an account is fully reaped from the system.378 type OnKilledAccount = ();379 /// What to do if a new account is created.380 type OnNewAccount = ();381 type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;382 /// The ubiquitous origin type.383 type Origin = Origin;384 /// This type is being generated by `construct_runtime!`.385 type PalletInfo = PalletInfo;386 /// This is used as an identifier of the chain. 42 is the generic substrate prefix.387 type SS58Prefix = SS58Prefix;388 /// Weight information for the extrinsics of this pallet.389 type SystemWeightInfo = frame_system::weights::SubstrateWeight<Self>;390 /// Version of the runtime.391 type Version = Version;392 type MaxConsumers = ConstU32<16>;393}394395parameter_types! {396 pub const MinimumPeriod: u64 = SLOT_DURATION / 2;397}398399impl pallet_timestamp::Config for Runtime {400 /// A timestamp: milliseconds since the unix epoch.401 type Moment = u64;402 type OnTimestampSet = ();403 type MinimumPeriod = MinimumPeriod;404 type WeightInfo = ();405}406407parameter_types! {408 // pub const ExistentialDeposit: u128 = 500;409 pub const ExistentialDeposit: u128 = 0;410 pub const MaxLocks: u32 = 50;411}412413impl pallet_balances::Config for Runtime {414 type MaxLocks = MaxLocks;415 type MaxReserves = ();416 type ReserveIdentifier = [u8; 8];417 /// The type for recording an account's balance.418 type Balance = Balance;419 /// The ubiquitous event type.420 type Event = Event;421 type DustRemoval = Treasury;422 type ExistentialDeposit = ExistentialDeposit;423 type AccountStore = System;424 type WeightInfo = pallet_balances::weights::SubstrateWeight<Self>;425}426427pub const fn deposit(items: u32, bytes: u32) -> Balance {428 items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE429}430431/*432parameter_types! {433 pub TombstoneDeposit: Balance = deposit(434 1,435 sp_std::mem::size_of::<pallet_contracts::Pallet<Runtime>> as u32,436 );437 pub DepositPerContract: Balance = TombstoneDeposit::get();438 pub const DepositPerStorageByte: Balance = deposit(0, 1);439 pub const DepositPerStorageItem: Balance = deposit(1, 0);440 pub RentFraction: Perbill = Perbill::from_rational(1u32, 30 * DAYS);441 pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;442 pub const SignedClaimHandicap: u32 = 2;443 pub const MaxDepth: u32 = 32;444 pub const MaxValueSize: u32 = 16 * 1024;445 pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb446 // The lazy deletion runs inside on_initialize.447 pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *448 RuntimeBlockWeights::get().max_block;449 // The weight needed for decoding the queue should be less or equal than a fifth450 // of the overall weight dedicated to the lazy deletion.451 pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (452 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -453 <Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)454 )) / 5) as u32;455 pub Schedule: pallet_contracts::Schedule<Runtime> = Default::default();456}457458impl pallet_contracts::Config for Runtime {459 type Time = Timestamp;460 type Randomness = RandomnessCollectiveFlip;461 type Currency = Balances;462 type Event = Event;463 type RentPayment = ();464 type SignedClaimHandicap = SignedClaimHandicap;465 type TombstoneDeposit = TombstoneDeposit;466 type DepositPerContract = DepositPerContract;467 type DepositPerStorageByte = DepositPerStorageByte;468 type DepositPerStorageItem = DepositPerStorageItem;469 type RentFraction = RentFraction;470 type SurchargeReward = SurchargeReward;471 type WeightPrice = pallet_transaction_payment::Pallet<Self>;472 type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;473 type ChainExtension = NFTExtension;474 type DeletionQueueDepth = DeletionQueueDepth;475 type DeletionWeightLimit = DeletionWeightLimit;476 type Schedule = Schedule;477 type CallStack = [pallet_contracts::Frame<Self>; 31];478}479*/480481parameter_types! {482 /// This value increases the priority of `Operational` transactions by adding483 /// a "virtual tip" that's equal to the `OperationalFeeMultiplier * final_fee`.484 pub const OperationalFeeMultiplier: u8 = 5;485}486487/// Linear implementor of `WeightToFeePolynomial`488pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);489490impl<T> WeightToFeePolynomial for LinearFee<T>491where492 T: BaseArithmetic + From<u32> + Copy + Unsigned,493{494 type Balance = T;495496 fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {497 smallvec!(WeightToFeeCoefficient {498 // Targeting 0.1 Unique per NFT transfer499 coeff_integer: WEIGHT_TO_FEE_COEFF.into(),500 coeff_frac: Perbill::zero(),501 negative: false,502 degree: 1,503 })504 }505}506507impl pallet_transaction_payment::Config for Runtime {508 type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter<Balances, DealWithFees>;509 type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;510 type OperationalFeeMultiplier = OperationalFeeMultiplier;511 type WeightToFee = LinearFee<Balance>;512 type FeeMultiplierUpdate = ();513}514515parameter_types! {516 pub const ProposalBond: Permill = Permill::from_percent(5);517 pub const ProposalBondMinimum: Balance = 1 * UNIQUE;518 pub const ProposalBondMaximum: Balance = 1000 * UNIQUE;519 pub const SpendPeriod: BlockNumber = 5 * MINUTES;520 pub const Burn: Permill = Permill::from_percent(0);521 pub const TipCountdown: BlockNumber = 1 * DAYS;522 pub const TipFindersFee: Percent = Percent::from_percent(20);523 pub const TipReportDepositBase: Balance = 1 * UNIQUE;524 pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;525 pub const BountyDepositBase: Balance = 1 * UNIQUE;526 pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;527 pub const TreasuryModuleId: PalletId = PalletId(*b"py/trsry");528 pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;529 pub const MaximumReasonLength: u32 = 16384;530 pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);531 pub const BountyValueMinimum: Balance = 5 * UNIQUE;532 pub const MaxApprovals: u32 = 100;533}534535impl pallet_treasury::Config for Runtime {536 type PalletId = TreasuryModuleId;537 type Currency = Balances;538 type ApproveOrigin = EnsureRoot<AccountId>;539 type RejectOrigin = EnsureRoot<AccountId>;540 type Event = Event;541 type OnSlash = ();542 type ProposalBond = ProposalBond;543 type ProposalBondMinimum = ProposalBondMinimum;544 type ProposalBondMaximum = ProposalBondMaximum;545 type SpendPeriod = SpendPeriod;546 type Burn = Burn;547 type BurnDestination = ();548 type SpendFunds = ();549 type WeightInfo = pallet_treasury::weights::SubstrateWeight<Self>;550 type MaxApprovals = MaxApprovals;551}552553impl pallet_sudo::Config for Runtime {554 type Event = Event;555 type Call = Call;556}557558pub struct RelayChainBlockNumberProvider<T>(sp_std::marker::PhantomData<T>);559560impl<T: cumulus_pallet_parachain_system::Config> BlockNumberProvider561 for RelayChainBlockNumberProvider<T>562{563 type BlockNumber = BlockNumber;564565 fn current_block_number() -> Self::BlockNumber {566 cumulus_pallet_parachain_system::Pallet::<T>::validation_data()567 .map(|d| d.relay_parent_number)568 .unwrap_or_default()569 }570}571572parameter_types! {573 pub const MinVestedTransfer: Balance = 10 * UNIQUE;574 pub const MaxVestingSchedules: u32 = 28;575}576577impl orml_vesting::Config for Runtime {578 type Event = Event;579 type Currency = pallet_balances::Pallet<Runtime>;580 type MinVestedTransfer = MinVestedTransfer;581 type VestedTransferOrigin = EnsureSigned<AccountId>;582 type WeightInfo = ();583 type MaxVestingSchedules = MaxVestingSchedules;584 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;585}586587parameter_types! {588 pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;589 pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;590}591592impl cumulus_pallet_parachain_system::Config for Runtime {593 type Event = Event;594 type SelfParaId = parachain_info::Pallet<Self>;595 type OnSystemEvent = ();596 // type DownwardMessageHandlers = cumulus_primitives_utility::UnqueuedDmpAsParent<597 // MaxDownwardMessageWeight,598 // XcmExecutor<XcmConfig>,599 // Call,600 // >;601 type OutboundXcmpMessageSource = XcmpQueue;602 type DmpMessageHandler = DmpQueue;603 type ReservedDmpWeight = ReservedDmpWeight;604 type ReservedXcmpWeight = ReservedXcmpWeight;605 type XcmpMessageHandler = XcmpQueue;606}607608impl parachain_info::Config for Runtime {}609610impl cumulus_pallet_aura_ext::Config for Runtime {}611612parameter_types! {613 pub const RelayLocation: MultiLocation = MultiLocation::parent();614 pub const RelayNetwork: NetworkId = NetworkId::Polkadot;615 pub RelayOrigin: Origin = cumulus_pallet_xcm::Origin::Relay.into();616 pub Ancestry: MultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();617}618619/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used620/// when determining ownership of accounts for asset transacting and when attempting to use XCM621/// `Transact` in order to determine the dispatch Origin.622pub type LocationToAccountId = (623 // The parent (Relay-chain) origin converts to the default `AccountId`.624 ParentIsPreset<AccountId>,625 // Sibling parachain origins convert to AccountId via the `ParaId::into`.626 SiblingParachainConvertsVia<Sibling, AccountId>,627 // Straight up local `AccountId32` origins just alias directly to `AccountId`.628 AccountId32Aliases<RelayNetwork, AccountId>,629);630631pub struct OnlySelfCurrency;632impl<B: TryFrom<u128>> MatchesFungible<B> for OnlySelfCurrency {633 fn matches_fungible(a: &MultiAsset) -> Option<B> {634 match (&a.id, &a.fun) {635 (Concrete(_), XcmFungible(ref amount)) => CheckedConversion::checked_from(*amount),636 _ => None,637 }638 }639}640641/// Means for transacting assets on this chain.642pub type LocalAssetTransactor = CurrencyAdapter<643 // Use this currency:644 Balances,645 // Use this currency when it is a fungible asset matching the given location or name:646 OnlySelfCurrency,647 // Do a simple punn to convert an AccountId32 MultiLocation into a native chain account ID:648 LocationToAccountId,649 // Our chain's account ID type (we can't get away without mentioning it explicitly):650 AccountId,651 // We don't track any teleports.652 (),653>;654655/// This is the type we use to convert an (incoming) XCM origin into a local `Origin` instance,656/// ready for dispatching a transaction with Xcm's `Transact`. There is an `OriginKind` which can657/// biases the kind of local `Origin` it will become.658pub type XcmOriginToTransactDispatchOrigin = (659 // Sovereign account converter; this attempts to derive an `AccountId` from the origin location660 // using `LocationToAccountId` and then turn that into the usual `Signed` origin. Useful for661 // foreign chains who want to have a local sovereign account on this chain which they control.662 SovereignSignedViaLocation<LocationToAccountId, Origin>,663 // Native converter for Relay-chain (Parent) location; will converts to a `Relay` origin when664 // recognised.665 RelayChainAsNative<RelayOrigin, Origin>,666 // Native converter for sibling Parachains; will convert to a `SiblingPara` origin when667 // recognised.668 SiblingParachainAsNative<cumulus_pallet_xcm::Origin, Origin>,669 // Superuser converter for the Relay-chain (Parent) location. This will allow it to issue a670 // transaction from the Root origin.671 ParentAsSuperuser<Origin>,672 // Native signed account converter; this just converts an `AccountId32` origin into a normal673 // `Origin::Signed` origin of the same 32-byte value.674 SignedAccountId32AsNative<RelayNetwork, Origin>,675 // Xcm origins can be represented natively under the Xcm pallet's Xcm origin.676 XcmPassthrough<Origin>,677);678679parameter_types! {680 // One XCM operation is 1_000_000 weight - almost certainly a conservative estimate.681 pub UnitWeightCost: Weight = 1_000_000;682 // 1200 UNIQUEs buy 1 second of weight.683 pub const WeightPrice: (MultiLocation, u128) = (MultiLocation::parent(), 1_200 * UNIQUE);684 pub const MaxInstructions: u32 = 100;685 pub const MaxAuthorities: u32 = 100_000;686}687688match_types! {689 pub type ParentOrParentsUnitPlurality: impl Contains<MultiLocation> = {690 MultiLocation { parents: 1, interior: Here } |691 MultiLocation { parents: 1, interior: X1(Plurality { id: BodyId::Unit, .. }) }692 };693}694695pub type Barrier = (696 TakeWeightCredit,697 AllowTopLevelPaidExecutionFrom<Everything>,698 AllowUnpaidExecutionFrom<ParentOrParentsUnitPlurality>,699 // ^^^ Parent & its unit plurality gets free execution700);701702pub struct UsingOnlySelfCurrencyComponents<703 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,704 AssetId: Get<MultiLocation>,705 AccountId,706 Currency: CurrencyT<AccountId>,707 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,708>(709 Weight,710 Currency::Balance,711 PhantomData<(WeightToFee, AssetId, AccountId, Currency, OnUnbalanced)>,712);713impl<714 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,715 AssetId: Get<MultiLocation>,716 AccountId,717 Currency: CurrencyT<AccountId>,718 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,719 > WeightTrader720 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>721{722 fn new() -> Self {723 Self(0, Zero::zero(), PhantomData)724 }725726 fn buy_weight(&mut self, weight: Weight, payment: Assets) -> Result<Assets, XcmError> {727 let amount = WeightToFee::calc(&weight);728 let u128_amount: u128 = amount.try_into().map_err(|_| XcmError::Overflow)?;729730 // location to this parachain through relay chain731 let option1: xcm::v1::AssetId = Concrete(MultiLocation {732 parents: 1,733 interior: X1(Parachain(ParachainInfo::parachain_id().into())),734 });735 // direct location736 let option2: xcm::v1::AssetId = Concrete(MultiLocation {737 parents: 0,738 interior: Here,739 });740741 let required = if payment.fungible.contains_key(&option1) {742 (option1, u128_amount).into()743 } else if payment.fungible.contains_key(&option2) {744 (option2, u128_amount).into()745 } else {746 (Concrete(MultiLocation::default()), u128_amount).into()747 };748749 let unused = payment750 .checked_sub(required)751 .map_err(|_| XcmError::TooExpensive)?;752 self.0 = self.0.saturating_add(weight);753 self.1 = self.1.saturating_add(amount);754 Ok(unused)755 }756757 fn refund_weight(&mut self, weight: Weight) -> Option<MultiAsset> {758 let weight = weight.min(self.0);759 let amount = WeightToFee::calc(&weight);760 self.0 -= weight;761 self.1 = self.1.saturating_sub(amount);762 let amount: u128 = amount.saturated_into();763 if amount > 0 {764 Some((AssetId::get(), amount).into())765 } else {766 None767 }768 }769}770impl<771 WeightToFee: WeightToFeePolynomial<Balance = Currency::Balance>,772 AssetId: Get<MultiLocation>,773 AccountId,774 Currency: CurrencyT<AccountId>,775 OnUnbalanced: OnUnbalancedT<Currency::NegativeImbalance>,776 > Drop777 for UsingOnlySelfCurrencyComponents<WeightToFee, AssetId, AccountId, Currency, OnUnbalanced>778{779 fn drop(&mut self) {780 OnUnbalanced::on_unbalanced(Currency::issue(self.1));781 }782}783784pub struct XcmConfig;785impl Config for XcmConfig {786 type Call = Call;787 type XcmSender = XcmRouter;788 // How to withdraw and deposit an asset.789 type AssetTransactor = LocalAssetTransactor;790 type OriginConverter = XcmOriginToTransactDispatchOrigin;791 type IsReserve = NativeAsset;792 type IsTeleporter = (); // Teleportation is disabled793 type LocationInverter = LocationInverter<Ancestry>;794 type Barrier = Barrier;795 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;796 type Trader = UsingOnlySelfCurrencyComponents<797 IdentityFee<Balance>,798 RelayLocation,799 AccountId,800 Balances,801 (),802 >;803 type ResponseHandler = (); // Don't handle responses for now.804 type SubscriptionService = PolkadotXcm;805806 type AssetTrap = PolkadotXcm;807 type AssetClaims = PolkadotXcm;808}809810// parameter_types! {811// pub const MaxDownwardMessageWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 10;812// }813814/// No local origins on this chain are allowed to dispatch XCM sends/executions.815pub type LocalOriginToLocation = (SignedToAccountId32<Origin, AccountId, RelayNetwork>,);816817/// The means for routing XCM messages which are not for local execution into the right message818/// queues.819pub type XcmRouter = (820 // Two routers - use UMP to communicate with the relay chain:821 cumulus_primitives_utility::ParentAsUmp<ParachainSystem, ()>,822 // ..and XCMP to communicate with the sibling chains.823 XcmpQueue,824);825826impl pallet_evm_coder_substrate::Config for Runtime {827 type GasWeightMapping = FixedGasWeightMapping;828}829830impl pallet_xcm::Config for Runtime {831 type Event = Event;832 type SendXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;833 type XcmRouter = XcmRouter;834 type ExecuteXcmOrigin = EnsureXcmOrigin<Origin, LocalOriginToLocation>;835 type XcmExecuteFilter = Everything;836 type XcmExecutor = XcmExecutor<XcmConfig>;837 type XcmTeleportFilter = Everything;838 type XcmReserveTransferFilter = Everything;839 type Weigher = FixedWeightBounds<UnitWeightCost, Call, MaxInstructions>;840 type LocationInverter = LocationInverter<Ancestry>;841 type Origin = Origin;842 type Call = Call;843 const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;844 type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;845}846847impl cumulus_pallet_xcm::Config for Runtime {848 type Event = Event;849 type XcmExecutor = XcmExecutor<XcmConfig>;850}851852impl cumulus_pallet_xcmp_queue::Config for Runtime {853 type WeightInfo = ();854 type Event = Event;855 type XcmExecutor = XcmExecutor<XcmConfig>;856 type ChannelInfo = ParachainSystem;857 type VersionWrapper = ();858 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;859 type ControllerOrigin = EnsureRoot<AccountId>;860 type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;861}862863impl cumulus_pallet_dmp_queue::Config for Runtime {864 type Event = Event;865 type XcmExecutor = XcmExecutor<XcmConfig>;866 type ExecuteOverweightOrigin = frame_system::EnsureRoot<AccountId>;867}868869impl pallet_aura::Config for Runtime {870 type AuthorityId = AuraId;871 type DisabledValidators = ();872 type MaxAuthorities = MaxAuthorities;873}874875parameter_types! {876 pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();877 pub const CollectionCreationPrice: Balance = 2 * UNIQUE;878}879880impl pallet_common::Config for Runtime {881 type WeightInfo = pallet_common::weights::SubstrateWeight<Self>;882 type Event = Event;883 type Currency = Balances;884 type CollectionCreationPrice = CollectionCreationPrice;885 type TreasuryAccountId = TreasuryAccountId;886 type CollectionDispatch = CollectionDispatchT<Self>;887888 type EvmTokenAddressMapping = EvmTokenAddressMapping;889 type CrossTokenAddressMapping = CrossTokenAddressMapping<Self::AccountId>;890}891892impl pallet_structure::Config for Runtime {893 type Event = Event;894 type Call = Call;895 type WeightInfo = pallet_structure::weights::SubstrateWeight<Self>;896}897898impl pallet_fungible::Config for Runtime {899 type WeightInfo = pallet_fungible::weights::SubstrateWeight<Self>;900}901impl pallet_refungible::Config for Runtime {902 type WeightInfo = pallet_refungible::weights::SubstrateWeight<Self>;903}904impl pallet_nonfungible::Config for Runtime {905 type WeightInfo = pallet_nonfungible::weights::SubstrateWeight<Self>;906}907908impl pallet_proxy_rmrk_core::Config for Runtime {909 type Event = Event;910}911912impl pallet_proxy_rmrk_equip::Config for Runtime {913 type Event = Event;914}915916impl pallet_unique::Config for Runtime {917 type Event = Event;918 type WeightInfo = pallet_unique::weights::SubstrateWeight<Self>;919 type CommonWeightInfo = CommonWeights<Self>;920}921922parameter_types! {923 pub const InflationBlockInterval: BlockNumber = 100; // every time per how many blocks inflation is applied924}925926/// Used for the pallet inflation927impl pallet_inflation::Config for Runtime {928 type Currency = Balances;929 type TreasuryAccountId = TreasuryAccountId;930 type InflationBlockInterval = InflationBlockInterval;931 type BlockNumberProvider = RelayChainBlockNumberProvider<Runtime>;932}933934// parameter_types! {935// pub MaximumSchedulerWeight: Weight = Perbill::from_percent(50) *936// RuntimeBlockWeights::get().max_block;937// pub const MaxScheduledPerBlock: u32 = 50;938// }939940type EvmSponsorshipHandler = (941 UniqueEthSponsorshipHandler<Runtime>,942 pallet_evm_contract_helpers::HelpersContractSponsoring<Runtime>,943);944type SponsorshipHandler = (945 UniqueSponsorshipHandler<Runtime>,946 //pallet_contract_helpers::ContractSponsorshipHandler<Runtime>,947 pallet_evm_transaction_payment::BridgeSponsorshipHandler<Runtime>,948);949950// impl pallet_unq_scheduler::Config for Runtime {951// type Event = Event;952// type Origin = Origin;953// type PalletsOrigin = OriginCaller;954// type Call = Call;955// type MaximumWeight = MaximumSchedulerWeight;956// type ScheduleOrigin = EnsureSigned<AccountId>;957// type MaxScheduledPerBlock = MaxScheduledPerBlock;958// type SponsorshipHandler = SponsorshipHandler;959// type WeightInfo = ();960// }961962impl pallet_evm_transaction_payment::Config for Runtime {963 type EvmSponsorshipHandler = EvmSponsorshipHandler;964 type Currency = Balances;965}966967impl pallet_charge_transaction::Config for Runtime {968 type SponsorshipHandler = SponsorshipHandler;969}970971// impl pallet_contract_helpers::Config for Runtime {972// type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;973// }974975parameter_types! {976 // 0x842899ECF380553E8a4de75bF534cdf6fBF64049977 pub const HelpersContractAddress: H160 = H160([978 0x84, 0x28, 0x99, 0xec, 0xf3, 0x80, 0x55, 0x3e, 0x8a, 0x4d, 0xe7, 0x5b, 0xf5, 0x34, 0xcd, 0xf6, 0xfb, 0xf6, 0x40, 0x49,979 ]);980981 // 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f982 pub const EvmCollectionHelperAddress: H160 = H160([983 0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,984 ]);985}986987impl pallet_evm_contract_helpers::Config for Runtime {988 type ContractAddress = HelpersContractAddress;989 type DefaultSponsoringRateLimit = DefaultSponsoringRateLimit;990}991992impl evm_collection::Config for Runtime {993 type ContractAddress = EvmCollectionHelperAddress;994}995996construct_runtime!(997 pub enum Runtime where998 Block = Block,999 NodeBlock = opaque::Block,1000 UncheckedExtrinsic = UncheckedExtrinsic1001 {1002 ParachainSystem: cumulus_pallet_parachain_system::{Pallet, Call, Config, Storage, Inherent, Event<T>, ValidateUnsigned} = 20,1003 ParachainInfo: parachain_info::{Pallet, Storage, Config} = 21,10041005 Aura: pallet_aura::{Pallet, Config<T>} = 22,1006 AuraExt: cumulus_pallet_aura_ext::{Pallet, Config} = 23,10071008 Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>} = 30,1009 RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Pallet, Storage} = 31,1010 Timestamp: pallet_timestamp::{Pallet, Call, Storage, Inherent} = 32,1011 TransactionPayment: pallet_transaction_payment::{Pallet, Storage} = 33,1012 Treasury: pallet_treasury::{Pallet, Call, Storage, Config, Event<T>} = 34,1013 Sudo: pallet_sudo::{Pallet, Call, Storage, Config<T>, Event<T>} = 35,1014 System: frame_system::{Pallet, Call, Storage, Config, Event<T>} = 36,1015 Vesting: orml_vesting::{Pallet, Storage, Call, Event<T>, Config<T>} = 37,1016 // Vesting: pallet_vesting::{Pallet, Call, Config<T>, Storage, Event<T>} = 37,1017 // Contracts: pallet_contracts::{Pallet, Call, Storage, Event<T>} = 38,10181019 // XCM helpers.1020 XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Call, Storage, Event<T>} = 50,1021 PolkadotXcm: pallet_xcm::{Pallet, Call, Event<T>, Origin} = 51,1022 CumulusXcm: cumulus_pallet_xcm::{Pallet, Call, Event<T>, Origin} = 52,1023 DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 53,10241025 // Unique Pallets1026 Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,1027 Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,1028 // Scheduler: pallet_unq_scheduler::{Pallet, Call, Storage, Event<T>} = 62,1029 // free = 631030 Charging: pallet_charge_transaction::{Pallet, Call, Storage } = 64,1031 // ContractHelpers: pallet_contract_helpers::{Pallet, Call, Storage} = 65,1032 Common: pallet_common::{Pallet, Storage, Event<T>} = 66,1033 Fungible: pallet_fungible::{Pallet, Storage} = 67,1034 Refungible: pallet_refungible::{Pallet, Storage} = 68,1035 Nonfungible: pallet_nonfungible::{Pallet, Storage} = 69,1036 Structure: pallet_structure::{Pallet, Call, Storage, Event<T>} = 70,1037 RmrkCore: pallet_proxy_rmrk_core::{Pallet, Call, Storage, Event<T>} = 71,1038 RmrkEquip: pallet_proxy_rmrk_equip::{Pallet, Call, Storage, Event<T>} = 72,10391040 // Frontier1041 EVM: pallet_evm::{Pallet, Config, Call, Storage, Event<T>} = 100,1042 Ethereum: pallet_ethereum::{Pallet, Config, Call, Storage, Event, Origin} = 101,10431044 EvmCoderSubstrate: pallet_evm_coder_substrate::{Pallet, Storage} = 150,1045 EvmContractHelpers: pallet_evm_contract_helpers::{Pallet, Storage} = 151,1046 EvmTransactionPayment: pallet_evm_transaction_payment::{Pallet} = 152,1047 EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,1048 }1049);10501051pub struct TransactionConverter;10521053impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {1054 fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {1055 UncheckedExtrinsic::new_unsigned(1056 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1057 )1058 }1059}10601061impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {1062 fn convert_transaction(1063 &self,1064 transaction: pallet_ethereum::Transaction,1065 ) -> opaque::UncheckedExtrinsic {1066 let extrinsic = UncheckedExtrinsic::new_unsigned(1067 pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),1068 );1069 let encoded = extrinsic.encode();1070 opaque::UncheckedExtrinsic::decode(&mut &encoded[..])1071 .expect("Encoded extrinsic is always valid")1072 }1073}10741075/// The address format for describing accounts.1076pub type Address = sp_runtime::MultiAddress<AccountId, ()>;1077/// Block header type as expected by this runtime.1078pub type Header = generic::Header<BlockNumber, BlakeTwo256>;1079/// Block type as expected by this runtime.1080pub type Block = generic::Block<Header, UncheckedExtrinsic>;1081/// A Block signed with a Justification1082pub type SignedBlock = generic::SignedBlock<Block>;1083/// BlockId type as expected by this runtime.1084pub type BlockId = generic::BlockId<Block>;1085/// The SignedExtension to the basic transaction logic.1086pub type SignedExtra = (1087 frame_system::CheckSpecVersion<Runtime>,1088 // system::CheckTxVersion<Runtime>,1089 frame_system::CheckGenesis<Runtime>,1090 frame_system::CheckEra<Runtime>,1091 frame_system::CheckNonce<Runtime>,1092 frame_system::CheckWeight<Runtime>,1093 pallet_charge_transaction::ChargeTransactionPayment<Runtime>,1094 //pallet_contract_helpers::ContractHelpersExtension<Runtime>,1095 pallet_ethereum::FakeTransactionFinalizer<Runtime>,1096);1097/// Unchecked extrinsic type as expected by this runtime.1098pub type UncheckedExtrinsic =1099 fp_self_contained::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;1100/// Extrinsic type that has already been checked.1101pub type CheckedExtrinsic = fp_self_contained::CheckedExtrinsic<AccountId, Call, SignedExtra, H160>;1102/// Executive: handles dispatch to the various modules.1103pub type Executive = frame_executive::Executive<1104 Runtime,1105 Block,1106 frame_system::ChainContext<Runtime>,1107 Runtime,1108 AllPalletsReversedWithSystemFirst,1109>;11101111impl_opaque_keys! {1112 pub struct SessionKeys {1113 pub aura: Aura,1114 }1115}11161117impl fp_self_contained::SelfContainedCall for Call {1118 type SignedInfo = H160;11191120 fn is_self_contained(&self) -> bool {1121 match self {1122 Call::Ethereum(call) => call.is_self_contained(),1123 _ => false,1124 }1125 }11261127 fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {1128 match self {1129 Call::Ethereum(call) => call.check_self_contained(),1130 _ => None,1131 }1132 }11331134 fn validate_self_contained(&self, info: &Self::SignedInfo) -> Option<TransactionValidity> {1135 match self {1136 Call::Ethereum(call) => call.validate_self_contained(info),1137 _ => None,1138 }1139 }11401141 fn pre_dispatch_self_contained(1142 &self,1143 info: &Self::SignedInfo,1144 ) -> Option<Result<(), TransactionValidityError>> {1145 match self {1146 Call::Ethereum(call) => call.pre_dispatch_self_contained(info),1147 _ => None,1148 }1149 }11501151 fn apply_self_contained(1152 self,1153 info: Self::SignedInfo,1154 ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {1155 match self {1156 call @ Call::Ethereum(pallet_ethereum::Call::transact { .. }) => Some(call.dispatch(1157 Origin::from(pallet_ethereum::RawOrigin::EthereumTransaction(info)),1158 )),1159 _ => None,1160 }1161 }1162}11631164macro_rules! dispatch_unique_runtime {1165 ($collection:ident.$method:ident($($name:ident),*)) => {{1166 let collection = <Runtime as pallet_common::Config>::CollectionDispatch::dispatch(<pallet_common::CollectionHandle<Runtime>>::try_get($collection)?);1167 let dispatch = collection.as_dyn();11681169 Ok::<_, DispatchError>(dispatch.$method($($name),*))1170 }};1171}11721173impl_common_runtime_apis!();11741175struct CheckInherents;11761177impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {1178 fn check_inherents(1179 block: &Block,1180 relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,1181 ) -> sp_inherents::CheckInherentsResult {1182 let relay_chain_slot = relay_state_proof1183 .read_slot()1184 .expect("Could not read the relay chain slot from the proof");11851186 let inherent_data =1187 cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(1188 relay_chain_slot,1189 sp_std::time::Duration::from_secs(6),1190 )1191 .create_inherent_data()1192 .expect("Could not create the timestamp inherent data");11931194 inherent_data.check_extrinsics(block)1195 }1196}11971198cumulus_pallet_parachain_system::register_validate_block!(1199 Runtime = Runtime,1200 BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::<Runtime, Executive>,1201 CheckInherents = CheckInherents,1202);runtime/quartz/src/lib.rsdiffbeforeafterboth--- a/runtime/quartz/src/lib.rs
+++ b/runtime/quartz/src/lib.rs
@@ -280,6 +280,7 @@
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
evm_collection::CollectionOnMethodCall<Self>,
+ evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -955,7 +956,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionAddress: H160 = H160([
+ pub const EvmCollectionHelperAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -966,7 +967,7 @@
}
impl evm_collection::Config for Runtime {
- type ContractAddress = EvmCollectionAddress;
+ type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
runtime/unique/src/lib.rsdiffbeforeafterboth--- a/runtime/unique/src/lib.rs
+++ b/runtime/unique/src/lib.rs
@@ -284,6 +284,7 @@
pallet_evm_contract_helpers::HelpersOnMethodCall<Self>,
CollectionDispatchT<Self>,
evm_collection::CollectionOnMethodCall<Self>,
+ evm_collection::CollectionHelperOnMethodCall<Self>,
);
type OnCreate = pallet_evm_contract_helpers::HelpersOnCreate<Self>;
type ChainId = ChainId;
@@ -960,7 +961,7 @@
]);
// 0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f
- pub const EvmCollectionAddress: H160 = H160([
+ pub const EvmCollectionHelperAddress: H160 = H160([
0x6c, 0x4e, 0x9f, 0xe1, 0xae, 0x37, 0xa4, 0x1e, 0x93, 0xce, 0xe4, 0x29, 0xe8, 0xe1, 0x88, 0x1a, 0xbd, 0xcb, 0xb5, 0x4f,
]);
}
@@ -971,7 +972,7 @@
}
impl evm_collection::Config for Runtime {
- type ContractAddress = EvmCollectionAddress;
+ type ContractAddress = EvmCollectionHelperAddress;
}
construct_runtime!(
tests/src/eth/api/Collection.soldiffbeforeafterboth--- a/tests/src/eth/api/Collection.sol
+++ b/tests/src/eth/api/Collection.sol
@@ -12,25 +12,17 @@
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
-// Selector: 1e95830f
+// Selector: 15cc740e
interface Collection is Dummy, ERC165 {
- // Selector: create721Collection(string,string,string) 951c0151
- function create721Collection(
- string memory name,
- string memory description,
- string memory tokenPrefix
- ) external view returns (address);
+ // Selector: setSponsor(address) 59753fb1
+ function setSponsor(address sponsor) external view;
- // Selector: setSponsor(address,address) f01fba93
- function setSponsor(address collectionAddress, address sponsor)
- external
- view;
+ // Selector: confirmSponsorship() c8c6a056
+ function confirmSponsorship() external view;
- // Selector: confirmSponsorship(address) abc00001
- function confirmSponsorship(address collectionAddress) external view;
+ // Selector: setLimits(string) 72cb345d
+ function setLimits(string memory limitsJson) external view;
- // Selector: setLimits(address,string) d05638cc
- function setLimits(address collectionAddress, string memory limitsJson)
- external
- view;
+ // Selector: contractAddress() f6b4dfb4
+ function contractAddress() external view returns (address);
}
tests/src/eth/api/CollectionHelper.soldiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/api/CollectionHelper.sol
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: OTHER
+// This code is automatically generated
+
+pragma solidity >=0.8.0 <0.9.0;
+
+// Common stubs holder
+interface Dummy {
+
+}
+
+interface ERC165 is Dummy {
+ function supportsInterface(bytes4 interfaceID) external view returns (bool);
+}
+
+// Selector: 951c0151
+interface CollectionHelper is Dummy, ERC165 {
+ // Selector: create721Collection(string,string,string) 951c0151
+ function create721Collection(
+ string memory name,
+ string memory description,
+ string memory tokenPrefix
+ ) external view returns (address);
+}
tests/src/eth/collectionAbi.jsondiffbeforeafterboth--- a/tests/src/eth/collectionAbi.json
+++ b/tests/src/eth/collectionAbi.json
@@ -1,35 +1,20 @@
[
{
- "inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- }
- ],
+ "inputs": [],
"name": "confirmSponsorship",
"outputs": [],
"stateMutability": "view",
"type": "function"
},
{
- "inputs": [
- { "internalType": "string", "name": "name", "type": "string" },
- { "internalType": "string", "name": "description", "type": "string" },
- { "internalType": "string", "name": "tokenPrefix", "type": "string" }
- ],
- "name": "create721Collection",
+ "inputs": [],
+ "name": "contractAddress",
"outputs": [{ "internalType": "address", "name": "", "type": "address" }],
"stateMutability": "view",
"type": "function"
},
{
"inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- },
{ "internalType": "string", "name": "limitsJson", "type": "string" }
],
"name": "setLimits",
@@ -39,11 +24,6 @@
},
{
"inputs": [
- {
- "internalType": "address",
- "name": "collectionAddress",
- "type": "address"
- },
{ "internalType": "address", "name": "sponsor", "type": "address" }
],
"name": "setSponsor",
tests/src/eth/collectionHelperAbi.jsondiffbeforeafterboth--- /dev/null
+++ b/tests/src/eth/collectionHelperAbi.json
@@ -0,0 +1,22 @@
+[
+ {
+ "inputs": [
+ { "internalType": "string", "name": "name", "type": "string" },
+ { "internalType": "string", "name": "description", "type": "string" },
+ { "internalType": "string", "name": "tokenPrefix", "type": "string" }
+ ],
+ "name": "create721Collection",
+ "outputs": [{ "internalType": "address", "name": "", "type": "address" }],
+ "stateMutability": "view",
+ "type": "function"
+ },
+ {
+ "inputs": [
+ { "internalType": "bytes4", "name": "interfaceID", "type": "bytes4" }
+ ],
+ "name": "supportsInterface",
+ "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
+ "stateMutability": "view",
+ "type": "function"
+ }
+]
tests/src/eth/createCollection.test.tsdiffbeforeafterboth--- a/tests/src/eth/createCollection.test.ts
+++ b/tests/src/eth/createCollection.test.ts
@@ -20,11 +20,12 @@
import {expect} from 'chai';
import {getCreatedCollectionCount, getDetailedCollectionInfo} from '../util/helpers';
import {
- collectionHelper,
+ evmCollectionHelper,
collectionIdFromAddress,
collectionIdToAddress,
createEthAccount,
createEthAccountWithBalance,
+ evmCollection,
GAS_ARGS,
itWeb3,
normalizeAddress,
@@ -41,7 +42,7 @@
describe('Create collection from EVM', () => {
itWeb3('Create collection', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
const collectionName = 'CollectionEVM';
const description = 'Some description';
const tokenPrefix = 'token prefix';
@@ -63,26 +64,27 @@
itWeb3('Set sponsorship', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- let result = await helper.methods.create721Collection('Sponsor collection', '1', '1').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ let result = await collectionHelper.methods.create721Collection('Sponsor collection', '1', '1').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const sponsor = await createEthAccountWithBalance(api, web3);
- result = await helper.methods.setSponsor(collectionIdAddress, sponsor).send();
- let collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.sponsorship.isUnconfirmed).to.be.true;
- expect(collection.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
- await expect(helper.methods.confirmSponsorship(collectionIdAddress).call()).to.be.rejectedWith('Caller is not set as sponsor');
- const sponsorHelper = collectionHelper(web3, sponsor);
- await sponsorHelper.methods.confirmSponsorship(collectionIdAddress).send();
- collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.sponsorship.isConfirmed).to.be.true;
- expect(collection.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ result = await collectionEvm.methods.setSponsor(sponsor).send();
+ let collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isUnconfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asUnconfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
+ await expect(collectionEvm.methods.confirmSponsorship().call()).to.be.rejectedWith('Caller is not set as sponsor');
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await sponsorCollection.methods.confirmSponsorship().send();
+ collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.sponsorship.isConfirmed).to.be.true;
+ expect(collectionSub.sponsorship.asConfirmed.toHuman()).to.be.eq(evmToAddress(sponsor));
});
itWeb3('Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- const result = await helper.methods.create721Collection('Const collection', '5', '5').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Const collection', '5', '5').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const limits = {
accountTokenOwnershipLimit: 1000,
@@ -97,23 +99,24 @@
};
const limitsJson = JSON.stringify(limits, null, 1);
- await helper.methods.setLimits(collectionIdAddress, limitsJson).send();
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
+ await collectionEvm.methods.setLimits(limitsJson).send();
- const collection = (await getDetailedCollectionInfo(api, collectionId))!;
- expect(collection.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
- expect(collection.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
- expect(collection.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
- expect(collection.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
- expect(collection.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
- expect(collection.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
- expect(collection.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
- expect(collection.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
- expect(collection.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
+ const collectionSub = (await getDetailedCollectionInfo(api, collectionId))!;
+ expect(collectionSub.limits.accountTokenOwnershipLimit.unwrap().toNumber()).to.be.eq(limits.accountTokenOwnershipLimit);
+ expect(collectionSub.limits.sponsoredDataSize.unwrap().toNumber()).to.be.eq(limits.sponsoredDataSize);
+ expect(collectionSub.limits.sponsoredDataRateLimit.unwrap().asBlocks.toNumber()).to.be.eq(limits.sponsoredDataRateLimit.Blocks);
+ expect(collectionSub.limits.tokenLimit.unwrap().toNumber()).to.be.eq(limits.tokenLimit);
+ expect(collectionSub.limits.sponsorTransferTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorTransferTimeout);
+ expect(collectionSub.limits.sponsorApproveTimeout.unwrap().toNumber()).to.be.eq(limits.sponsorApproveTimeout);
+ expect(collectionSub.limits.ownerCanTransfer.toHuman()).to.be.eq(limits.ownerCanTransfer);
+ expect(collectionSub.limits.ownerCanDestroy.toHuman()).to.be.eq(limits.ownerCanDestroy);
+ expect(collectionSub.limits.transfersEnabled.toHuman()).to.be.eq(limits.transfersEnabled);
});
itWeb3('Check tokenURI', async ({web3, api}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
let result = await helper.methods.create721Collection('Mint collection', '6', '6').send();
const {collectionIdAddress, collectionId} = await getCollectionAddressFromResult(api, result);
const receiver = createEthAccount(web3);
@@ -154,7 +157,7 @@
describe('(!negative tests!) Create collection from EVM', () => {
itWeb3('(!negative test!) Create collection (bad lengths)', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
{
const MAX_NAME_LENGHT = 64;
const collectionName = 'A'.repeat(MAX_NAME_LENGHT + 1);
@@ -188,7 +191,7 @@
itWeb3('(!negative test!) Create collection (no funds)', async ({web3}) => {
const owner = await createEthAccount(web3);
- const helper = collectionHelper(web3, owner);
+ const helper = evmCollectionHelper(web3, owner);
const collectionName = 'A';
const description = 'A';
const tokenPrefix = 'A';
@@ -200,24 +203,24 @@
itWeb3('(!negative test!) Collection address (Contract is not an unique collection)', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
const collectionAddressWithBadPrefix = '0x00112233445566778899AABBCCDDEEFF00112233';
+ const collectionEvm = evmCollection(web3, owner, collectionAddressWithBadPrefix);
const EXPECTED_ERROR = 'Contract is not an unique collection';
{
const sponsor = await createEthAccountWithBalance(api, web3);
- await expect(helper.methods
- .setSponsor(collectionAddressWithBadPrefix, sponsor)
+ await expect(collectionEvm.methods
+ .setSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
- const sponsorHelper = collectionHelper(web3, sponsor);
- await expect(sponsorHelper.methods
- .confirmSponsorship(collectionAddressWithBadPrefix)
+ const sponsorCollection = evmCollection(web3, sponsor, collectionAddressWithBadPrefix);
+ await expect(sponsorCollection.methods
+ .confirmSponsorship()
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
{
const limits = '{"account_token_ownership_limit":1000}';
- await expect(helper.methods
- .setLimits(collectionAddressWithBadPrefix, limits)
+ await expect(collectionEvm.methods
+ .setLimits(limits)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
@@ -225,38 +228,39 @@
itWeb3('(!negative test!) Check owner', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
const notOwner = await createEthAccount(web3);
- const helperFromOwner = collectionHelper(web3, owner);
- const helperFromNotOwner = collectionHelper(web3, notOwner);
- const result = await helperFromOwner.methods.create721Collection('A', 'A', 'A').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('A', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const contractEvmFromNotOwner = evmCollection(web3, notOwner, collectionIdAddress);
const EXPECTED_ERROR = 'NoPermission';
{
const sponsor = await createEthAccountWithBalance(api, web3);
- await expect(helperFromNotOwner.methods
- .setSponsor(collectionIdAddress, sponsor)
+ await expect(contractEvmFromNotOwner.methods
+ .setSponsor(sponsor)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
- const sponsorHelper = collectionHelper(web3, sponsor);
- await expect(sponsorHelper.methods
- .confirmSponsorship(collectionIdAddress)
+ const sponsorCollection = evmCollection(web3, sponsor, collectionIdAddress);
+ await expect(sponsorCollection.methods
+ .confirmSponsorship()
.call()).to.be.rejectedWith('Caller is not set as sponsor');
}
{
const limits = '{"account_token_ownership_limit":1000}';
- await expect(helperFromNotOwner.methods
- .setLimits(collectionIdAddress, limits)
+ await expect(contractEvmFromNotOwner.methods
+ .setLimits(limits)
.call()).to.be.rejectedWith(EXPECTED_ERROR);
}
});
itWeb3('(!negative test!) Set limits', async ({api, web3}) => {
const owner = await createEthAccountWithBalance(api, web3);
- const helper = collectionHelper(web3, owner);
- const result = await helper.methods.create721Collection('Schema collection', 'A', 'A').send();
+ const collectionHelper = evmCollectionHelper(web3, owner);
+ const result = await collectionHelper.methods.create721Collection('Schema collection', 'A', 'A').send();
const {collectionIdAddress} = await getCollectionAddressFromResult(api, result);
+ const collectionEvm = evmCollection(web3, owner, collectionIdAddress);
const badJson = '{accountTokenOwnershipLimit: 1000}';
- await expect(helper.methods
- .setLimits(collectionIdAddress, badJson)
+ await expect(collectionEvm.methods
+ .setLimits(badJson)
.call()).to.be.rejectedWith('Parse JSON error:');
});
});
\ No newline at end of file
tests/src/eth/util/helpers.tsdiffbeforeafterboth--- a/tests/src/eth/util/helpers.ts
+++ b/tests/src/eth/util/helpers.ts
@@ -29,6 +29,7 @@
import privateKey from '../../substrate/privateKey';
import contractHelpersAbi from './contractHelpersAbi.json';
import collectionAbi from '../collectionAbi.json';
+import collectionHelperAbi from '../collectionHelperAbi.json';
import getBalance from '../../substrate/get-balance';
import waitNewBlocks from '../../substrate/wait-new-blocks';
@@ -283,13 +284,23 @@
}
/**
- * pallet evm_collection
+ * evm collection helper
* @param web3
* @param caller - eth address
* @returns
*/
-export function collectionHelper(web3: Web3, caller: string) {
- return new web3.eth.Contract(collectionAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+export function evmCollectionHelper(web3: Web3, caller: string) {
+ return new web3.eth.Contract(collectionHelperAbi as any, '0x6c4e9fe1ae37a41e93cee429e8e1881abdcbb54f', {from: caller, ...GAS_ARGS});
+}
+
+/**
+ * evm collection
+ * @param web3
+ * @param caller - eth address
+ * @returns
+ */
+export function evmCollection(web3: Web3, caller: string, collection: string) {
+ return new web3.eth.Contract(collectionAbi as any, collection, {from: caller, ...GAS_ARGS});
}
/**
tests/src/interfaces/unique/types.tsdiffbeforeafterboth--- a/tests/src/interfaces/unique/types.ts
+++ b/tests/src/interfaces/unique/types.ts
@@ -6,9 +6,6 @@
import type { AccountId32, Call, H160, H256, MultiAddress, Perbill, Permill } from '@polkadot/types/interfaces/runtime';
import type { Event } from '@polkadot/types/interfaces/system';
-/** @name BTreeSet */
-export interface BTreeSet extends BTreeSet<Bytes> {}
-
/** @name CumulusPalletDmpQueueCall */
export interface CumulusPalletDmpQueueCall extends Enum {
readonly isServiceOverweight: boolean;