git.delta.rocks / unique-network / refs/commits / 683924f8b65f

difftreelog

feat log recording

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

2 files changed

modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -43,7 +43,7 @@
 };
 use sp_runtime::traits::StaticLookup;
 use pallet_contracts::chain_extension::UncheckedFrom;
-use pallet_evm::AddressMapping;
+use pallet_ethereum::EthereumTransactionSender;
 use pallet_transaction_payment::OnChargeTransaction;
 
 #[cfg(test)]
@@ -185,7 +185,24 @@
 pub struct CollectionHandle<T: Config> {
     pub id: CollectionId,
     collection: Collection<T>,
+    logs: eth::log::LogRecorder,
 }
+impl<T: Config> CollectionHandle<T> {
+	pub fn get(id: CollectionId) -> Option<Self> {
+		<CollectionById<T>>::get(id)
+			.map(|collection| Self {
+				id,
+				collection,
+                logs: eth::log::LogRecorder::default(),
+			})
+	}
+    pub fn log(&self, topics: Vec<H256>, data: eth::abi::AbiWriter) {
+        self.logs.log(topics, data)
+    }
+    pub fn into_inner(self) -> Collection<T> {
+        self.collection.clone()
+    }
+}
 
 impl<T: Config> Deref for CollectionHandle<T> {
     type Target = Collection<T>;
@@ -471,6 +488,9 @@
     type Currency: Currency<Self::AccountId>;
     type CollectionCreationPrice: Get<<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance>;
     type TreasuryAccountId: Get<Self::AccountId>;
+
+    type EthereumChainId: Get<u64>;
+    type EthereumTransactionSender: pallet_ethereum::EthereumTransactionSender;
 }
 
 #[cfg(feature = "runtime-benchmarks")]
@@ -1125,6 +1145,7 @@
             Self::validate_create_item_args(&target_collection, &data)?;
             Self::create_item_no_validation(&target_collection, owner, data)?;
 
+            Self::submit_logs(target_collection)?;
             Ok(())
         }
 
@@ -1158,6 +1179,7 @@
 
             Self::create_multiple_items_internal(sender, &collection, owner, items_data)?;
 
+            Self::submit_logs(collection)?;
             Ok(())
         }
 
@@ -1183,6 +1205,7 @@
 
             Self::burn_item_internal(&sender, &target_collection, item_id, value)?;
 
+            Self::submit_logs(target_collection)?;
             Ok(())
         }
 
@@ -1217,6 +1240,7 @@
 
             Self::transfer_internal(sender, recipient, &collection, item_id, value)?;
 
+            Self::submit_logs(collection)?;
             Ok(())
         }
 
@@ -1244,6 +1268,7 @@
 
             Self::approve_internal(sender, spender, &collection, item_id, amount)?;
 
+            Self::submit_logs(collection)?;
             Ok(())
         }
         
@@ -1275,6 +1300,7 @@
 
             Self::transfer_from_internal(sender, from, recipient, &collection, item_id, value)?;
 
+            Self::submit_logs(collection)?;
             Ok(())
         }
 
@@ -1736,7 +1762,30 @@
 		}
 		<Allowances<T>>::insert(collection.id, (item_id, sender.as_sub(), spender.as_sub()), allowance);
 
+		if matches!(collection.mode, CollectionMode::NFT) {
+			// TODO: NFT: only one owner may exist for token in ERC721
+			collection.log(
+				Vec::from([
+					eth::APPROVAL_NFT_TOPIC,
+					eth::address_to_topic(sender.as_eth()),
+					eth::address_to_topic(spender.as_eth()),
+				]),
+				abi_encode!(uint256(item_id.into())),
+			);
+		}
 
+		if matches!(collection.mode, CollectionMode::Fungible(_)) {
+			// TODO: NFT: only one owner may exist for token in ERC20
+			collection.log(
+				Vec::from([
+					eth::APPROVAL_FUNGIBLE_TOPIC,
+					eth::address_to_topic(sender.as_eth()),
+					eth::address_to_topic(spender.as_eth()),
+				]),
+				abi_encode!(uint256(allowance.into())),
+			);
+		}
+
 		Self::deposit_event(RawEvent::Approved(collection.id, item_id, sender, spender, allowance));
 		Ok(())
 	}
@@ -1791,6 +1840,17 @@
 			_ => ()
 		};
 
+		if matches!(collection.mode, CollectionMode::Fungible(_)) {
+			collection.log(
+				Vec::from([
+					eth::APPROVAL_FUNGIBLE_TOPIC,
+					eth::address_to_topic(from.as_eth()),
+					eth::address_to_topic(sender.as_eth()),
+				]),
+				abi_encode!(uint256(allowance.into())),
+			);
+		}
+
 		Ok(())
 	}
 
@@ -2017,6 +2077,14 @@
             .ok_or(Error::<T>::NumOverflow)?;
         <Balance<T>>::insert(collection_id, item_owner.as_sub(), new_balance);
 
+        collection.log(
+            Vec::from([
+                eth::TRANSFER_NFT_TOPIC,
+                eth::address_to_topic(&H160::default()),
+                eth::address_to_topic(item_owner.as_eth()),
+            ]),
+            abi_encode!(uint256(current_index.into())),
+        );
         Self::deposit_event(RawEvent::ItemCreated(collection_id, current_index, item_owner));
         Ok(())
     }
@@ -2103,22 +2171,32 @@
             <FungibleItemList<T>>::remove(collection_id, owner.as_sub());
         }
 
+        collection.log(
+            Vec::from([
+                eth::TRANSFER_FUNGIBLE_TOPIC,
+                eth::address_to_topic(owner.as_eth()),
+                eth::address_to_topic(&H160::default()),
+            ]),
+            abi_encode!(uint256(value.into())),
+        );
         Ok(())
     }
 
     pub fn get_collection(collection_id: CollectionId) -> Result<CollectionHandle<T>, sp_runtime::DispatchError> {
-        Ok(<CollectionById<T>>::get(collection_id)
-            .map(|collection| CollectionHandle {
-                id: collection_id,
-                collection
-            })
+        Ok(<CollectionHandle<T>>::get(collection_id)
             .ok_or(Error::<T>::CollectionNotFound)?)
     }
 
     fn save_collection(collection: CollectionHandle<T>) {
-        <CollectionById<T>>::insert(collection.id, collection.collection);
+        <CollectionById<T>>::insert(collection.id, collection.into_inner());
     }
 
+    fn submit_logs(collection: CollectionHandle<T>) -> DispatchResult {
+        T::EthereumTransactionSender::submit_logs_transaction(
+            eth::generate_transaction(collection.id, T::EthereumChainId::get()),
+            collection.logs.retrieve_logs_for_contract(eth::collection_id_to_address(collection.id)),
+        )
+    }
 
     fn check_owner_permissions(target_collection: &CollectionHandle<T>, subject: &T::CrossAccountId) -> DispatchResult {
         ensure!(
@@ -2224,6 +2302,14 @@
             <FungibleItemList<T>>::insert(collection_id, owner.as_sub(), balance);
         }
 
+        collection.log(
+            Vec::from([
+                eth::TRANSFER_FUNGIBLE_TOPIC,
+                eth::address_to_topic(owner.as_eth()),
+                eth::address_to_topic(recipient.as_eth()),
+            ]),
+            abi_encode!(uint256(value.into())),
+        );
         Self::deposit_event(RawEvent::Transfer(collection.id, 1, owner.clone(), recipient.clone(), value));
 
         Ok(())
@@ -2348,6 +2434,14 @@
         // update index collection
         Self::move_token_index(collection_id, item_id, &old_owner, &new_owner)?;
 
+        collection.log(
+            Vec::from([
+                eth::TRANSFER_NFT_TOPIC,
+                eth::address_to_topic(sender.as_eth()),
+                eth::address_to_topic(new_owner.as_eth()),
+            ]),
+            abi_encode!(uint256(item_id.into())),
+        );
         Self::deposit_event(RawEvent::Transfer(collection.id, item_id, sender, new_owner, 1));
 
         Ok(())
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, OnMethodCall};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 BlockGasLimit = BlockGasLimit;348	type FeeCalculator = ();349	type GasWeightMapping = ();350	type CallOrigin = EnsureAddressTruncated;351	type WithdrawOrigin = EnsureAddressTruncated;352	type AddressMapping = HashedAddressMapping<Self::Hashing>;353	type Precompiles = ();354	type Currency = Balances;355	type Event = Event;356	type OnMethodCall = pallet_nft::NftErcSupport<Self>;357	type ChainId = ChainId;358	type Runner = pallet_evm::runner::stack::Runner<Self>;359	type OnChargeTransaction = ();360}361362pub struct EthereumFindAuthor<F>(PhantomData<F>);363impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>364{365	fn find_author<'a, I>(digests: I) -> Option<H160> where366		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>367	{368		if let Some(author_index) = F::find_author(digests) {369			let authority_id = Aura::authorities()[author_index as usize].clone();370			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));371		}372		None373	}374}375376parameter_types! {377	pub BlockGasLimit: U256 = U256::from(u32::max_value());378}379380impl pallet_ethereum::Config for Runtime {381	type Event = Event;382	type FindAuthor = EthereumFindAuthor<Aura>;383	type StateRoot = pallet_ethereum::IntermediateStateRoot;384}385386impl pallet_grandpa::Config for Runtime {387	type Event = Event;388	type Call = Call;389390	type KeyOwnerProofSystem = ();391392	type KeyOwnerProof =393		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;394395	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(396		KeyTypeId,397		GrandpaId,398	)>>::IdentificationTuple;399400	type HandleEquivocation = ();401402	type WeightInfo = ();403}404405parameter_types! {406	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;407}408409impl pallet_timestamp::Config for Runtime {410	/// A timestamp: milliseconds since the unix epoch.411	type Moment = u64;412	type OnTimestampSet = Aura;413	type MinimumPeriod = MinimumPeriod;414	type WeightInfo = ();415}416417parameter_types! {418	// pub const ExistentialDeposit: u128 = 500;419	pub const ExistentialDeposit: u128 = 0;420	pub const MaxLocks: u32 = 50;421}422423impl pallet_balances::Config for Runtime {424	type MaxLocks = MaxLocks;425	/// The type for recording an account's balance.426	type Balance = Balance;427	/// The ubiquitous event type.428	type Event = Event;429	type DustRemoval = Treasury;430	type ExistentialDeposit = ExistentialDeposit;431	type AccountStore = System;432	type WeightInfo = ();433}434435pub const MICROUNIQUE: Balance = 1_000_000_000;436pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;437pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;438pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;439440pub const fn deposit(items: u32, bytes: u32) -> Balance {441	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE442}443444parameter_types! {445	pub const TombstoneDeposit: Balance = deposit(446		0,447		sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32448	);449	pub const DepositPerContract: Balance = TombstoneDeposit::get();450	pub const DepositPerStorageByte: Balance = deposit(0, 1);451	pub const DepositPerStorageItem: Balance = deposit(1, 0);452	pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);453	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;454	pub const SignedClaimHandicap: u32 = 2;455	pub const MaxDepth: u32 = 32;456	pub const MaxValueSize: u32 = 16 * 1024;457	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb458	// The lazy deletion runs inside on_initialize.459	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *460		RuntimeBlockWeights::get().max_block;461	// The weight needed for decoding the queue should be less or equal than a fifth462	// of the overall weight dedicated to the lazy deletion.463	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (464			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -465			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)466		)) / 5) as u32;467}468469470impl pallet_contracts::Config for Runtime {471	type Time = Timestamp;472	type Randomness = RandomnessCollectiveFlip;473	type Currency = Balances;474	type Event = Event;475	type RentPayment = ();476	type SignedClaimHandicap = SignedClaimHandicap;477	type TombstoneDeposit = TombstoneDeposit;478	type DepositPerContract = DepositPerContract;479	type DepositPerStorageByte = DepositPerStorageByte;480	type DepositPerStorageItem = DepositPerStorageItem;481	type RentFraction = RentFraction;482	type SurchargeReward = SurchargeReward;483	type MaxDepth = MaxDepth;484	type MaxValueSize = MaxValueSize;485	type WeightPrice = pallet_transaction_payment::Module<Self>;486	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;487	type ChainExtension = NFTExtension;488	type DeletionQueueDepth = DeletionQueueDepth;489	type DeletionWeightLimit = DeletionWeightLimit;490	type MaxCodeSize = MaxCodeSize;491}492493parameter_types! {494	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer495}496497/// Linear implementor of `WeightToFeePolynomial`498pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);499500impl<T> WeightToFeePolynomial for LinearFee<T> where501	T: BaseArithmetic + From<u32> + Copy + Unsigned502{503	type Balance = T;504505	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {506		smallvec!(WeightToFeeCoefficient {507			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer508			coeff_frac: Perbill::zero(),509			negative: false,510			degree: 1,511		})512	}513}514515impl pallet_transaction_payment::Config for Runtime {516	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;517	type TransactionByteFee = TransactionByteFee;518	type WeightToFee = LinearFee<Balance>;519	type FeeMultiplierUpdate = ();520}521522parameter_types! {523	pub const ProposalBond: Permill = Permill::from_percent(5);524	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;525	pub const SpendPeriod: BlockNumber = 5 * MINUTES;526	pub const Burn: Permill = Permill::from_percent(0);527	pub const TipCountdown: BlockNumber = 1 * DAYS;528	pub const TipFindersFee: Percent = Percent::from_percent(20);529	pub const TipReportDepositBase: Balance = 1 * UNIQUE;530	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;531	pub const BountyDepositBase: Balance = 1 * UNIQUE;532	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;533	pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");534	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;535	pub const MaximumReasonLength: u32 = 16384;536	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);537	pub const BountyValueMinimum: Balance = 5 * UNIQUE;538}539540impl pallet_treasury::Config for Runtime {541	type ModuleId = TreasuryModuleId;542	type Currency = Balances;543	type ApproveOrigin = EnsureRoot<AccountId>;544	type RejectOrigin = EnsureRoot<AccountId>;545	type Event = Event;546	type OnSlash = ();547	type ProposalBond = ProposalBond;548	type ProposalBondMinimum = ProposalBondMinimum;549	type SpendPeriod = SpendPeriod;550	type Burn = Burn;551	type BurnDestination = ();552	type SpendFunds = ();553	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;554}555556impl pallet_sudo::Config for Runtime {557	type Event = Event;558	type Call = Call;559}560561parameter_types! {562	pub const MinVestedTransfer: Balance = 10 * UNIQUE;563}564565impl pallet_vesting::Config for Runtime {566	type Event = Event;567	type Currency = Balances;568	type BlockNumberToBalance = ConvertInto;569	type MinVestedTransfer = MinVestedTransfer;570	type WeightInfo = ();571}572573parameter_types! {574	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();575	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;576}577578/// Used for the module nft in `./nft.rs`579impl pallet_nft::Config for Runtime {580	type Event = Event;581	type WeightInfo = nft_weights::WeightInfo;582583	type EvmWithdrawOrigin = EnsureAddressTruncated;584	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;585	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;586	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;587588	type Currency = Balances;589	type CollectionCreationPrice = CollectionCreationPrice;590	type TreasuryAccountId = TreasuryAccountId;591}592593construct_runtime!(594	pub enum Runtime where595		Block = Block,596		NodeBlock = opaque::Block,597		UncheckedExtrinsic = UncheckedExtrinsic598	{599		System: system::{Module, Call, Config, Storage, Event<T>},600		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},601		Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},602		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},603		Aura: pallet_aura::{Module, Config<T> },604		EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},605		Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},606		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},607		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},608		TransactionPayment: pallet_transaction_payment::{Module, Storage},609		Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},610		Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},611		Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},612		Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},613	}614);615616pub struct TransactionConverter;617618impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {619	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {620		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())621	}622}623624impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {625	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {626		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());627		let encoded = extrinsic.encode();628		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")629	}630}631632/// The address format for describing accounts.633pub type Address = AccountId;634/// Block header type as expected by this runtime.635pub type Header = generic::Header<BlockNumber, BlakeTwo256>;636/// Block type as expected by this runtime.637pub type Block = generic::Block<Header, UncheckedExtrinsic>;638/// A Block signed with a Justification639pub type SignedBlock = generic::SignedBlock<Block>;640/// BlockId type as expected by this runtime.641pub type BlockId = generic::BlockId<Block>;642/// The SignedExtension to the basic transaction logic.643pub type SignedExtra = (644	system::CheckSpecVersion<Runtime>,645	system::CheckTxVersion<Runtime>,646	system::CheckGenesis<Runtime>,647	system::CheckEra<Runtime>,648	system::CheckNonce<Runtime>,649	system::CheckWeight<Runtime>,650	pallet_nft::ChargeTransactionPayment<Runtime>,651);652/// Unchecked extrinsic type as expected by this runtime.653pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;654/// Extrinsic type that has already been checked.655pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;656/// Executive: handles dispatch to the various modules.657pub type Executive =658	frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;659660impl_runtime_apis! {661	impl pallet_nft::NftApi<Block>662		for Runtime663	{664		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {665			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)666		}667	}668669	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>670		for Runtime671	{672		fn call(673			origin: AccountId,674			dest: AccountId,675			value: Balance,676			gas_limit: u64,677			input_data: Vec<u8>,678		) -> pallet_contracts_primitives::ContractExecResult {679			Contracts::bare_call(origin, dest, value, gas_limit, input_data)680		}681682		fn get_storage(683			address: AccountId,684			key: [u8; 32],685		) -> pallet_contracts_primitives::GetStorageResult {686			Contracts::get_storage(address, key)687		}688689		fn rent_projection(690			address: AccountId,691		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {692			Contracts::rent_projection(address)693		}694	}695696	impl sp_api::Core<Block> for Runtime {697		fn version() -> RuntimeVersion {698			VERSION699		}700701		fn execute_block(block: Block) {702			Executive::execute_block(block)703		}704705		fn initialize_block(header: &<Block as BlockT>::Header) {706			Executive::initialize_block(header)707		}708	}709710	impl sp_api::Metadata<Block> for Runtime {711		fn metadata() -> OpaqueMetadata {712			Runtime::metadata().into()713		}714	}715716	impl sp_block_builder::BlockBuilder<Block> for Runtime {717		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {718			Executive::apply_extrinsic(extrinsic)719		}720721		fn finalize_block() -> <Block as BlockT>::Header {722			Executive::finalize_block()723		}724725		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {726			data.create_extrinsics()727		}728729		fn check_inherents(730			block: Block,731			data: sp_inherents::InherentData,732		) -> sp_inherents::CheckInherentsResult {733			data.check_extrinsics(&block)734		}735736		fn random_seed() -> <Block as BlockT>::Hash {737			RandomnessCollectiveFlip::random_seed().0738		}739	}740741	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {742		fn validate_transaction(743			source: TransactionSource,744			tx: <Block as BlockT>::Extrinsic,745		) -> TransactionValidity {746			Executive::validate_transaction(source, tx)747		}748	}749750	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {751		fn offchain_worker(header: &<Block as BlockT>::Header) {752			Executive::offchain_worker(header)753		}754	}755756	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {757		fn slot_duration() -> u64 {758			Aura::slot_duration()759		}760761		fn authorities() -> Vec<AuraId> {762			Aura::authorities()763		}764	}765766	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {767		fn chain_id() -> u64 {768			<Runtime as pallet_evm::Config>::ChainId::get()769		}770771		fn account_basic(address: H160) -> EVMAccount {772			EVM::account_basic(&address)773		}774775		fn gas_price() -> U256 {776			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()777		}778779		fn account_code_at(address: H160) -> Vec<u8> {780			EVM::account_codes(address)781		}782783		fn author() -> H160 {784			<pallet_ethereum::Module<Runtime>>::find_author()785		}786787		fn storage_at(address: H160, index: U256) -> H256 {788			let mut tmp = [0u8; 32];789			index.to_big_endian(&mut tmp);790			EVM::account_storages(address, H256::from_slice(&tmp[..]))791		}792793		fn call(794			from: H160,795			to: H160,796			data: Vec<u8>,797			value: U256,798			gas_limit: U256,799			gas_price: Option<U256>,800			nonce: Option<U256>,801			estimate: bool,802		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {803			let config = if estimate {804				let mut config = <Runtime as pallet_evm::Config>::config().clone();805				config.estimate = true;806				Some(config)807			} else {808				None809			};810811			<Runtime as pallet_evm::Config>::Runner::call(812				from,813				to,814				data,815				value,816				gas_limit.low_u64(),817				gas_price,818				nonce,819				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),820			).map_err(|err| err.into())821		}822823		fn create(824			from: H160,825			data: Vec<u8>,826			value: U256,827			gas_limit: U256,828			gas_price: Option<U256>,829			nonce: Option<U256>,830			estimate: bool,831		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {832			let config = if estimate {833				let mut config = <Runtime as pallet_evm::Config>::config().clone();834				config.estimate = true;835				Some(config)836			} else {837				None838			};839840			<Runtime as pallet_evm::Config>::Runner::create(841				from,842				data,843				value,844				gas_limit.low_u64(),845				gas_price,846				nonce,847				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),848			).map_err(|err| err.into())849		}850851		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {852			Ethereum::current_transaction_statuses()853		}854855		fn current_block() -> Option<pallet_ethereum::Block> {856			Ethereum::current_block()857		}858859		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {860			Ethereum::current_receipts()861		}862863		fn current_all() -> (864			Option<pallet_ethereum::Block>,865			Option<Vec<pallet_ethereum::Receipt>>,866			Option<Vec<TransactionStatus>>867		) {868			(869				Ethereum::current_block(),870				Ethereum::current_receipts(),871				Ethereum::current_transaction_statuses()872			)873		}874	}875876	impl sp_session::SessionKeys<Block> for Runtime {877		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {878			opaque::SessionKeys::generate(seed)879		}880881		fn decode_session_keys(882			encoded: Vec<u8>,883		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {884			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)885		}886	}887888	impl fg_primitives::GrandpaApi<Block> for Runtime {889		fn grandpa_authorities() -> GrandpaAuthorityList {890			Grandpa::grandpa_authorities()891		}892893		fn submit_report_equivocation_unsigned_extrinsic(894			_equivocation_proof: fg_primitives::EquivocationProof<895				<Block as BlockT>::Hash,896				NumberFor<Block>,897			>,898			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,899		) -> Option<()> {900			None901		}902903		fn generate_key_ownership_proof(904			_set_id: fg_primitives::SetId,905			_authority_id: GrandpaId,906		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {907			// NOTE: this is the only implementation possible since we've908			// defined our key owner proof type as a bottom type (i.e. a type909			// with no values).910			None911		}912	}913914	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {915		fn account_nonce(account: AccountId) -> Index {916			System::account_nonce(account)917		}918	}919920	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {921		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {922			TransactionPayment::query_info(uxt, len)923		}924		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {925			TransactionPayment::query_fee_details(uxt, len)926		}927	}928929	#[cfg(feature = "runtime-benchmarks")]930	impl frame_benchmarking::Benchmark<Block> for Runtime {931		fn dispatch_benchmark(932			config: frame_benchmarking::BenchmarkConfig933		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {934			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};935936			let whitelist: Vec<TrackedStorageKey> = vec![937				// Alice account938				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),939				// // Total Issuance940				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),941				// // Execution Phase942				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),943				// // Event Count944				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),945				// // System Events946				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),947			];948949			let mut batches = Vec::<BenchmarkBatch>::new();950			let params = (&config, &whitelist);951952			add_benchmark!(params, batches, pallet_nft, Nft);953954			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }955			Ok(batches)956		}957	}958}
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, OnMethodCall};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 BlockGasLimit = BlockGasLimit;348	type FeeCalculator = ();349	type GasWeightMapping = ();350	type CallOrigin = EnsureAddressTruncated;351	type WithdrawOrigin = EnsureAddressTruncated;352	type AddressMapping = HashedAddressMapping<Self::Hashing>;353	type Precompiles = ();354	type Currency = Balances;355	type Event = Event;356	type OnMethodCall = pallet_nft::NftErcSupport<Self>;357	type ChainId = ChainId;358	type Runner = pallet_evm::runner::stack::Runner<Self>;359	type OnChargeTransaction = ();360}361362pub struct EthereumFindAuthor<F>(PhantomData<F>);363impl<F: FindAuthor<u32>> FindAuthor<H160> for EthereumFindAuthor<F>364{365	fn find_author<'a, I>(digests: I) -> Option<H160> where366		I: 'a + IntoIterator<Item=(ConsensusEngineId, &'a [u8])>367	{368		if let Some(author_index) = F::find_author(digests) {369			let authority_id = Aura::authorities()[author_index as usize].clone();370			return Some(H160::from_slice(&authority_id.to_raw_vec()[4..24]));371		}372		None373	}374}375376parameter_types! {377	pub BlockGasLimit: U256 = U256::from(u32::max_value());378}379380impl pallet_ethereum::Config for Runtime {381	type Event = Event;382	type FindAuthor = EthereumFindAuthor<Aura>;383	type StateRoot = pallet_ethereum::IntermediateStateRoot;384	type EvmSubmitLog = pallet_evm::Module<Runtime>;385}386387impl pallet_grandpa::Config for Runtime {388	type Event = Event;389	type Call = Call;390391	type KeyOwnerProofSystem = ();392393	type KeyOwnerProof =394		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;395396	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(397		KeyTypeId,398		GrandpaId,399	)>>::IdentificationTuple;400401	type HandleEquivocation = ();402403	type WeightInfo = ();404}405406parameter_types! {407	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;408}409410impl pallet_timestamp::Config for Runtime {411	/// A timestamp: milliseconds since the unix epoch.412	type Moment = u64;413	type OnTimestampSet = Aura;414	type MinimumPeriod = MinimumPeriod;415	type WeightInfo = ();416}417418parameter_types! {419	// pub const ExistentialDeposit: u128 = 500;420	pub const ExistentialDeposit: u128 = 0;421	pub const MaxLocks: u32 = 50;422}423424impl pallet_balances::Config for Runtime {425	type MaxLocks = MaxLocks;426	/// The type for recording an account's balance.427	type Balance = Balance;428	/// The ubiquitous event type.429	type Event = Event;430	type DustRemoval = Treasury;431	type ExistentialDeposit = ExistentialDeposit;432	type AccountStore = System;433	type WeightInfo = ();434}435436pub const MICROUNIQUE: Balance = 1_000_000_000;437pub const MILLIUNIQUE: Balance = 1_000 * MICROUNIQUE;438pub const CENTIUNIQUE: Balance = 10 * MILLIUNIQUE;439pub const UNIQUE: Balance      = 100 * CENTIUNIQUE;440441pub const fn deposit(items: u32, bytes: u32) -> Balance {442	items as Balance * 15 * CENTIUNIQUE + (bytes as Balance) * 6 * CENTIUNIQUE443}444445parameter_types! {446	pub const TombstoneDeposit: Balance = deposit(447		0,448		sp_std::mem::size_of::<pallet_contracts::ContractInfo<Runtime>>() as u32449	);450	pub const DepositPerContract: Balance = TombstoneDeposit::get();451	pub const DepositPerStorageByte: Balance = deposit(0, 1);452	pub const DepositPerStorageItem: Balance = deposit(1, 0);453	pub RentFraction: Perbill = Perbill::from_rational_approximation(1u32, 30 * DAYS);454	pub const SurchargeReward: Balance = 150 * MILLIUNIQUE;455	pub const SignedClaimHandicap: u32 = 2;456	pub const MaxDepth: u32 = 32;457	pub const MaxValueSize: u32 = 16 * 1024;458	pub const MaxCodeSize: u32 = 1024 * 1024 * 25; // 25 Mb459	// The lazy deletion runs inside on_initialize.460	pub DeletionWeightLimit: Weight = AVERAGE_ON_INITIALIZE_RATIO *461		RuntimeBlockWeights::get().max_block;462	// The weight needed for decoding the queue should be less or equal than a fifth463	// of the overall weight dedicated to the lazy deletion.464	pub DeletionQueueDepth: u32 = ((DeletionWeightLimit::get() / (465			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(1) -466			<Runtime as pallet_contracts::Config>::WeightInfo::on_initialize_per_queue_item(0)467		)) / 5) as u32;468}469470471impl pallet_contracts::Config for Runtime {472	type Time = Timestamp;473	type Randomness = RandomnessCollectiveFlip;474	type Currency = Balances;475	type Event = Event;476	type RentPayment = ();477	type SignedClaimHandicap = SignedClaimHandicap;478	type TombstoneDeposit = TombstoneDeposit;479	type DepositPerContract = DepositPerContract;480	type DepositPerStorageByte = DepositPerStorageByte;481	type DepositPerStorageItem = DepositPerStorageItem;482	type RentFraction = RentFraction;483	type SurchargeReward = SurchargeReward;484	type MaxDepth = MaxDepth;485	type MaxValueSize = MaxValueSize;486	type WeightPrice = pallet_transaction_payment::Module<Self>;487	type WeightInfo = pallet_contracts::weights::SubstrateWeight<Self>;488	type ChainExtension = NFTExtension;489	type DeletionQueueDepth = DeletionQueueDepth;490	type DeletionWeightLimit = DeletionWeightLimit;491	type MaxCodeSize = MaxCodeSize;492}493494parameter_types! {495	pub const TransactionByteFee: Balance = 501 * MICROUNIQUE; // Targeting 0.1 Unique per NFT transfer496}497498/// Linear implementor of `WeightToFeePolynomial`499pub struct LinearFee<T>(sp_std::marker::PhantomData<T>);500501impl<T> WeightToFeePolynomial for LinearFee<T> where502	T: BaseArithmetic + From<u32> + Copy + Unsigned503{504	type Balance = T;505506	fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {507		smallvec!(WeightToFeeCoefficient {508			coeff_integer: 146_700u32.into(), // Targeting 0.1 Unique per NFT transfer509			coeff_frac: Perbill::zero(),510			negative: false,511			degree: 1,512		})513	}514}515516impl pallet_transaction_payment::Config for Runtime {517	type OnChargeTransaction = CurrencyAdapter<Balances, DealWithFees>;518	type TransactionByteFee = TransactionByteFee;519	type WeightToFee = LinearFee<Balance>;520	type FeeMultiplierUpdate = ();521}522523parameter_types! {524	pub const ProposalBond: Permill = Permill::from_percent(5);525	pub const ProposalBondMinimum: Balance = 1 * UNIQUE;526	pub const SpendPeriod: BlockNumber = 5 * MINUTES;527	pub const Burn: Permill = Permill::from_percent(0);528	pub const TipCountdown: BlockNumber = 1 * DAYS;529	pub const TipFindersFee: Percent = Percent::from_percent(20);530	pub const TipReportDepositBase: Balance = 1 * UNIQUE;531	pub const DataDepositPerByte: Balance = 1 * CENTIUNIQUE;532	pub const BountyDepositBase: Balance = 1 * UNIQUE;533	pub const BountyDepositPayoutDelay: BlockNumber = 1 * DAYS;534	pub const TreasuryModuleId: ModuleId = ModuleId(*b"py/trsry");535	pub const BountyUpdatePeriod: BlockNumber = 14 * DAYS;536	pub const MaximumReasonLength: u32 = 16384;537	pub const BountyCuratorDeposit: Permill = Permill::from_percent(50);538	pub const BountyValueMinimum: Balance = 5 * UNIQUE;539}540541impl pallet_treasury::Config for Runtime {542	type ModuleId = TreasuryModuleId;543	type Currency = Balances;544	type ApproveOrigin = EnsureRoot<AccountId>;545	type RejectOrigin = EnsureRoot<AccountId>;546	type Event = Event;547	type OnSlash = ();548	type ProposalBond = ProposalBond;549	type ProposalBondMinimum = ProposalBondMinimum;550	type SpendPeriod = SpendPeriod;551	type Burn = Burn;552	type BurnDestination = ();553	type SpendFunds = ();554	type WeightInfo = pallet_treasury::weights::SubstrateWeight<Runtime>;555}556557impl pallet_sudo::Config for Runtime {558	type Event = Event;559	type Call = Call;560}561562parameter_types! {563	pub const MinVestedTransfer: Balance = 10 * UNIQUE;564}565566impl pallet_vesting::Config for Runtime {567	type Event = Event;568	type Currency = Balances;569	type BlockNumberToBalance = ConvertInto;570	type MinVestedTransfer = MinVestedTransfer;571	type WeightInfo = ();572}573574parameter_types! {575	pub TreasuryAccountId: AccountId = TreasuryModuleId::get().into_account();576	pub const CollectionCreationPrice: Balance = 100 * UNIQUE;577}578579/// Used for the module nft in `./nft.rs`580impl pallet_nft::Config for Runtime {581	type Event = Event;582	type WeightInfo = nft_weights::WeightInfo;583584	type EvmWithdrawOrigin = EnsureAddressTruncated;585	type EvmBackwardsAddressMapping = pallet_nft::MapBackwardsAddressTruncated;586	type EvmAddressMapping = HashedAddressMapping<Self::Hashing>;587	type CrossAccountId = pallet_nft::BasicCrossAccountId<Self>;588589	type Currency = Balances;590	type CollectionCreationPrice = CollectionCreationPrice;591	type TreasuryAccountId = TreasuryAccountId;592593	type EthereumChainId = ChainId;594	type EthereumTransactionSender = pallet_ethereum::Module<Runtime>;595}596597construct_runtime!(598	pub enum Runtime where599		Block = Block,600		NodeBlock = opaque::Block,601		UncheckedExtrinsic = UncheckedExtrinsic602	{603		System: system::{Module, Call, Config, Storage, Event<T>},604		RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},605		Contracts: pallet_contracts::{Module, Call, Config<T>, Storage, Event<T>},606		Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},607		Aura: pallet_aura::{Module, Config<T> },608		EVM: pallet_evm::{Module, Config, Call, Storage, Event<T>},609		Ethereum: pallet_ethereum::{Module, Config, Call, Storage, Event, ValidateUnsigned},610		Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},611		Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},612		TransactionPayment: pallet_transaction_payment::{Module, Storage},613		Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},614		Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},615		Treasury: pallet_treasury::{Module, Call, Storage, Config, Event<T>},616		Vesting: pallet_vesting::{Module, Call, Config<T>, Storage, Event<T>},617	}618);619620pub struct TransactionConverter;621622impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {623	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {624		UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into())625	}626}627628impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {629	fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> opaque::UncheckedExtrinsic {630		let extrinsic = UncheckedExtrinsic::new_unsigned(pallet_ethereum::Call::<Runtime>::transact(transaction).into());631		let encoded = extrinsic.encode();632		opaque::UncheckedExtrinsic::decode(&mut &encoded[..]).expect("Encoded extrinsic is always valid")633	}634}635636/// The address format for describing accounts.637pub type Address = AccountId;638/// Block header type as expected by this runtime.639pub type Header = generic::Header<BlockNumber, BlakeTwo256>;640/// Block type as expected by this runtime.641pub type Block = generic::Block<Header, UncheckedExtrinsic>;642/// A Block signed with a Justification643pub type SignedBlock = generic::SignedBlock<Block>;644/// BlockId type as expected by this runtime.645pub type BlockId = generic::BlockId<Block>;646/// The SignedExtension to the basic transaction logic.647pub type SignedExtra = (648	system::CheckSpecVersion<Runtime>,649	system::CheckTxVersion<Runtime>,650	system::CheckGenesis<Runtime>,651	system::CheckEra<Runtime>,652	system::CheckNonce<Runtime>,653	system::CheckWeight<Runtime>,654	pallet_nft::ChargeTransactionPayment<Runtime>,655);656/// Unchecked extrinsic type as expected by this runtime.657pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;658/// Extrinsic type that has already been checked.659pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;660/// Executive: handles dispatch to the various modules.661pub type Executive =662	frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;663664impl_runtime_apis! {665	impl pallet_nft::NftApi<Block>666		for Runtime667	{668		fn eth_contract_code(account: H160) -> Option<Vec<u8>> {669			<pallet_nft::NftErcSupport<Runtime>>::get_code(&account)670		}671	}672673	impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>674		for Runtime675	{676		fn call(677			origin: AccountId,678			dest: AccountId,679			value: Balance,680			gas_limit: u64,681			input_data: Vec<u8>,682		) -> pallet_contracts_primitives::ContractExecResult {683			Contracts::bare_call(origin, dest, value, gas_limit, input_data)684		}685686		fn get_storage(687			address: AccountId,688			key: [u8; 32],689		) -> pallet_contracts_primitives::GetStorageResult {690			Contracts::get_storage(address, key)691		}692693		fn rent_projection(694			address: AccountId,695		) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {696			Contracts::rent_projection(address)697		}698	}699700	impl sp_api::Core<Block> for Runtime {701		fn version() -> RuntimeVersion {702			VERSION703		}704705		fn execute_block(block: Block) {706			Executive::execute_block(block)707		}708709		fn initialize_block(header: &<Block as BlockT>::Header) {710			Executive::initialize_block(header)711		}712	}713714	impl sp_api::Metadata<Block> for Runtime {715		fn metadata() -> OpaqueMetadata {716			Runtime::metadata().into()717		}718	}719720	impl sp_block_builder::BlockBuilder<Block> for Runtime {721		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {722			Executive::apply_extrinsic(extrinsic)723		}724725		fn finalize_block() -> <Block as BlockT>::Header {726			Executive::finalize_block()727		}728729		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {730			data.create_extrinsics()731		}732733		fn check_inherents(734			block: Block,735			data: sp_inherents::InherentData,736		) -> sp_inherents::CheckInherentsResult {737			data.check_extrinsics(&block)738		}739740		fn random_seed() -> <Block as BlockT>::Hash {741			RandomnessCollectiveFlip::random_seed().0742		}743	}744745	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {746		fn validate_transaction(747			source: TransactionSource,748			tx: <Block as BlockT>::Extrinsic,749		) -> TransactionValidity {750			Executive::validate_transaction(source, tx)751		}752	}753754	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {755		fn offchain_worker(header: &<Block as BlockT>::Header) {756			Executive::offchain_worker(header)757		}758	}759760	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {761		fn slot_duration() -> u64 {762			Aura::slot_duration()763		}764765		fn authorities() -> Vec<AuraId> {766			Aura::authorities()767		}768	}769770	impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {771		fn chain_id() -> u64 {772			<Runtime as pallet_evm::Config>::ChainId::get()773		}774775		fn account_basic(address: H160) -> EVMAccount {776			EVM::account_basic(&address)777		}778779		fn gas_price() -> U256 {780			<Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price()781		}782783		fn account_code_at(address: H160) -> Vec<u8> {784			EVM::account_codes(address)785		}786787		fn author() -> H160 {788			<pallet_ethereum::Module<Runtime>>::find_author()789		}790791		fn storage_at(address: H160, index: U256) -> H256 {792			let mut tmp = [0u8; 32];793			index.to_big_endian(&mut tmp);794			EVM::account_storages(address, H256::from_slice(&tmp[..]))795		}796797		fn call(798			from: H160,799			to: H160,800			data: Vec<u8>,801			value: U256,802			gas_limit: U256,803			gas_price: Option<U256>,804			nonce: Option<U256>,805			estimate: bool,806		) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {807			let config = if estimate {808				let mut config = <Runtime as pallet_evm::Config>::config().clone();809				config.estimate = true;810				Some(config)811			} else {812				None813			};814815			<Runtime as pallet_evm::Config>::Runner::call(816				from,817				to,818				data,819				value,820				gas_limit.low_u64(),821				gas_price,822				nonce,823				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),824			).map_err(|err| err.into())825		}826827		fn create(828			from: H160,829			data: Vec<u8>,830			value: U256,831			gas_limit: U256,832			gas_price: Option<U256>,833			nonce: Option<U256>,834			estimate: bool,835		) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {836			let config = if estimate {837				let mut config = <Runtime as pallet_evm::Config>::config().clone();838				config.estimate = true;839				Some(config)840			} else {841				None842			};843844			<Runtime as pallet_evm::Config>::Runner::create(845				from,846				data,847				value,848				gas_limit.low_u64(),849				gas_price,850				nonce,851				config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),852			).map_err(|err| err.into())853		}854855		fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {856			Ethereum::current_transaction_statuses()857		}858859		fn current_block() -> Option<pallet_ethereum::Block> {860			Ethereum::current_block()861		}862863		fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {864			Ethereum::current_receipts()865		}866867		fn current_all() -> (868			Option<pallet_ethereum::Block>,869			Option<Vec<pallet_ethereum::Receipt>>,870			Option<Vec<TransactionStatus>>871		) {872			(873				Ethereum::current_block(),874				Ethereum::current_receipts(),875				Ethereum::current_transaction_statuses()876			)877		}878	}879880	impl sp_session::SessionKeys<Block> for Runtime {881		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {882			opaque::SessionKeys::generate(seed)883		}884885		fn decode_session_keys(886			encoded: Vec<u8>,887		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {888			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)889		}890	}891892	impl fg_primitives::GrandpaApi<Block> for Runtime {893		fn grandpa_authorities() -> GrandpaAuthorityList {894			Grandpa::grandpa_authorities()895		}896897		fn submit_report_equivocation_unsigned_extrinsic(898			_equivocation_proof: fg_primitives::EquivocationProof<899				<Block as BlockT>::Hash,900				NumberFor<Block>,901			>,902			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,903		) -> Option<()> {904			None905		}906907		fn generate_key_ownership_proof(908			_set_id: fg_primitives::SetId,909			_authority_id: GrandpaId,910		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {911			// NOTE: this is the only implementation possible since we've912			// defined our key owner proof type as a bottom type (i.e. a type913			// with no values).914			None915		}916	}917918	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {919		fn account_nonce(account: AccountId) -> Index {920			System::account_nonce(account)921		}922	}923924	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {925		fn query_info(uxt: <Block as BlockT>::Extrinsic, len: u32) -> RuntimeDispatchInfo<Balance> {926			TransactionPayment::query_info(uxt, len)927		}928		fn query_fee_details(uxt: <Block as BlockT>::Extrinsic, len: u32) -> FeeDetails<Balance> {929			TransactionPayment::query_fee_details(uxt, len)930		}931	}932933	#[cfg(feature = "runtime-benchmarks")]934	impl frame_benchmarking::Benchmark<Block> for Runtime {935		fn dispatch_benchmark(936			config: frame_benchmarking::BenchmarkConfig937		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {938			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};939940			let whitelist: Vec<TrackedStorageKey> = vec![941				// Alice account942				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),943				// // Total Issuance944				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),945				// // Execution Phase946				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),947				// // Event Count948				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),949				// // System Events950				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),951			];952953			let mut batches = Vec::<BenchmarkBatch>::new();954			let params = (&config, &whitelist);955956			add_benchmark!(params, batches, pallet_nft, Nft);957958			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }959			Ok(batches)960		}961	}962}