git.delta.rocks / unique-network / refs/commits / 415e3d612ac1

difftreelog

feat eth address mapping

Yaroslav Bolyukin2021-04-30parent: #9936e25.patch.diff
in: master

5 files changed

addedpallets/nft/src/eth/account.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/nft/src/eth/account.rs
@@ -0,0 +1,135 @@
+use crate::Config;
+use codec::{Encode, EncodeLike, Decode};
+use sp_core::{H160, H256, crypto::AccountId32};
+use core::cmp::Ordering;
+#[cfg(feature = "std")]
+use serde::{Serialize, Deserialize};
+use pallet_evm::AddressMapping;
+use sp_std::vec::Vec;
+use sp_std::clone::Clone;
+
+pub trait CrossAccountId<AccountId>: 
+    Encode + EncodeLike + Decode + 
+    Clone + PartialEq + Ord + core::fmt::Debug // + 
+    // Serialize + Deserialize<'static> 
+{
+    fn as_sub(&self) -> &AccountId;
+    fn as_eth(&self) -> &H160;
+
+    fn from_sub(account: AccountId) -> Self;
+    fn from_eth(account: H160) -> Self;
+}
+
+#[derive(Eq)]
+#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
+pub struct BasicCrossAccountId<T: Config> {
+    /// If true - then ethereum is canonical encoding
+    from_ethereum: bool,
+    substrate: T::AccountId,
+    ethereum: H160,
+}
+
+impl<T: Config> core::fmt::Debug for BasicCrossAccountId<T> {
+    fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result {
+        if self.from_ethereum {
+            fmt.debug_tuple("CrossAccountId::Ethereum")
+                .field(&self.ethereum)
+                .finish()
+        } else {
+            fmt.debug_tuple("CrossAccountId::Substrate")
+                .field(&self.substrate)
+                .finish()
+        }
+    }
+}
+
+impl<T: Config> PartialOrd for BasicCrossAccountId<T> {
+    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+        Some(self.substrate.cmp(&other.substrate))
+    }
+}
+
+impl<T: Config> Ord for BasicCrossAccountId<T> {
+    fn cmp(&self, other: &Self) -> Ordering {
+        self.partial_cmp(other).expect("substrate account is total ordered")
+    }
+}
+
+impl<T: Config> PartialEq for BasicCrossAccountId<T> {
+    fn eq(&self, other: &Self) -> bool {
+        if self.from_ethereum == other.from_ethereum {
+            self.substrate == other.substrate && self.ethereum == other.ethereum
+        } else if self.from_ethereum {
+            // ethereum is canonical encoding, but we need to compare derived address
+            self.substrate == other.substrate
+        } else {
+            self.ethereum == other.ethereum
+        }
+    }
+}
+impl<T: Config> Clone for BasicCrossAccountId<T> {
+    fn clone(&self) -> Self {
+        Self {
+            from_ethereum: self.from_ethereum,
+            substrate: self.substrate.clone(),
+            ethereum: self.ethereum,
+        }
+    }
+}
+impl<T: Config> Encode for BasicCrossAccountId<T> {
+    fn encode(&self) -> Vec<u8> {
+        let as_result = if !self.from_ethereum {
+            Ok(self.substrate.clone())
+        } else {
+            Err(self.ethereum)
+        };
+        as_result.encode()
+    }
+}
+impl<T: Config> EncodeLike for BasicCrossAccountId<T> {}
+impl<T: Config> Decode for BasicCrossAccountId<T> {
+    fn decode<I>(input: &mut I) -> Result<Self, codec::Error>
+        where I: codec::Input
+    {
+        Ok(match <Result<T::AccountId, H160>>::decode(input)? {
+            Ok(s) => Self::from_sub(s),
+            Err(e) => Self::from_eth(e),
+        })
+    }
+}
+impl<T: Config> CrossAccountId<T::AccountId> for BasicCrossAccountId<T> {
+    fn as_sub(&self) -> &T::AccountId {
+        &self.substrate
+    }
+    fn as_eth(&self) -> &H160 {
+        &self.ethereum
+    }
+    fn from_sub(substrate: T::AccountId) -> Self {
+        Self {
+            ethereum: T::EvmBackwardsAddressMapping::from_account_id(substrate.clone()),
+            substrate,
+            from_ethereum: false,
+        }
+    }
+    fn from_eth(ethereum: H160) -> Self {
+        Self {
+            ethereum,
+            substrate: T::EvmAddressMapping::into_account_id(ethereum),
+            from_ethereum: true,
+        }
+    }
+}
+
+pub trait EvmBackwardsAddressMapping<AccountId> {
+    fn from_account_id(account_id: AccountId) -> H160;
+}
+
+/// Should have same mapping as EnsureAddressTruncated
+pub struct MapBackwardsAddressTruncated;
+impl EvmBackwardsAddressMapping<AccountId32> for MapBackwardsAddressTruncated {
+    fn from_account_id(account_id: AccountId32) -> H160 {
+        let mut out = [0; 20];
+        out.copy_from_slice(&(account_id.as_ref() as &[u8])[0..20]);
+        H160(out)
+    }
+}
\ No newline at end of file
addedpallets/nft/src/eth/mod.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/nft/src/eth/mod.rs
@@ -0,0 +1,2 @@
+pub mod account;
+use account::CrossAccountId;
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -8,9 +8,6 @@
 #![cfg_attr(not(feature = "std"), no_std)]
 
 #[cfg(feature = "std")]
-pub use std::*;
-
-#[cfg(feature = "std")]
 pub use serde::*;
 
 use core::ops::{Deref, DerefMut};
@@ -33,6 +30,7 @@
 };
 
 use frame_system::{self as system, ensure_signed, ensure_root};
+use sp_core::{H160, H256};
 use sp_runtime::sp_std::prelude::Vec;
 use sp_runtime::{
     traits::{
@@ -45,6 +43,7 @@
 };
 use sp_runtime::traits::StaticLookup;
 use pallet_contracts::chain_extension::UncheckedFrom;
+use pallet_evm::AddressMapping;
 use pallet_transaction_payment::OnChargeTransaction;
 
 #[cfg(test)]
@@ -54,6 +53,9 @@
 mod tests;
 
 mod default_weights;
+mod eth;
+
+pub use eth::account::*;
 
 pub const MAX_DECIMAL_POINTS: DecimalPoints = 30;
 pub const MAX_REFUNGIBLE_PIECES: u128 = 1_000_000_000_000_000_000_000;
@@ -164,7 +166,7 @@
 #[derive(Encode, Decode, Clone, PartialEq)]
 #[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
 pub struct Collection<T: Config> {
-    pub owner: T::AccountId,
+    pub owner: T::CrossAccountId,
     pub mode: CollectionMode,
     pub access: AccessMode,
     pub decimal_points: DecimalPoints,
@@ -174,7 +176,7 @@
     pub mint_mode: bool,
     pub offchain_schema: Vec<u8>,
     pub schema_version: SchemaVersion,
-    pub sponsorship: SponsorshipState<T::AccountId>,
+    pub sponsorship: SponsorshipState<T::CrossAccountId>,
     pub limits: CollectionLimits<T::BlockNumber>, // Collection private restrictions 
     pub variable_on_chain_schema: Vec<u8>, //
     pub const_on_chain_schema: Vec<u8>, //
@@ -461,6 +463,11 @@
     /// Weight information for extrinsics in this pallet.
 	type WeightInfo: WeightInfo;
 
+    type EvmAddressMapping: pallet_evm::AddressMapping<Self::AccountId>;
+    type EvmBackwardsAddressMapping: EvmBackwardsAddressMapping<Self::AccountId>;
+    type EvmWithdrawOrigin: pallet_evm::EnsureAddressOrigin<Self::Origin, Success = Self::AccountId>;
+
+	type CrossAccountId: CrossAccountId<Self::AccountId>;
     type Currency: Currency<Self::AccountId>;
     type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;
     type TreasuryAccountId: Get<Self::AccountId>;
@@ -525,7 +532,7 @@
         pub CollectionById get(fn collection_id) config(): map hasher(blake2_128_concat) CollectionId => Option<Collection<T>> = None;
         /// List of collection admins
         /// Collection id (controlled?2)
-        pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::AccountId>;
+        pub AdminList get(fn admin_list_collection): map hasher(blake2_128_concat) CollectionId => Vec<T::CrossAccountId>;
         /// Whitelisted collection users
         /// Collection id (controlled?2), user id (controlled?3)
         pub WhiteList get(fn white_list): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => bool;
@@ -542,11 +549,11 @@
 
         //#region Item collections
         /// Collection id (controlled?2), token id (controlled?1)
-        pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::AccountId>>;
+        pub NftItemList get(fn nft_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<NftItemType<T::CrossAccountId>>;
         /// Collection id (controlled?2), owner (controlled?2)
         pub FungibleItemList get(fn fungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) T::AccountId => FungibleItemType;
         /// Collection id (controlled?2), token id (controlled?1)
-        pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::AccountId>>;
+        pub ReFungibleItemList get(fn refungible_item_id) config(): double_map hasher(blake2_128_concat) CollectionId, hasher(blake2_128_concat) TokenId => Option<ReFungibleItemType<T::CrossAccountId>>;
         //#endregion
 
         //#region Index list
@@ -610,7 +617,7 @@
 decl_event!(
     pub enum Event<T>
     where
-        AccountId = <T as system::Config>::AccountId,
+        CrossAccountId = <T as Config>::CrossAccountId,
     {
         /// New collection was created
         /// 
@@ -621,7 +628,7 @@
         /// * mode: [CollectionMode] converted into u8.
         /// 
         /// * account_id: Collection owner.
-        CollectionCreated(CollectionId, u8, AccountId),
+        CollectionCreated(CollectionId, u8, CrossAccountId),
 
         /// New item was created.
         /// 
@@ -632,7 +639,7 @@
         /// * item_id: Id of an item. Unique within the collection.
         ///
         /// * recipient: Owner of newly created item 
-        ItemCreated(CollectionId, TokenId, AccountId),
+        ItemCreated(CollectionId, TokenId, CrossAccountId),
 
         /// Collection item was burned.
         /// 
@@ -654,7 +661,7 @@
         /// * recipient: New owner of item
         ///
         /// * amount: Always 1 for NFT
-        Transfer(CollectionId, TokenId, AccountId, AccountId, u128),
+        Transfer(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
 
         /// * collection_id
         ///
@@ -665,7 +672,7 @@
         /// * spender
         ///
         /// * amount
-        Approved(CollectionId, TokenId, AccountId, AccountId, u128),
+        Approved(CollectionId, TokenId, CrossAccountId, CrossAccountId, u128),
     }
 );
 
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "256"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata, H160, U256 };21use sp_runtime::{22	Permill, Perbill, Percent,23	ModuleId,24	create_runtime_str, generic, impl_opaque_keys,25	traits::{26		Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,27		IdentityLookup, NumberFor, Verify, AccountIdConversion,28	},29	transaction_validity::{TransactionSource, TransactionValidity},30	ApplyExtrinsicResult, MultiSignature,31};32#[cfg(feature = "std")]33use sp_version::NativeVersion;34use sp_version::RuntimeVersion;35pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};36// A few exports that help ease life for downstream crates.37pub use pallet_balances::Call as BalancesCall;38pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};39pub use pallet_contracts::{Schedule as ContractsSchedule };40pub use frame_support::{41	construct_runtime,42	dispatch::DispatchResult,43	parameter_types,44	StorageValue,45	traits::{46		Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,47		LockIdentifier, FindAuthor,48	},49	weights::{50		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},51		DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight,52		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients53	},54	ConsensusEngineId,55};56use pallet_contracts::weights::WeightInfo;57// #[cfg(any(feature = "std", test))]58use frame_system::{59	self as system,60	EnsureRoot,61	limits::{BlockWeights, BlockLength},62};63use sp_std::{prelude::*, marker::PhantomData};64use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};65use smallvec::smallvec;66use codec::{Encode, Decode};67use pallet_evm::{Account as EVMAccount, FeeCalculator};68use fp_rpc::TransactionStatus;69use sp_core::H256;7071pub use pallet_timestamp::Call as TimestampCall;7273mod chain_extension;74use crate::chain_extension::{ NFTExtension, Imbalance };7576/// Struct that handles the conversion of Balance -> `u64`. This is used for77/// staking's election calculation.78pub struct CurrencyToVoteHandler;7980impl CurrencyToVoteHandler {81	fn factor() -> Balance {82		(Balances::total_issuance() / u64::max_value() as Balance).max(1)83	}84}8586impl Convert<Balance, u64> for CurrencyToVoteHandler {87	fn convert(x: Balance) -> u64 {88		(x / Self::factor()) as u6489	}90}9192impl Convert<u128, Balance> for CurrencyToVoteHandler {93	fn convert(x: u128) -> Balance {94		x * Self::factor()95	}96}9798/// Re-export a nft pallet99/// TODO: Check this re-export. Is this safe and good style?100extern crate pallet_nft;101pub use pallet_nft::*;102103/// An index to a block.104pub type BlockNumber = u32;105106/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.107pub type Signature = MultiSignature;108109/// Some way of identifying an account on the chain. We intentionally make it equivalent110/// to the public key of our transaction signing scheme.111pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;112113/// The type for looking up accounts. We don't expect more than 4 billion of them, but you114/// never know...115pub type AccountIndex = u32;116117/// Balance of an account.118pub type Balance = u128;119120/// Index of a transaction in the chain.121pub type Index = u32;122123/// A hash of some data used by the chain.124pub type Hash = sp_core::H256;125126/// Digest item type.127pub type DigestItem = generic::DigestItem<Hash>;128129mod nft_weights;130131/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know132/// the specifics of the runtime. They can then be made to be agnostic over specific formats133/// of data like extrinsics, allowing for them to continue syncing the network through upgrades134/// to even the core data structures.135pub mod opaque {136	use super::*;137138	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;139140	/// Opaque block header type.141	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;142	/// Opaque block type.143	pub type Block = generic::Block<Header, UncheckedExtrinsic>;144	/// Opaque block identifier type.145	pub type BlockId = generic::BlockId<Block>;146147	impl_opaque_keys! {148		pub struct SessionKeys {149			pub aura: Aura,150			pub grandpa: Grandpa,151		}152	}153}154155/// This runtime version.156pub const VERSION: RuntimeVersion = RuntimeVersion {157	spec_name: create_runtime_str!("nft"),158	impl_name: create_runtime_str!("nft"),159	authoring_version: 1,160	spec_version: 3,161	impl_version: 1,162	apis: RUNTIME_API_VERSIONS,163	transaction_version: 1,164};165166pub const MILLISECS_PER_BLOCK: u64 = 6000;167168pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;169170// These time units are defined in number of blocks.171pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);172pub const HOURS: BlockNumber = MINUTES * 60;173pub const DAYS: BlockNumber = HOURS * 24;174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178	NativeVersion {179		runtime_version: VERSION,180		can_author_with: Default::default(),181	}182}183184/// Provides a membership set with only the configured aura users185pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);186impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {187	fn contains(t: &AccountId) -> bool {188		let arr: [u8; 32] = *t.as_ref();189		let raw_key: Vec<u8> = Vec::from(arr);190191		match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {192			Some(_) => true,193			None => false,194		}195	}196	fn sorted_members() -> Vec<AccountId> {197		let mut members: Vec<AccountId> = Vec::new();198		for auth in pallet_aura::Module::<Runtime>::authorities() {199			let mut arr: [u8; 32] = Default::default();200			let bor_arr = auth.clone().to_raw_vec();201			let slice = bor_arr.as_slice();202			arr.copy_from_slice(slice);203			members.push(AccountId::from(arr));204		}205		members206	}207	fn count() -> usize {208		pallet_aura::Module::<Runtime>::authorities().len()209	}210}211212impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {213	fn min_len() -> usize {214		1215	}216	fn max_len() -> usize {217		100218	}219}220221type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;222223pub struct DealWithFees;224impl OnUnbalanced<NegativeImbalance> for DealWithFees {225	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {226		if let Some(fees) = fees_then_tips.next() {227			// for fees, 100% to treasury228			let mut split = fees.ration(100, 0);229			if let Some(tips) = fees_then_tips.next() {230				// for tips, if any, 100% to treasury231				tips.ration_merge_into(100, 0, &mut split);232			}233			Treasury::on_unbalanced(split.0);234			// Author::on_unbalanced(split.1);235		}236	}237}238239// impl OnUnbalanced<NegativeImbalance> for DealWithFees {240// 	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {241// 		if let Some(fees) = fees_then_tips.next() {242// 			// for fees, 100% to treasury243// 			let mut split = fees.ration(100, 0);244// 			if let Some(tips) = fees_then_tips.next() {245// 				// for tips, if any, 100% to treasury246// 				tips.ration_merge_into(100, 0, &mut split);247// 			}248// 			Treasury::on_unbalanced(split.0);249// 			// Author::on_unbalanced(split.1);250// 		}251// 	}252// }253254/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.255/// This is used to limit the maximal weight of a single extrinsic.256const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);257/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used258/// by  Operational  extrinsics.259const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);260/// We allow for 2 seconds of compute with a 6 second average block time.261const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;262263parameter_types! {264	pub const BlockHashCount: BlockNumber = 2400;265	pub RuntimeBlockLength: BlockLength =266		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);267	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);268	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;269	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()270		.base_block(BlockExecutionWeight::get())271		.for_class(DispatchClass::all(), |weights| {272			weights.base_extrinsic = ExtrinsicBaseWeight::get();273		})274		.for_class(DispatchClass::Normal, |weights| {275			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);276		})277		.for_class(DispatchClass::Operational, |weights| {278			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);279			// Operational transactions have some extra reserved space, so that they280			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.281			weights.reserved = Some(282				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT283			);284		})285		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)286		.build_or_panic();287	pub const Version: RuntimeVersion = VERSION;288	pub const SS58Prefix: u8 = 42;289}290291impl system::Config for Runtime {292	/// The basic call filter to use in dispatchable.293	type BaseCallFilter = ();294	/// The identifier used to distinguish between accounts.295	type AccountId = AccountId;296	/// The aggregated dispatch type that is available for extrinsics.297	type Call = Call;298	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.299	type Lookup = IdentityLookup<AccountId>;300	/// The index type for storing how many extrinsics an account has signed.301	type Index = Index;302	/// The index type for blocks.303	type BlockNumber = BlockNumber;304	/// The type for hashing blocks and tries.305	type Hash = Hash;306	/// The hashing algorithm used.307	type Hashing = BlakeTwo256;308	/// The header type.309	type Header = generic::Header<BlockNumber, BlakeTwo256>;310	/// The ubiquitous event type.311	type Event = Event;312	/// The ubiquitous origin type.313	type Origin = Origin;314	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).315	type BlockHashCount = BlockHashCount;316	/// The weight of database operations that the runtime can invoke.317	type DbWeight = RocksDbWeight;318	/// The weight of the overhead invoked on the block import process, independent of the319	/// extrinsics included in that block.320	type BlockWeights = RuntimeBlockWeights;321	/// Version of the runtime.322	type Version = Version;323 	/// This type is being generated by `construct_runtime!`.324	type PalletInfo = PalletInfo;325	/// What to do if a new account is created.326	type OnNewAccount = ();327	/// What to do if an account is fully reaped from the system.328	type OnKilledAccount = ();329	/// The data to be stored in an account.330	type AccountData = pallet_balances::AccountData<Balance>;331	/// Weight information for the extrinsics of this pallet.332	type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;333334	type BlockLength = RuntimeBlockLength;335	type SS58Prefix = SS58Prefix;336}337338impl pallet_aura::Config for Runtime {339	type AuthorityId = AuraId;340}341342parameter_types! {343	pub const ChainId: u64 = 8888;344}345346impl pallet_evm::Config for Runtime {347	type FeeCalculator = ();348	type GasWeightMapping = ();349	type CallOrigin = EnsureAddressTruncated;350	type WithdrawOrigin = EnsureAddressTruncated;351	type AddressMapping = HashedAddressMapping<BlakeTwo256>;352	type Currency = Balances;353	type Event = Event;354	type Precompiles = ();355	type ChainId = ChainId;356	type Runner = pallet_evm::runner::stack::Runner<Self>;357	type OnChargeTransaction = ();358}359360pub struct EthereumFindAuthor<F>(PhantomData<F>);361impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>362{363	fn find_author<'a, I>(digests: I) -> Option<H160> where364		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>365	{366		if let Some(author_index) = F::find_author(digests) {367			let authority_id = Aura::authorities()[author_index as usize].clone();368			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));369		}370		None371	}372}373374parameter_types! {375	pub BlockGasLimit: U256 = U256::from(u32::max_value());376}377378impl pallet_ethereum::Config for Runtime {379	type Event = Event;380	type FindAuthor = EthereumFindAuthor<Aura>;381	type StateRoot = pallet_ethereum::IntermediateStateRoot;382	type BlockGasLimit = BlockGasLimit;383}384385impl pallet_grandpa::Config for Runtime {386	type Event = Event;387	type Call = Call;388389	type KeyOwnerProofSystem = ();390391	type KeyOwnerProof =392		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;393394	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(395		KeyTypeId,396		GrandpaId,397	)>>::IdentificationTuple;398399	type HandleEquivocation = ();400401	type WeightInfo = ();402}403404parameter_types! {405	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;406}407408impl pallet_timestamp::Config for Runtime {409	/// A timestamp: milliseconds since the unix epoch.410	type Moment = u64;411	type OnTimestampSet = Aura;412	type MinimumPeriod = MinimumPeriod;413	type WeightInfo = ();414}415416parameter_types! {417	// pub const ExistentialDeposit: u128 = 500;418	pub const ExistentialDeposit: u128 = 0;419	pub const MaxLocks: u32 = 50;420}421422impl pallet_balances::Config for Runtime {423	type MaxLocks = MaxLocks;424	/// The type for recording an account's balance.425	type Balance = Balance;426	/// The ubiquitous event type.427	type Event = Event;428	type DustRemoval = Treasury;429	type ExistentialDeposit = ExistentialDeposit;430	type AccountStore = System;431	type WeightInfo = ();432}433434pub const MICROUNIQUE: Balance = 1_000_000_000;435pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;436pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;437pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;438439pub const fn deposit(items: u32, bytes: u32) -> Balance {440	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE441}442443parameter_types! {444	pub const TombstoneDeposit: Balance = deposit(445		0,446		sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32447	);448	pub const DepositPerContract: Balance = TombstoneDeposit::get();449	pub const DepositPerStorageByte: Balance = deposit(0, 1);450	pub const DepositPerStorageItem: Balance = deposit(1, 0);451	pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);452	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;453	pub const SignedClaimHandicap: u32 = 2;454	pub const MaxDepth: u32 = 32;455	pub const MaxValueSize: u32 = 16 * 1024;456	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb457	// The lazy deletion runs inside on_initialize.458	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *459		RuntimeBlockWeights::get().max_block;460	// The weight needed for decoding the queue should be less or equal than a fifth461	// of the overall weight dedicated to the lazy deletion.462	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (463			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -464			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)465		)) / 5) as u32;466}467468469impl pallet_contracts::Config for Runtime {470	type Time = Timestamp;471	type Randomness = RandomnessCollectiveFlip;472	type Currency = Balances;473	type Event = Event;474	type RentPayment = ();475	type SignedClaimHandicap = SignedClaimHandicap;476	type TombstoneDeposit = TombstoneDeposit;477	type DepositPerContract = DepositPerContract;478	type DepositPerStorageByte = DepositPerStorageByte;479	type DepositPerStorageItem = DepositPerStorageItem;480	type RentFraction = RentFraction;481	type SurchargeReward = SurchargeReward;482	type MaxDepth = MaxDepth;483	type MaxValueSize = MaxValueSize;484	type WeightPrice = pallet_transaction_payment::Module<Self>;485	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;486	type ChainExtension = NFTExtension;487	type DeletionQueueDepth = DeletionQueueDepth;488	type DeletionWeightLimit = DeletionWeightLimit;489	type MaxCodeSize = MaxCodeSize;490}491492parameter_types! {493	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer494}495496/// Linear implementor of `WeightToFeePolynomial`497pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);498499impl<T> WeightToFeePolynomial for LinearFee<T> where500	T: BaseArithmetic + From<u32> + Copy + Unsigned501{502	type Balance = T;503504	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {505		smallvec!(WeightToFeeCoefficient {506			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer507			coeff_frac: Perbill::zero(),508			negative: false,509			degree: 1,510		})511	}512}513514impl pallet_transaction_payment::Config for Runtime {515	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;516	type TransactionByteFee = TransactionByteFee;517	type WeightToFee = LinearFee<Balance>;518	type FeeMultiplierUpdate = ();519}520521parameter_types! {522	pub const ProposalBond: Permill = Permill::from_percent(5);523	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;524	pub const SpendPeriod: BlockNumber = 5 * MINUTES;525	pub const Burn: Permill = Permill::from_percent(0);526	pub const TipCountdown: BlockNumber = 1 * DAYS;527	pub const TipFindersFee: Percent = Percent::from_percent(20);528	pub const TipReportDepositBase: Balance = 1 * UNIQUE;529	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;530	pub const BountyDepositBase: Balance = 1 * UNIQUE;531	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;532	pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");533	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;534	pub const MaximumReasonLength: u32 = 16384;535	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);536	pub const BountyValueMinimum: Balance = 5 * UNIQUE;537}538539impl pallet_treasury::Config for Runtime {540	type ModuleId = TreasuryModuleId;541	type Currency = Balances;542	type ApproveOrigin = EnsureRoot<AccountId>;543	type RejectOrigin = EnsureRoot<AccountId>;544	type Event = Event;545	type OnSlash = ();546	type ProposalBond = ProposalBond;547	type ProposalBondMinimum = ProposalBondMinimum;548	type SpendPeriod = SpendPeriod;549	type Burn = Burn;550	type BurnDestination = ();551	type SpendFunds = ();552	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;553}554555impl pallet_sudo::Config for Runtime {556	type Event = Event;557	type Call = Call;558}559560parameter_types! {561	pub const MinVestedTransfer: Balance = 10 * UNIQUE;562}563564impl pallet_vesting::Config for Runtime {565	type Event = Event;566	type Currency = Balances;567	type BlockNumberToBalance = ConvertInto;568	type MinVestedTransfer = MinVestedTransfer;569	type WeightInfo = ();570}571572parameter_types! {573	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();574	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;575}576577/// Used for the module nft in `./nft.rs`578impl pallet_nft::Config for Runtime {579	type Event = Event;580	type WeightInfo = nft_weights::WeightInfo;581	type Currency = Balances;582	type CollectionCreationPrice = CollectionCreationPrice;583	type TreasuryAccountId = TreasuryAccountId;584}585586construct_runtime!(587	pub enum Runtime where588		Block = Block,589		NodeBlock = opaque::Block,590		UncheckedExtrinsic = UncheckedExtrinsic591	{592		System: system::{Module, Call, Config, Storage, Event<T>},593		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},594		Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},595		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},596		Aura: pallet_aura::{Module, Config<T> },597		EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},598		Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},599		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},600		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},601		TransactionPayment: pallet_transaction_payment::{Module, Storage},602		Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},603		Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},604		Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},605		Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},606	}607);608609pub struct TransactionConverter;610611impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {612	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {613		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())614	}615}616617impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {618	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {619		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());620		let encoded = extrinsic.encode();621		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")622	}623}624625/// The address format for describing accounts.626pub type Address = AccountId;627/// Block header type as expected by this runtime.628pub type Header = generic::Header<BlockNumber, BlakeTwo256>;629/// Block type as expected by this runtime.630pub type Block = generic::Block<Header, UncheckedExtrinsic>;631/// A Block signed with a Justification632pub type SignedBlock = generic::SignedBlock<Block>;633/// BlockId type as expected by this runtime.634pub type BlockId = generic::BlockId<Block>;635/// The SignedExtension to the basic transaction logic.636pub type SignedExtra = (637	system::CheckSpecVersion<Runtime>,638	system::CheckTxVersion<Runtime>,639	system::CheckGenesis<Runtime>,640	system::CheckEra<Runtime>,641	system::CheckNonce<Runtime>,642	system::CheckWeight<Runtime>,643	pallet_nft::ChargeTransactionPayment<Runtime>,644);645/// Unchecked extrinsic type as expected by this runtime.646pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;647/// Extrinsic type that has already been checked.648pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;649/// Executive: handles dispatch to the various modules.650pub type Executive =651	frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;652653impl_runtime_apis! {654655	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>656		for Runtime657	{658		fn call(659			origin: AccountId,660			dest: AccountId,661			value: Balance,662			gas_limit: u64,663			input_data: Vec<u8>,664		) -> pallet_contracts_primitives::ContractExecResult {665			Contracts::bare_call(origin, dest, value, gas_limit, input_data)666		}667668		fn get_storage(669			address: AccountId,670			key: [u8; 32],671		) -> pallet_contracts_primitives::GetStorageResult {672			Contracts::get_storage(address, key)673		}674675		fn rent_projection(676			address: AccountId,677		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {678			Contracts::rent_projection(address)679		}680	}681682	impl sp_api::Core<Block> for Runtime {683		fn version() -> RuntimeVersion {684			VERSION685		}686687		fn execute_block(block: Block) {688			Executive::execute_block(block)689		}690691		fn initialize_block(header: &<Block as BlockT>::Header) {692			Executive::initialize_block(header)693		}694	}695696	impl sp_api::Metadata<Block> for Runtime {697		fn metadata() -> OpaqueMetadata {698			Runtime::metadata().into()699		}700	}701702	impl sp_block_builder::BlockBuilder<Block> for Runtime {703		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {704			Executive::apply_extrinsic(extrinsic)705		}706707		fn finalize_block() -> <Block as BlockT>::Header {708			Executive::finalize_block()709		}710711		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {712			data.create_extrinsics()713		}714715		fn check_inherents(716			block: Block,717			data: sp_inherents::InherentData,718		) -> sp_inherents::CheckInherentsResult {719			data.check_extrinsics(&block)720		}721722		fn random_seed() -> <Block as BlockT>::Hash {723			RandomnessCollectiveFlip::random_seed().0724		}725	}726727	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {728		fn validate_transaction(729			source: TransactionSource,730			tx: <Block as BlockT>::Extrinsic,731		) -> TransactionValidity {732			Executive::validate_transaction(source, tx)733		}734	}735736	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {737		fn offchain_worker(header: &<Block as BlockT>::Header) {738			Executive::offchain_worker(header)739		}740	}741742	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {743		fn slot_duration() -> u64 {744			Aura::slot_duration()745		}746747		fn authorities() -> Vec<AuraId> {748			Aura::authorities()749		}750	}751752	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {753		fn chain_id() -> u64 {754			<Runtime as pallet_evm::Config>::ChainId::get()755		}756757		fn account_basic(address: H160) -> EVMAccount {758			EVM::account_basic(&address)759		}760761		fn gas_price() -> U256 {762			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()763		}764765		fn account_code_at(address: H160) -> Vec<u8> {766			EVM::account_codes(address)767		}768769		fn author() -> H160 {770			<pallet_ethereum::Module<Runtime>>::find_author()771		}772773		fn storage_at(address: H160, index: U256) -> H256 {774			let mut tmp = [0u8; 32];775			index.to_big_endian(&mut tmp);776			EVM::account_storages(address, H256::from_slice(&tmp[..]))777		}778779		fn call(780			from: H160,781			to: H160,782			data: Vec<u8>,783			value: U256,784			gas_limit: U256,785			gas_price: Option<U256>,786			nonce: Option<U256>,787			estimate: bool,788		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {789			let config = if estimate {790				let mut config = <Runtime as pallet_evm::Config>::config().clone();791				config.estimate = true;792				Some(config)793			} else {794				None795			};796797			<Runtime as pallet_evm::Config>::Runner::call(798				from,799				to,800				data,801				value,802				gas_limit.low_u64(),803				gas_price,804				nonce,805				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),806			).map_err(|err| err.into())807		}808809		fn create(810			from: H160,811			data: Vec<u8>,812			value: U256,813			gas_limit: U256,814			gas_price: Option<U256>,815			nonce: Option<U256>,816			estimate: bool,817		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {818			let config = if estimate {819				let mut config = <Runtime as pallet_evm::Config>::config().clone();820				config.estimate = true;821				Some(config)822			} else {823				None824			};825826			<Runtime as pallet_evm::Config>::Runner::create(827				from,828				data,829				value,830				gas_limit.low_u64(),831				gas_price,832				nonce,833				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),834			).map_err(|err| err.into())835		}836837		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {838			Ethereum::current_transaction_statuses()839		}840841		fn current_block() -> Option<pallet_ethereum::Block> {842			Ethereum::current_block()843		}844845		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {846			Ethereum::current_receipts()847		}848849		fn current_all() -> (850			Option<pallet_ethereum::Block>,851			Option<Vec<pallet_ethereum::Receipt>>,852			Option<Vec<TransactionStatus>>853		) {854			(855				Ethereum::current_block(),856				Ethereum::current_receipts(),857				Ethereum::current_transaction_statuses()858			)859		}860	}861862	impl sp_session::SessionKeys<Block> for Runtime {863		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {864			opaque::SessionKeys::generate(seed)865		}866867		fn decode_session_keys(868			encoded: Vec<u8>,869		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {870			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)871		}872	}873874	impl fg_primitives::GrandpaApi<Block> for Runtime {875		fn grandpa_authorities() -> GrandpaAuthorityList {876			Grandpa::grandpa_authorities()877		}878879		fn submit_report_equivocation_unsigned_extrinsic(880			_equivocation_proof: fg_primitives::EquivocationProof<881				<Block as BlockT>::Hash,882				NumberFor<Block>,883			>,884			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,885		) -> Option<()> {886			None887		}888889		fn generate_key_ownership_proof(890			_set_id: fg_primitives::SetId,891			_authority_id: GrandpaId,892		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {893			// NOTE: this is the only implementation possible since we've894			// defined our key owner proof type as a bottom type (i.e. a type895			// with no values).896			None897		}898	}899900	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {901		fn account_nonce(account: AccountId) -> Index {902			System::account_nonce(account)903		}904	}905906	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {907		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {908			TransactionPayment::query_info(uxt, len)909		}910		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {911			TransactionPayment::query_fee_details(uxt, len)912		}913	}914915	#[cfg(feature = "runtime-benchmarks")]916	impl frame_benchmarking::Benchmark<Block> for Runtime {917		fn dispatch_benchmark(918			config: frame_benchmarking::BenchmarkConfig919		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {920			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};921922			let whitelist: Vec<TrackedStorageKey> = vec![923				// Alice account924				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),925				// // Total Issuance926				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),927				// // Execution Phase928				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),929				// // Event Count930				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),931				// // System Events932				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),933			];934935			let mut batches = Vec::<BenchmarkBatch>::new();936			let params = (&config, &whitelist);937938			add_benchmark!(params, batches, pallet_nft, Nft);939940			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }941			Ok(batches)942		}943	}944}
after · runtime/src/lib.rs
1//2// This file is subject to the terms and conditions defined in3// file 'LICENSE', which is part of this source code package.4//56//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.78#![cfg_attr(not(feature = "std"), no_std)]9// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.10#![recursion_limit = "256"]1112// Make the WASM binary available.13#[cfg(feature = "std")]14include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1516use pallet_grandpa::fg_primitives;17use pallet_grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};18use sp_api::impl_runtime_apis;19use sp_consensus_aura::sr25519::AuthorityId as AuraId;20use sp_core::{ crypto::KeyTypeId, crypto::Public, OpaqueMetadata, H160, U256 };21use sp_runtime::{22	Permill, Perbill, Percent,23	ModuleId,24	create_runtime_str, generic, impl_opaque_keys,25	traits::{26		Convert, ConvertInto, BlakeTwo256, Block as BlockT, IdentifyAccount,27		IdentityLookup, NumberFor, Verify, AccountIdConversion,28	},29	transaction_validity::{TransactionSource, TransactionValidity},30	ApplyExtrinsicResult, MultiSignature,31};32#[cfg(feature = "std")]33use sp_version::NativeVersion;34use sp_version::RuntimeVersion;35pub use pallet_transaction_payment::{Multiplier, TargetedFeeAdjustment, CurrencyAdapter, FeeDetails, RuntimeDispatchInfo};36// A few exports that help ease life for downstream crates.37pub use pallet_balances::Call as BalancesCall;38pub use pallet_evm::{EnsureAddressTruncated, HashedAddressMapping, Runner};39pub use pallet_contracts::{Schedule as ContractsSchedule };40pub use frame_support::{41	construct_runtime,42	dispatch::DispatchResult,43	parameter_types,44	StorageValue,45	traits::{46		Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,47		LockIdentifier, FindAuthor,48	},49	weights::{50		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},51		DispatchClass, DispatchInfo, GetDispatchInfo, Pays, PostDispatchInfo, Weight,52		WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients53	},54	ConsensusEngineId,55};56use pallet_contracts::weights::WeightInfo;57// #[cfg(any(feature = "std", test))]58use frame_system::{59	self as system,60	EnsureRoot,61	limits::{BlockWeights, BlockLength},62};63use sp_std::{prelude::*, marker::PhantomData};64use sp_arithmetic::{traits::{BaseArithmetic, Unsigned}};65use smallvec::smallvec;66use codec::{Encode, Decode};67use pallet_evm::{Account as EVMAccount, FeeCalculator};68use fp_rpc::TransactionStatus;69use sp_core::H256;7071pub use pallet_timestamp::Call as TimestampCall;7273mod chain_extension;74use crate::chain_extension::{ NFTExtension, Imbalance };7576/// Struct that handles the conversion of Balance -> `u64`. This is used for77/// staking's election calculation.78pub struct CurrencyToVoteHandler;7980impl CurrencyToVoteHandler {81	fn factor() -> Balance {82		(Balances::total_issuance() / u64::max_value() as Balance).max(1)83	}84}8586impl Convert<Balance, u64> for CurrencyToVoteHandler {87	fn convert(x: Balance) -> u64 {88		(x / Self::factor()) as u6489	}90}9192impl Convert<u128, Balance> for CurrencyToVoteHandler {93	fn convert(x: u128) -> Balance {94		x * Self::factor()95	}96}9798/// Re-export a nft pallet99/// TODO: Check this re-export. Is this safe and good style?100extern crate pallet_nft;101pub use pallet_nft::*;102103/// An index to a block.104pub type BlockNumber = u32;105106/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.107pub type Signature = MultiSignature;108109/// Some way of identifying an account on the chain. We intentionally make it equivalent110/// to the public key of our transaction signing scheme.111pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;112113/// The type for looking up accounts. We don't expect more than 4 billion of them, but you114/// never know...115pub type AccountIndex = u32;116117/// Balance of an account.118pub type Balance = u128;119120/// Index of a transaction in the chain.121pub type Index = u32;122123/// A hash of some data used by the chain.124pub type Hash = sp_core::H256;125126/// Digest item type.127pub type DigestItem = generic::DigestItem<Hash>;128129mod nft_weights;130131/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know132/// the specifics of the runtime. They can then be made to be agnostic over specific formats133/// of data like extrinsics, allowing for them to continue syncing the network through upgrades134/// to even the core data structures.135pub mod opaque {136	use super::*;137138	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;139140	/// Opaque block header type.141	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;142	/// Opaque block type.143	pub type Block = generic::Block<Header, UncheckedExtrinsic>;144	/// Opaque block identifier type.145	pub type BlockId = generic::BlockId<Block>;146147	impl_opaque_keys! {148		pub struct SessionKeys {149			pub aura: Aura,150			pub grandpa: Grandpa,151		}152	}153}154155/// This runtime version.156pub const VERSION: RuntimeVersion = RuntimeVersion {157	spec_name: create_runtime_str!("nft"),158	impl_name: create_runtime_str!("nft"),159	authoring_version: 1,160	spec_version: 3,161	impl_version: 1,162	apis: RUNTIME_API_VERSIONS,163	transaction_version: 1,164};165166pub const MILLISECS_PER_BLOCK: u64 = 6000;167168pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;169170// These time units are defined in number of blocks.171pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);172pub const HOURS: BlockNumber = MINUTES * 60;173pub const DAYS: BlockNumber = HOURS * 24;174175/// The version information used to identify this runtime when compiled natively.176#[cfg(feature = "std")]177pub fn native_version() -> NativeVersion {178	NativeVersion {179		runtime_version: VERSION,180		can_author_with: Default::default(),181	}182}183184/// Provides a membership set with only the configured aura users185pub struct ValiudatorsOnly<Runtime: pallet_aura::Config>(PhantomData<Runtime>);186impl frame_support::traits::Contains<AccountId> for ValiudatorsOnly<Runtime> {187	fn contains(t: &AccountId) -> bool {188		let arr: [u8; 32] = *t.as_ref();189		let raw_key: Vec<u8> = Vec::from(arr);190191		match pallet_aura::Module::<Runtime>::authorities().iter().find(|auth| auth.to_raw_vec() == raw_key) {192			Some(_) => true,193			None => false,194		}195	}196	fn sorted_members() -> Vec<AccountId> {197		let mut members: Vec<AccountId> = Vec::new();198		for auth in pallet_aura::Module::<Runtime>::authorities() {199			let mut arr: [u8; 32] = Default::default();200			let bor_arr = auth.clone().to_raw_vec();201			let slice = bor_arr.as_slice();202			arr.copy_from_slice(slice);203			members.push(AccountId::from(arr));204		}205		members206	}207	fn count() -> usize {208		pallet_aura::Module::<Runtime>::authorities().len()209	}210}211212impl frame_support::traits::ContainsLengthBound for ValiudatorsOnly<Runtime> {213	fn min_len() -> usize {214		1215	}216	fn max_len() -> usize {217		100218	}219}220221type NegativeImbalance = <Balances as Currency<AccountId>>::NegativeImbalance;222223pub struct DealWithFees;224impl OnUnbalanced<NegativeImbalance> for DealWithFees {225	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {226		if let Some(fees) = fees_then_tips.next() {227			// for fees, 100% to treasury228			let mut split = fees.ration(100, 0);229			if let Some(tips) = fees_then_tips.next() {230				// for tips, if any, 100% to treasury231				tips.ration_merge_into(100, 0, &mut split);232			}233			Treasury::on_unbalanced(split.0);234			// Author::on_unbalanced(split.1);235		}236	}237}238239// impl OnUnbalanced<NegativeImbalance> for DealWithFees {240// 	fn on_unbalanceds<B>(mut fees_then_tips: impl Iterator<Item=NegativeImbalance>) {241// 		if let Some(fees) = fees_then_tips.next() {242// 			// for fees, 100% to treasury243// 			let mut split = fees.ration(100, 0);244// 			if let Some(tips) = fees_then_tips.next() {245// 				// for tips, if any, 100% to treasury246// 				tips.ration_merge_into(100, 0, &mut split);247// 			}248// 			Treasury::on_unbalanced(split.0);249// 			// Author::on_unbalanced(split.1);250// 		}251// 	}252// }253254/// We assume that ~10% of the block weight is consumed by `on_initalize` handlers.255/// This is used to limit the maximal weight of a single extrinsic.256const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(10);257/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used258/// by  Operational  extrinsics.259const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);260/// We allow for 2 seconds of compute with a 6 second average block time.261const MAXIMUM_BLOCK_WEIGHT: Weight = 2 * WEIGHT_PER_SECOND;262263parameter_types! {264	pub const BlockHashCount: BlockNumber = 2400;265	pub RuntimeBlockLength: BlockLength =266		BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);267	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);268	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;269	pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()270		.base_block(BlockExecutionWeight::get())271		.for_class(DispatchClass::all(), |weights| {272			weights.base_extrinsic = ExtrinsicBaseWeight::get();273		})274		.for_class(DispatchClass::Normal, |weights| {275			weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);276		})277		.for_class(DispatchClass::Operational, |weights| {278			weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);279			// Operational transactions have some extra reserved space, so that they280			// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.281			weights.reserved = Some(282				MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT283			);284		})285		.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)286		.build_or_panic();287	pub const Version: RuntimeVersion = VERSION;288	pub const SS58Prefix: u8 = 42;289}290291impl system::Config for Runtime {292	/// The basic call filter to use in dispatchable.293	type BaseCallFilter = ();294	/// The identifier used to distinguish between accounts.295	type AccountId = AccountId;296	/// The aggregated dispatch type that is available for extrinsics.297	type Call = Call;298	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.299	type Lookup = IdentityLookup<AccountId>;300	/// The index type for storing how many extrinsics an account has signed.301	type Index = Index;302	/// The index type for blocks.303	type BlockNumber = BlockNumber;304	/// The type for hashing blocks and tries.305	type Hash = Hash;306	/// The hashing algorithm used.307	type Hashing = BlakeTwo256;308	/// The header type.309	type Header = generic::Header<BlockNumber, BlakeTwo256>;310	/// The ubiquitous event type.311	type Event = Event;312	/// The ubiquitous origin type.313	type Origin = Origin;314	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).315	type BlockHashCount = BlockHashCount;316	/// The weight of database operations that the runtime can invoke.317	type DbWeight = RocksDbWeight;318	/// The weight of the overhead invoked on the block import process, independent of the319	/// extrinsics included in that block.320	type BlockWeights = RuntimeBlockWeights;321	/// Version of the runtime.322	type Version = Version;323 	/// This type is being generated by `construct_runtime!`.324	type PalletInfo = PalletInfo;325	/// What to do if a new account is created.326	type OnNewAccount = ();327	/// What to do if an account is fully reaped from the system.328	type OnKilledAccount = ();329	/// The data to be stored in an account.330	type AccountData = pallet_balances::AccountData<Balance>;331	/// Weight information for the extrinsics of this pallet.332	type SystemWeightInfo = system::weights::SubstrateWeight<Runtime>;333334	type BlockLength = RuntimeBlockLength;335	type SS58Prefix = SS58Prefix;336}337338impl pallet_aura::Config for Runtime {339	type AuthorityId = AuraId;340}341342parameter_types! {343	pub const ChainId: u64 = 8888;344}345346impl pallet_evm::Config for Runtime {347	type FeeCalculator = ();348	type GasWeightMapping = ();349	type CallOrigin = EnsureAddressTruncated;350	type WithdrawOrigin = EnsureAddressTruncated;351	type AddressMapping = HashedAddressMapping<BlakeTwo256>;352	type Currency = Balances;353	type Event = Event;354	type Precompiles = ();355	type ChainId = ChainId;356	type Runner = pallet_evm::runner::stack::Runner<Self>;357	type OnChargeTransaction = ();358}359360pub struct EthereumFindAuthor<F>(PhantomData<F>);361impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>362{363	fn find_author<'a, I>(digests: I) -> Option<H160> where364		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>365	{366		if let Some(author_index) = F::find_author(digests) {367			let authority_id = Aura::authorities()[author_index as usize].clone();368			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));369		}370		None371	}372}373374parameter_types! {375	pub BlockGasLimit: U256 = U256::from(u32::max_value());376}377378impl pallet_ethereum::Config for Runtime {379	type Event = Event;380	type FindAuthor = EthereumFindAuthor<Aura>;381	type StateRoot = pallet_ethereum::IntermediateStateRoot;382	type BlockGasLimit = BlockGasLimit;383}384385impl pallet_grandpa::Config for Runtime {386	type Event = Event;387	type Call = Call;388389	type KeyOwnerProofSystem = ();390391	type KeyOwnerProof =392		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;393394	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(395		KeyTypeId,396		GrandpaId,397	)>>::IdentificationTuple;398399	type HandleEquivocation = ();400401	type WeightInfo = ();402}403404parameter_types! {405	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;406}407408impl pallet_timestamp::Config for Runtime {409	/// A timestamp: milliseconds since the unix epoch.410	type Moment = u64;411	type OnTimestampSet = Aura;412	type MinimumPeriod = MinimumPeriod;413	type WeightInfo = ();414}415416parameter_types! {417	// pub const ExistentialDeposit: u128 = 500;418	pub const ExistentialDeposit: u128 = 0;419	pub const MaxLocks: u32 = 50;420}421422impl pallet_balances::Config for Runtime {423	type MaxLocks = MaxLocks;424	/// The type for recording an account's balance.425	type Balance = Balance;426	/// The ubiquitous event type.427	type Event = Event;428	type DustRemoval = Treasury;429	type ExistentialDeposit = ExistentialDeposit;430	type AccountStore = System;431	type WeightInfo = ();432}433434pub const MICROUNIQUE: Balance = 1_000_000_000;435pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;436pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;437pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;438439pub const fn deposit(items: u32, bytes: u32) -> Balance {440	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE441}442443parameter_types! {444	pub const TombstoneDeposit: Balance = deposit(445		0,446		sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32447	);448	pub const DepositPerContract: Balance = TombstoneDeposit::get();449	pub const DepositPerStorageByte: Balance = deposit(0, 1);450	pub const DepositPerStorageItem: Balance = deposit(1, 0);451	pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);452	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;453	pub const SignedClaimHandicap: u32 = 2;454	pub const MaxDepth: u32 = 32;455	pub const MaxValueSize: u32 = 16 * 1024;456	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb457	// The lazy deletion runs inside on_initialize.458	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *459		RuntimeBlockWeights::get().max_block;460	// The weight needed for decoding the queue should be less or equal than a fifth461	// of the overall weight dedicated to the lazy deletion.462	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (463			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -464			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)465		)) / 5) as u32;466}467468469impl pallet_contracts::Config for Runtime {470	type Time = Timestamp;471	type Randomness = RandomnessCollectiveFlip;472	type Currency = Balances;473	type Event = Event;474	type RentPayment = ();475	type SignedClaimHandicap = SignedClaimHandicap;476	type TombstoneDeposit = TombstoneDeposit;477	type DepositPerContract = DepositPerContract;478	type DepositPerStorageByte = DepositPerStorageByte;479	type DepositPerStorageItem = DepositPerStorageItem;480	type RentFraction = RentFraction;481	type SurchargeReward = SurchargeReward;482	type MaxDepth = MaxDepth;483	type MaxValueSize = MaxValueSize;484	type WeightPrice = pallet_transaction_payment::Module<Self>;485	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;486	type ChainExtension = NFTExtension;487	type DeletionQueueDepth = DeletionQueueDepth;488	type DeletionWeightLimit = DeletionWeightLimit;489	type MaxCodeSize = MaxCodeSize;490}491492parameter_types! {493	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer494}495496/// Linear implementor of `WeightToFeePolynomial`497pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);498499impl<T> WeightToFeePolynomial for LinearFee<T> where500	T: BaseArithmetic + From<u32> + Copy + Unsigned501{502	type Balance = T;503504	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {505		smallvec!(WeightToFeeCoefficient {506			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer507			coeff_frac: Perbill::zero(),508			negative: false,509			degree: 1,510		})511	}512}513514impl pallet_transaction_payment::Config for Runtime {515	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;516	type TransactionByteFee = TransactionByteFee;517	type WeightToFee = LinearFee<Balance>;518	type FeeMultiplierUpdate = ();519}520521parameter_types! {522	pub const ProposalBond: Permill = Permill::from_percent(5);523	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;524	pub const SpendPeriod: BlockNumber = 5 * MINUTES;525	pub const Burn: Permill = Permill::from_percent(0);526	pub const TipCountdown: BlockNumber = 1 * DAYS;527	pub const TipFindersFee: Percent = Percent::from_percent(20);528	pub const TipReportDepositBase: Balance = 1 * UNIQUE;529	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;530	pub const BountyDepositBase: Balance = 1 * UNIQUE;531	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;532	pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");533	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;534	pub const MaximumReasonLength: u32 = 16384;535	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);536	pub const BountyValueMinimum: Balance = 5 * UNIQUE;537}538539impl pallet_treasury::Config for Runtime {540	type ModuleId = TreasuryModuleId;541	type Currency = Balances;542	type ApproveOrigin = EnsureRoot<AccountId>;543	type RejectOrigin = EnsureRoot<AccountId>;544	type Event = Event;545	type OnSlash = ();546	type ProposalBond = ProposalBond;547	type ProposalBondMinimum = ProposalBondMinimum;548	type SpendPeriod = SpendPeriod;549	type Burn = Burn;550	type BurnDestination = ();551	type SpendFunds = ();552	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;553}554555impl pallet_sudo::Config for Runtime {556	type Event = Event;557	type Call = Call;558}559560parameter_types! {561	pub const MinVestedTransfer: Balance = 10 * UNIQUE;562}563564impl pallet_vesting::Config for Runtime {565	type Event = Event;566	type Currency = Balances;567	type BlockNumberToBalance = ConvertInto;568	type MinVestedTransfer = MinVestedTransfer;569	type WeightInfo = ();570}571572parameter_types! {573	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();574	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;575}576577/// Used for the module nft in `./nft.rs`578impl pallet_nft::Config for Runtime {579	type Event = Event;580	type WeightInfo = nft_weights::WeightInfo;581582	type EvmWithdrawOrigin = EnsureAddressTruncated;583	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;584	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;585	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;586587	type Currency = Balances;588	type CollectionCreationPrice = CollectionCreationPrice;589	type TreasuryAccountId = TreasuryAccountId;590}591592construct_runtime!(593	pub enum Runtime where594		Block = Block,595		NodeBlock = opaque::Block,596		UncheckedExtrinsic = UncheckedExtrinsic597	{598		System: system::{Module, Call, Config, Storage, Event<T>},599		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},600		Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},601		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},602		Aura: pallet_aura::{Module, Config<T> },603		EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},604		Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},605		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},606		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},607		TransactionPayment: pallet_transaction_payment::{Module, Storage},608		Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},609		Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},610		Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},611		Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},612	}613);614615pub struct TransactionConverter;616617impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {618	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {619		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())620	}621}622623impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {624	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {625		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());626		let encoded = extrinsic.encode();627		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")628	}629}630631/// The address format for describing accounts.632pub type Address = AccountId;633/// Block header type as expected by this runtime.634pub type Header = generic::Header<BlockNumber, BlakeTwo256>;635/// Block type as expected by this runtime.636pub type Block = generic::Block<Header, UncheckedExtrinsic>;637/// A Block signed with a Justification638pub type SignedBlock = generic::SignedBlock<Block>;639/// BlockId type as expected by this runtime.640pub type BlockId = generic::BlockId<Block>;641/// The SignedExtension to the basic transaction logic.642pub type SignedExtra = (643	system::CheckSpecVersion<Runtime>,644	system::CheckTxVersion<Runtime>,645	system::CheckGenesis<Runtime>,646	system::CheckEra<Runtime>,647	system::CheckNonce<Runtime>,648	system::CheckWeight<Runtime>,649	pallet_nft::ChargeTransactionPayment<Runtime>,650);651/// Unchecked extrinsic type as expected by this runtime.652pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;653/// Extrinsic type that has already been checked.654pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;655/// Executive: handles dispatch to the various modules.656pub type Executive =657	frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;658659impl_runtime_apis! {660661	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>662		for Runtime663	{664		fn call(665			origin: AccountId,666			dest: AccountId,667			value: Balance,668			gas_limit: u64,669			input_data: Vec<u8>,670		) -> pallet_contracts_primitives::ContractExecResult {671			Contracts::bare_call(origin, dest, value, gas_limit, input_data)672		}673674		fn get_storage(675			address: AccountId,676			key: [u8; 32],677		) -> pallet_contracts_primitives::GetStorageResult {678			Contracts::get_storage(address, key)679		}680681		fn rent_projection(682			address: AccountId,683		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {684			Contracts::rent_projection(address)685		}686	}687688	impl sp_api::Core<Block> for Runtime {689		fn version() -> RuntimeVersion {690			VERSION691		}692693		fn execute_block(block: Block) {694			Executive::execute_block(block)695		}696697		fn initialize_block(header: &<Block as BlockT>::Header) {698			Executive::initialize_block(header)699		}700	}701702	impl sp_api::Metadata<Block> for Runtime {703		fn metadata() -> OpaqueMetadata {704			Runtime::metadata().into()705		}706	}707708	impl sp_block_builder::BlockBuilder<Block> for Runtime {709		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {710			Executive::apply_extrinsic(extrinsic)711		}712713		fn finalize_block() -> <Block as BlockT>::Header {714			Executive::finalize_block()715		}716717		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {718			data.create_extrinsics()719		}720721		fn check_inherents(722			block: Block,723			data: sp_inherents::InherentData,724		) -> sp_inherents::CheckInherentsResult {725			data.check_extrinsics(&block)726		}727728		fn random_seed() -> <Block as BlockT>::Hash {729			RandomnessCollectiveFlip::random_seed().0730		}731	}732733	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {734		fn validate_transaction(735			source: TransactionSource,736			tx: <Block as BlockT>::Extrinsic,737		) -> TransactionValidity {738			Executive::validate_transaction(source, tx)739		}740	}741742	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {743		fn offchain_worker(header: &<Block as BlockT>::Header) {744			Executive::offchain_worker(header)745		}746	}747748	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {749		fn slot_duration() -> u64 {750			Aura::slot_duration()751		}752753		fn authorities() -> Vec<AuraId> {754			Aura::authorities()755		}756	}757758	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {759		fn chain_id() -> u64 {760			<Runtime as pallet_evm::Config>::ChainId::get()761		}762763		fn account_basic(address: H160) -> EVMAccount {764			EVM::account_basic(&address)765		}766767		fn gas_price() -> U256 {768			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()769		}770771		fn account_code_at(address: H160) -> Vec<u8> {772			EVM::account_codes(address)773		}774775		fn author() -> H160 {776			<pallet_ethereum::Module<Runtime>>::find_author()777		}778779		fn storage_at(address: H160, index: U256) -> H256 {780			let mut tmp = [0u8; 32];781			index.to_big_endian(&mut tmp);782			EVM::account_storages(address, H256::from_slice(&tmp[..]))783		}784785		fn call(786			from: H160,787			to: H160,788			data: Vec<u8>,789			value: U256,790			gas_limit: U256,791			gas_price: Option<U256>,792			nonce: Option<U256>,793			estimate: bool,794		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {795			let config = if estimate {796				let mut config = <Runtime as pallet_evm::Config>::config().clone();797				config.estimate = true;798				Some(config)799			} else {800				None801			};802803			<Runtime as pallet_evm::Config>::Runner::call(804				from,805				to,806				data,807				value,808				gas_limit.low_u64(),809				gas_price,810				nonce,811				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),812			).map_err(|err| err.into())813		}814815		fn create(816			from: H160,817			data: Vec<u8>,818			value: U256,819			gas_limit: U256,820			gas_price: Option<U256>,821			nonce: Option<U256>,822			estimate: bool,823		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {824			let config = if estimate {825				let mut config = <Runtime as pallet_evm::Config>::config().clone();826				config.estimate = true;827				Some(config)828			} else {829				None830			};831832			<Runtime as pallet_evm::Config>::Runner::create(833				from,834				data,835				value,836				gas_limit.low_u64(),837				gas_price,838				nonce,839				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),840			).map_err(|err| err.into())841		}842843		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {844			Ethereum::current_transaction_statuses()845		}846847		fn current_block() -> Option<pallet_ethereum::Block> {848			Ethereum::current_block()849		}850851		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {852			Ethereum::current_receipts()853		}854855		fn current_all() -> (856			Option<pallet_ethereum::Block>,857			Option<Vec<pallet_ethereum::Receipt>>,858			Option<Vec<TransactionStatus>>859		) {860			(861				Ethereum::current_block(),862				Ethereum::current_receipts(),863				Ethereum::current_transaction_statuses()864			)865		}866	}867868	impl sp_session::SessionKeys<Block> for Runtime {869		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {870			opaque::SessionKeys::generate(seed)871		}872873		fn decode_session_keys(874			encoded: Vec<u8>,875		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {876			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)877		}878	}879880	impl fg_primitives::GrandpaApi<Block> for Runtime {881		fn grandpa_authorities() -> GrandpaAuthorityList {882			Grandpa::grandpa_authorities()883		}884885		fn submit_report_equivocation_unsigned_extrinsic(886			_equivocation_proof: fg_primitives::EquivocationProof<887				<Block as BlockT>::Hash,888				NumberFor<Block>,889			>,890			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,891		) -> Option<()> {892			None893		}894895		fn generate_key_ownership_proof(896			_set_id: fg_primitives::SetId,897			_authority_id: GrandpaId,898		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {899			// NOTE: this is the only implementation possible since we've900			// defined our key owner proof type as a bottom type (i.e. a type901			// with no values).902			None903		}904	}905906	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {907		fn account_nonce(account: AccountId) -> Index {908			System::account_nonce(account)909		}910	}911912	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {913		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {914			TransactionPayment::query_info(uxt, len)915		}916		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {917			TransactionPayment::query_fee_details(uxt, len)918		}919	}920921	#[cfg(feature = "runtime-benchmarks")]922	impl frame_benchmarking::Benchmark<Block> for Runtime {923		fn dispatch_benchmark(924			config: frame_benchmarking::BenchmarkConfig925		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {926			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};927928			let whitelist: Vec<TrackedStorageKey> = vec![929				// Alice account930				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),931				// // Total Issuance932				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),933				// // Execution Phase934				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),935				// // Event Count936				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),937				// // System Events938				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),939			];940941			let mut batches = Vec::<BenchmarkBatch>::new();942			let params = (&config, &whitelist);943944			add_benchmark!(params, batches, pallet_nft, Nft);945946			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }947			Ok(batches)948		}949	}950}
modifiedruntime_types.jsondiffbeforeafterboth
--- a/runtime_types.json
+++ b/runtime_types.json
@@ -1,4 +1,10 @@
 {
+    "CrossAccountId": {
+      "_enum": {
+        "substrate": "AccountId",
+        "ethereum": "H160"
+      }
+    },
     "AccessMode": {
       "_enum": [
         "Normal",
@@ -15,31 +21,31 @@
       }
     },
     "Ownership": {
-      "Owner": "AccountId",
+      "Owner": "CrossAccountId",
       "Fraction": "u128"
     },
     "FungibleItemType": {
       "Value": "u128"
     },
     "NftItemType": {
-      "Owner": "AccountId",
+      "Owner": "CrossAccountId",
       "ConstData": "Vec<u8>",
       "VariableData": "Vec<u8>"
     },
     "ReFungibleItemType": {
-      "Owner": "Vec<Ownership<AccountId>>",
+      "Owner": "Vec<Ownership<CrossAccountId>>",
       "ConstData": "Vec<u8>",
       "VariableData": "Vec<u8>"
     },
     "SponsorshipState": {
       "_enum": {
-        "Disabled": null,
-        "Unconfirmed": "AccountId",
-        "Confirmed": "AccountId"
+        "disabled": null,
+        "unconfirmed": "CrossAccountId",
+        "confirmed": "CrossAccountId"
       }
     },
     "Collection": {
-      "Owner": "AccountId",
+      "Owner": "CrossAccountId",
       "Mode": "CollectionMode",
       "Access": "AccessMode",
       "DecimalPoints": "DecimalPoints",