git.delta.rocks / unique-network / refs/commits / e9291bd41a30

difftreelog

Add economic model POC

Greg Zaitsev2020-07-27parent: #31df977.patch.diff
in: master

5 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3085,10 +3085,12 @@
 dependencies = [
  "frame-support",
  "frame-system",
+ "pallet-transaction-payment",
  "parity-scale-codec",
  "sp-core",
  "sp-io",
  "sp-runtime",
+ "sp-std",
 ]
 
 [[package]]
modifieddoc/application_development.mddiffbeforeafterboth
--- a/doc/application_development.md
+++ b/doc/application_development.md
@@ -16,6 +16,54 @@
 
 ![](serverless_architecture.png)
 
+## Custom Types for JS API
+
+```
+{
+  "Schedule": {
+    "version": "u32",
+    "put_code_per_byte_cost": "Gas",
+    "grow_mem_cost": "Gas",
+    "regular_op_cost": "Gas",
+    "return_data_per_byte_cost": "Gas",
+    "event_data_per_byte_cost": "Gas",
+    "event_per_topic_cost": "Gas",
+    "event_base_cost": "Gas",
+    "call_base_cost": "Gas",
+    "instantiate_base_cost": "Gas",
+    "dispatch_base_cost": "Gas",
+    "sandbox_data_read_cost": "Gas",
+    "sandbox_data_write_cost": "Gas",
+    "transfer_cost": "Gas",
+    "instantiate_cost": "Gas",
+    "max_event_topics": "u32",
+    "max_stack_height": "u32",
+    "max_memory_pages": "u32",
+    "max_table_size": "u32",
+    "enable_println": "bool",
+    "max_subject_len": "u32"
+  },
+  "NftItemType": {
+    "Collection": "u64",
+    "Owner": "AccountId",
+    "Data": "Vec<u8>"
+  },
+  "CollectionType": {
+    "Owner": "AccountId",
+    "NextItemId": "u64",
+    "Name": "Vec<u16>",
+    "Description": "Vec<u16>",
+    "TokenPrefix": "Vec<u8>",
+    "CustomDataSize": "u32",
+    "Sponsor": "AccountId",
+    "UnconfirmedSponsor": "AccountId"
+  },
+  "Address": "AccountId",
+  "LookupSource": "AccountId",
+  "Weight": "u64"
+}
+```
+
 ## NFT Palette Methods
 
 ### Collection Management
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -33,6 +33,19 @@
 branch = 'rc4_ext_dispatch_reenabled'
 version = '2.0.0-rc4'
 
+[dependencies.sp-std]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+branch = 'rc4_ext_dispatch_reenabled'
+version = '2.0.0-rc4'
+
+[dependencies.transaction-payment]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-transaction-payment'
+branch = 'rc4_ext_dispatch_reenabled'
+version = '2.0.0-rc4'
+
 [package]
 authors = ['Substrate DevHub <https://github.com/substrate-developer-hub>']
 description = 'FRAME pallet nft'
@@ -52,4 +65,5 @@
     'frame-support/std',
     'frame-system/std',
     'sp-runtime/std',
+    'sp-std/std',
 ]
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -9,9 +9,32 @@
 
 /// For more guidance on Substrate FRAME, see the example pallet
 /// https://github.com/paritytech/substrate/blob/master/frame/example/src/lib.rs
-use frame_support::{decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure};
+pub use frame_support::{
+    decl_event, decl_module, decl_storage,
+    construct_runtime, parameter_types,
+    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason, Imbalance},
+    weights::{
+        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},
+        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,
+    },
+    StorageValue,
+    dispatch::DispatchResult, 
+    IsSubType,
+    ensure
+};
+
 use frame_system::{self as system, ensure_signed};
 use sp_runtime::sp_std::prelude::Vec;
+use sp_std::prelude::*;
+use sp_runtime::{
+	FixedU128, FixedPointOperand, 
+	transaction_validity::{
+		TransactionPriority, ValidTransaction, InvalidTransaction, TransactionValidityError, TransactionValidity
+	},
+	traits::{
+        Saturating, Dispatchable, DispatchInfoOf, PostDispatchInfoOf, SignedExtension, Zero, SaturatedConversion,
+	},
+};
 
 #[cfg(test)]
 mod mock;
@@ -28,6 +51,8 @@
     pub description: Vec<u16>, // 256 include null escape char
     pub token_prefix: Vec<u8>, // 16 include null escape char
     pub custom_data_size: u32,
+    pub sponsor: AccountId,    // Who pays fees. If set to default address, the fees are applied to the transaction sender
+    pub unconfirmed_sponsor: AccountId, // Sponsor address that has not yet confirmed sponsorship
 }
 
 #[derive(Encode, Decode, Default, Clone, PartialEq)]
@@ -51,6 +76,7 @@
 
     /// The overarching event type.
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
+
 }
 
 // This pallet's storage items.
@@ -138,6 +164,8 @@
                 token_prefix: prefix,
                 next_item_id: next_id,
                 custom_data_size: custom_data_sz,
+                sponsor: T::AccountId::default(),
+                unconfirmed_sponsor: T::AccountId::default(),
             };
 
             // Add new collection to map
@@ -237,6 +265,54 @@
         }
 
         #[weight = 0]
+        pub fn set_collection_sponsor(origin, collection_id: u64, new_sponsor: T::AccountId) -> DispatchResult {
+
+            let sender = ensure_signed(origin)?;
+            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
+
+            let mut target_collection = <Collection<T>>::get(collection_id);
+            ensure!(sender == target_collection.owner, "You do not own this collection");
+
+            target_collection.unconfirmed_sponsor = new_sponsor;
+            <Collection<T>>::insert(collection_id, target_collection);
+
+            Ok(())
+        }
+
+        #[weight = 0]
+        pub fn confirm_sponsorship(origin, collection_id: u64) -> DispatchResult {
+
+            let sender = ensure_signed(origin)?;
+            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
+
+            let mut target_collection = <Collection<T>>::get(collection_id);
+            ensure!(sender == target_collection.unconfirmed_sponsor, "This address is not set as sponsor, use setCollectionSponsor first");
+
+            target_collection.sponsor = target_collection.unconfirmed_sponsor;
+            target_collection.unconfirmed_sponsor = T::AccountId::default();
+            <Collection<T>>::insert(collection_id, target_collection);
+
+            Ok(())
+        }
+
+        #[weight = 0]
+        pub fn remove_collection_sponsor(origin, collection_id: u64) -> DispatchResult {
+
+            let sender = ensure_signed(origin)?;
+            ensure!(<Collection<T>>::contains_key(collection_id), "This collection does not exist");
+
+            let mut target_collection = <Collection<T>>::get(collection_id);
+            ensure!(sender == target_collection.owner, "You do not own this collection");
+
+            target_collection.sponsor = T::AccountId::default();
+            <Collection<T>>::insert(collection_id, target_collection);
+
+            Ok(())
+        }
+        
+
+
+        #[weight = 0]
         pub fn create_item(origin, collection_id: u64, properties: Vec<u8>) -> DispatchResult {
 
             let sender = ensure_signed(origin)?;
@@ -490,3 +566,185 @@
         Ok(())
     }
 }
+
+
+////////////////////////////////////////////////////////////////////////////////////////////////////
+// Economic models
+
+/// Fee multiplier.
+pub type Multiplier = FixedU128;
+
+type BalanceOf<T> =
+	<<T as transaction_payment::Trait>::Currency as Currency<<T as system::Trait>::AccountId>>::Balance;
+type NegativeImbalanceOf<T> = <<T as transaction_payment::Trait>::Currency as Currency<
+	<T as system::Trait>::AccountId,>>::NegativeImbalance;
+
+
+
+/// Require the transactor pay for themselves and maybe include a tip to gain additional priority
+/// in the queue.
+#[derive(Encode, Decode, Clone, Eq, PartialEq)]
+pub struct ChargeTransactionPayment<T: transaction_payment::Trait + Send + Sync>(#[codec(compact)] BalanceOf<T>);
+
+impl<T:Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug for ChargeTransactionPayment<T> {
+	#[cfg(feature = "std")]
+	fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+		write!(f, "ChargeTransactionPayment<{:?}>", self.0)
+	}
+	#[cfg(not(feature = "std"))]
+	fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+		Ok(())
+	}
+}
+
+impl<T:Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T> where
+	T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
+	BalanceOf<T>: Send + Sync + FixedPointOperand,
+{
+	/// utility constructor. Used only in client/factory code.
+	pub fn from(fee: BalanceOf<T>) -> Self {
+		Self(fee)
+	}
+
+    pub fn traditional_fee(
+        len: usize,
+        info: &DispatchInfoOf<T::Call>,
+        tip: BalanceOf<T>,
+    ) -> BalanceOf<T> where
+        T::Call: Dispatchable<Info=DispatchInfo>,
+    {
+        <transaction_payment::Module<T>>::compute_fee(len as u32, info, tip)
+    }
+
+	fn withdraw_fee(
+		&self,
+        who: &T::AccountId,
+        call: &T::Call,
+		info: &DispatchInfoOf<T::Call>,
+		len: usize,
+	) -> Result<(BalanceOf<T>, Option<NegativeImbalanceOf<T>>), TransactionValidityError> {
+        let tip = self.0;
+
+        // Set fee based on call type. Creating collection costs 1 Unique.
+        // All other transactions have traditional fees so far
+        let fee = match call.is_sub_type() {
+            Some(Call::create_collection(..)) => <BalanceOf<T>>::from(1_000_000_000),
+            _ => Self::traditional_fee(len, info, tip)
+
+            // Flat fee model, use only for testing purposes
+            // _ => <BalanceOf<T>>::from(100)
+        };
+
+        // Determine who is paying transaction fee based on ecnomic model
+        // Parse call to extract collection ID and access collection sponsor
+        let sponsor: T::AccountId = match call.is_sub_type() {
+            Some(Call::create_item(collection_id, _properties)) => {
+                <Collection<T>>::get(collection_id).sponsor
+            },
+            Some(Call::transfer(collection_id, _item_id, _new_owner)) => {
+                <Collection<T>>::get(collection_id).sponsor
+            },
+
+            _ => T::AccountId::default()
+        };
+
+        let mut who_pays_fee: T::AccountId = sponsor.clone();
+        if sponsor == T::AccountId::default() {
+            who_pays_fee = who.clone();
+        }
+
+		// Only mess with balances if fee is not zero.
+		if fee.is_zero() {
+			return Ok((fee, None));
+		}
+
+		match <T as transaction_payment::Trait>::Currency::withdraw(
+			&who_pays_fee,
+			fee,
+			if tip.is_zero() {
+				WithdrawReason::TransactionPayment.into()
+			} else {
+				WithdrawReason::TransactionPayment | WithdrawReason::Tip
+			},
+			ExistenceRequirement::KeepAlive,
+		) {
+			Ok(imbalance) => Ok((fee, Some(imbalance))),
+			Err(_) => Err(InvalidTransaction::Payment.into()),
+		}
+	}
+}
+
+impl<T:Trait + transaction_payment::Trait + Send + Sync> SignedExtension for ChargeTransactionPayment<T> where
+    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
+    T::Call: Dispatchable<Info=DispatchInfo, PostInfo=PostDispatchInfo> + IsSubType<Module<T>, T>,
+{
+	const IDENTIFIER: &'static str = "ChargeTransactionPayment";
+	type AccountId = T::AccountId;
+	type Call = T::Call;
+	type AdditionalSigned = ();
+	type Pre = (BalanceOf<T>, Self::AccountId, Option<NegativeImbalanceOf<T>>, BalanceOf<T>);
+	fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { Ok(()) }
+
+	fn validate(
+		&self,
+		who: &Self::AccountId,
+		call: &Self::Call,
+		info: &DispatchInfoOf<Self::Call>,
+		len: usize,
+	) -> TransactionValidity {
+		let (fee, _) = self.withdraw_fee(who, call, info, len)?;
+
+		let mut r = ValidTransaction::default();
+		// NOTE: we probably want to maximize the _fee (of any type) per weight unit_ here, which
+		// will be a bit more than setting the priority to tip. For now, this is enough.
+		r.priority = fee.saturated_into::<TransactionPriority>();
+		Ok(r)
+	}
+
+	fn pre_dispatch(
+		self,
+		who: &Self::AccountId,
+		call: &Self::Call,
+		info: &DispatchInfoOf<Self::Call>,
+		len: usize
+	) -> Result<Self::Pre, TransactionValidityError> {
+		let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
+		Ok((self.0, who.clone(), imbalance, fee))
+	}
+
+	fn post_dispatch(
+		pre: Self::Pre,
+		info: &DispatchInfoOf<Self::Call>,
+		post_info: &PostDispatchInfoOf<Self::Call>,
+		len: usize,
+		_result: &DispatchResult,
+	) -> Result<(), TransactionValidityError> {
+		let (tip, who, imbalance, fee) = pre;
+		if let Some(payed) = imbalance {
+			let actual_fee = <transaction_payment::Module<T>>::compute_actual_fee(
+				len as u32,
+				info,
+				post_info,
+				tip,
+			);
+			let refund = fee.saturating_sub(actual_fee);
+			let actual_payment = match <T as transaction_payment::Trait>::Currency::deposit_into_existing(&who, refund) {
+				Ok(refund_imbalance) => {
+					// The refund cannot be larger than the up front payed max weight.
+					// `PostDispatchInfo::calc_unspent` guards against such a case.
+					match payed.offset(refund_imbalance) {
+						Ok(actual_payment) => actual_payment,
+						Err(_) => return Err(InvalidTransaction::Payment.into()),
+					}
+				}
+				// We do not recreate the account using the refund. The up front payment
+				// is gone in that case.
+				Err(_) => payed,
+			};
+			let imbalances = actual_payment.split(tip);
+			<T as transaction_payment::Trait>::OnTransactionPayment::on_unbalanceds(Some(imbalances.0).into_iter()
+				.chain(Some(imbalances.1)));
+		}
+		Ok(())
+	}
+}
modifiedruntime/src/lib.rsdiffbeforeafterboth
before · runtime/src/lib.rs
1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use contracts_rpc_runtime_api::ContractExecResult;12use grandpa::fg_primitives;13use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::traits::{18    BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,19};20use sp_runtime::{21    create_runtime_str, generic, impl_opaque_keys,22    transaction_validity::{TransactionSource, TransactionValidity},23    ApplyExtrinsicResult, MultiSignature,24};25use sp_std::prelude::*;26#[cfg(feature = "std")]27use sp_version::NativeVersion;28use sp_version::RuntimeVersion;2930// A few exports that help ease life for downstream crates.31pub use balances::Call as BalancesCall;32pub use contracts::Schedule as ContractsSchedule;33pub use frame_support::{34    construct_runtime, parameter_types,35    traits::{KeyOwnerProofSystem, Randomness},36    weights::{37        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},38        IdentityFee, Weight,39    },40    StorageValue,41};42#[cfg(any(feature = "std", test))]43pub use sp_runtime::BuildStorage;44pub use sp_runtime::{Perbill, Permill};45pub use timestamp::Call as TimestampCall;4647/// Importing a nft pallet48pub use nft;4950/// An index to a block.51pub type BlockNumber = u32;5253/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.54pub type Signature = MultiSignature;5556/// Some way of identifying an account on the chain. We intentionally make it equivalent57/// to the public key of our transaction signing scheme.58pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5960/// The type for looking up accounts. We don't expect more than 4 billion of them, but you61/// never know...62pub type AccountIndex = u32;6364/// Balance of an account.65pub type Balance = u128;6667/// Index of a transaction in the chain.68pub type Index = u32;6970/// A hash of some data used by the chain.71pub type Hash = sp_core::H256;7273/// Digest item type.74pub type DigestItem = generic::DigestItem<Hash>;7576/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know77/// the specifics of the runtime. They can then be made to be agnostic over specific formats78/// of data like extrinsics, allowing for them to continue syncing the network through upgrades79/// to even the core data structures.80pub mod opaque {81    use super::*;8283    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;8485    /// Opaque block header type.86    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;87    /// Opaque block type.88    pub type Block = generic::Block<Header, UncheckedExtrinsic>;89    /// Opaque block identifier type.90    pub type BlockId = generic::BlockId<Block>;9192    impl_opaque_keys! {93        pub struct SessionKeys {94            pub aura: Aura,95            pub grandpa: Grandpa,96        }97    }98}99100/// This runtime version.101pub const VERSION: RuntimeVersion = RuntimeVersion {102    spec_name: create_runtime_str!("nft"),103    impl_name: create_runtime_str!("nft"),104    authoring_version: 1,105    spec_version: 1,106    impl_version: 1,107    apis: RUNTIME_API_VERSIONS,108    transaction_version: 1,109};110111pub const MILLISECS_PER_BLOCK: u64 = 6000;112113pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;114115// These time units are defined in number of blocks.116pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);117pub const HOURS: BlockNumber = MINUTES * 60;118pub const DAYS: BlockNumber = HOURS * 24;119120/// The version information used to identify this runtime when compiled natively.121#[cfg(feature = "std")]122pub fn native_version() -> NativeVersion {123    NativeVersion {124        runtime_version: VERSION,125        can_author_with: Default::default(),126    }127}128129parameter_types! {130    pub const BlockHashCount: BlockNumber = 2400;131    /// We allow for 2 seconds of compute with a 6 second average block time.132    pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;133    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);134    /// Assume 10% of weight for average on_initialize calls.135    pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()136        .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();137    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;138    pub const Version: RuntimeVersion = VERSION;139}140141impl system::Trait for Runtime {142    /// The basic call filter to use in dispatchable.143    type BaseCallFilter = ();144    /// The identifier used to distinguish between accounts.145    type AccountId = AccountId;146    /// The aggregated dispatch type that is available for extrinsics.147    type Call = Call;148    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.149    type Lookup = IdentityLookup<AccountId>;150    /// The index type for storing how many extrinsics an account has signed.151    type Index = Index;152    /// The index type for blocks.153    type BlockNumber = BlockNumber;154    /// The type for hashing blocks and tries.155    type Hash = Hash;156    /// The hashing algorithm used.157    type Hashing = BlakeTwo256;158    /// The header type.159    type Header = generic::Header<BlockNumber, BlakeTwo256>;160    /// The ubiquitous event type.161    type Event = Event;162    /// The ubiquitous origin type.163    type Origin = Origin;164    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).165    type BlockHashCount = BlockHashCount;166    /// Maximum weight of each block.167    type MaximumBlockWeight = MaximumBlockWeight;168    /// The weight of database operations that the runtime can invoke.169    type DbWeight = RocksDbWeight;170    /// The weight of the overhead invoked on the block import process, independent of the171    /// extrinsics included in that block.172    type BlockExecutionWeight = BlockExecutionWeight;173    /// The base weight of any extrinsic processed by the runtime, independent of the174    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)175    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;176    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,177    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on178    /// initialize cost).179    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;180    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.181    type MaximumBlockLength = MaximumBlockLength;182    /// Portion of the block weight that is available to all normal transactions.183    type AvailableBlockRatio = AvailableBlockRatio;184    /// Version of the runtime.185    type Version = Version;186    /// Converts a module to the index of the module in `construct_runtime!`.187    ///188    /// This type is being generated by `construct_runtime!`.189    type ModuleToIndex = ModuleToIndex;190    /// What to do if a new account is created.191    type OnNewAccount = ();192    /// What to do if an account is fully reaped from the system.193    type OnKilledAccount = ();194    /// The data to be stored in an account.195    type AccountData = balances::AccountData<Balance>;196}197198impl aura::Trait for Runtime {199    type AuthorityId = AuraId;200}201202impl grandpa::Trait for Runtime {203    type Event = Event;204    type Call = Call;205206    type KeyOwnerProofSystem = ();207208    type KeyOwnerProof =209        <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;210211    type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(212        KeyTypeId,213        GrandpaId,214    )>>::IdentificationTuple;215216    type HandleEquivocation = ();217}218219parameter_types! {220    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;221}222223impl timestamp::Trait for Runtime {224    /// A timestamp: milliseconds since the unix epoch.225    type Moment = u64;226    type OnTimestampSet = Aura;227    type MinimumPeriod = MinimumPeriod;228}229230parameter_types! {231    pub const ExistentialDeposit: u128 = 500;232}233234impl balances::Trait for Runtime {235    /// The type for recording an account's balance.236    type Balance = Balance;237    /// The ubiquitous event type.238    type Event = Event;239    type DustRemoval = ();240    type ExistentialDeposit = ExistentialDeposit;241    type AccountStore = System;242}243244pub const MILLICENTS: Balance = 1_000_000_000;245pub const CENTS: Balance = 1_000 * MILLICENTS;246pub const DOLLARS: Balance = 100 * CENTS;247248parameter_types! {249    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;250    pub const RentByteFee: Balance = 4 * MILLICENTS;251    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;252    pub const SurchargeReward: Balance = 150 * MILLICENTS;253}254255impl contracts::Trait for Runtime {256    type Call = Call;257    type Time = Timestamp;258    type Randomness = RandomnessCollectiveFlip;259    type Currency = Balances;260    type Event = Event;261    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;262    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;263    type RentPayment = ();264    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;265    type TombstoneDeposit = TombstoneDeposit;266    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;267    type RentByteFee = RentByteFee;268    type RentDepositOffset = RentDepositOffset;269    type SurchargeReward = SurchargeReward;270    type MaxDepth = contracts::DefaultMaxDepth;271    type MaxValueSize = contracts::DefaultMaxValueSize;272    type WeightPrice = transaction_payment::Module<Self>;273}274275parameter_types! {276    pub const TransactionByteFee: Balance = 1;277}278279impl transaction_payment::Trait for Runtime {280    type Currency = balances::Module<Runtime>;281    type OnTransactionPayment = ();282    type TransactionByteFee = TransactionByteFee;283    type WeightToFee = IdentityFee<Balance>;284    type FeeMultiplierUpdate = ();285}286287impl sudo::Trait for Runtime {288    type Event = Event;289    type Call = Call;290}291292/// Used for the module nft in `./nft.rs`293impl nft::Trait for Runtime {294    type Event = Event;295}296297construct_runtime!(298    pub enum Runtime where299        Block = Block,300        NodeBlock = opaque::Block,301        UncheckedExtrinsic = UncheckedExtrinsic302    {303        System: system::{Module, Call, Config, Storage, Event<T>},304        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},305        Contracts: contracts::{Module, Call, Config, Storage, Event<T>},306        Timestamp: timestamp::{Module, Call, Storage, Inherent},307        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},308        Grandpa: grandpa::{Module, Call, Storage, Config, Event},309        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},310        TransactionPayment: transaction_payment::{Module, Storage},311        Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},312        Nft: nft::{Module, Call, Storage, Event<T>},313    }314);315316/// The address format for describing accounts.317pub type Address = AccountId;318/// Block header type as expected by this runtime.319pub type Header = generic::Header<BlockNumber, BlakeTwo256>;320/// Block type as expected by this runtime.321pub type Block = generic::Block<Header, UncheckedExtrinsic>;322/// A Block signed with a Justification323pub type SignedBlock = generic::SignedBlock<Block>;324/// BlockId type as expected by this runtime.325pub type BlockId = generic::BlockId<Block>;326/// The SignedExtension to the basic transaction logic.327pub type SignedExtra = (328    system::CheckSpecVersion<Runtime>,329    system::CheckTxVersion<Runtime>,330    system::CheckGenesis<Runtime>,331    system::CheckEra<Runtime>,332    system::CheckNonce<Runtime>,333    system::CheckWeight<Runtime>,334    transaction_payment::ChargeTransactionPayment<Runtime>,335);336/// Unchecked extrinsic type as expected by this runtime.337pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;338/// Extrinsic type that has already been checked.339pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;340/// Executive: handles dispatch to the various modules.341pub type Executive =342    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;343344impl_runtime_apis! {345346    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>347    for Runtime348    {349        fn call(350            origin: AccountId,351            dest: AccountId,352            value: Balance,353            gas_limit: u64,354            input_data: Vec<u8>,355        ) -> ContractExecResult {356            let exec_result =357                Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);358            match exec_result {359                Ok(v) => ContractExecResult::Success {360                    status: v.status,361                    data: v.data,362                },363                Err(_) => ContractExecResult::Error,364            }365        }366367        fn get_storage(368            address: AccountId,369            key: [u8; 32],370        ) -> contracts_primitives::GetStorageResult {371            Contracts::get_storage(address, key)372        }373374        fn rent_projection(375            address: AccountId,376        ) -> contracts_primitives::RentProjectionResult<BlockNumber> {377            Contracts::rent_projection(address)378        }379    }380381    impl sp_api::Core<Block> for Runtime {382        fn version() -> RuntimeVersion {383            VERSION384        }385386        fn execute_block(block: Block) {387            Executive::execute_block(block)388        }389390        fn initialize_block(header: &<Block as BlockT>::Header) {391            Executive::initialize_block(header)392        }393    }394395    impl sp_api::Metadata<Block> for Runtime {396        fn metadata() -> OpaqueMetadata {397            Runtime::metadata().into()398        }399    }400401    impl sp_block_builder::BlockBuilder<Block> for Runtime {402        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {403            Executive::apply_extrinsic(extrinsic)404        }405406        fn finalize_block() -> <Block as BlockT>::Header {407            Executive::finalize_block()408        }409410        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {411            data.create_extrinsics()412        }413414        fn check_inherents(415            block: Block,416            data: sp_inherents::InherentData,417        ) -> sp_inherents::CheckInherentsResult {418            data.check_extrinsics(&block)419        }420421        fn random_seed() -> <Block as BlockT>::Hash {422            RandomnessCollectiveFlip::random_seed()423        }424    }425426    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {427        fn validate_transaction(428            source: TransactionSource,429            tx: <Block as BlockT>::Extrinsic,430        ) -> TransactionValidity {431            Executive::validate_transaction(source, tx)432        }433    }434435    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {436        fn offchain_worker(header: &<Block as BlockT>::Header) {437            Executive::offchain_worker(header)438        }439    }440441    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {442        fn slot_duration() -> u64 {443            Aura::slot_duration()444        }445446        fn authorities() -> Vec<AuraId> {447            Aura::authorities()448        }449    }450451    impl sp_session::SessionKeys<Block> for Runtime {452        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {453            opaque::SessionKeys::generate(seed)454        }455456        fn decode_session_keys(457            encoded: Vec<u8>,458        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {459            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)460        }461    }462463    impl fg_primitives::GrandpaApi<Block> for Runtime {464        fn grandpa_authorities() -> GrandpaAuthorityList {465            Grandpa::grandpa_authorities()466        }467468        fn submit_report_equivocation_extrinsic(469            _equivocation_proof: fg_primitives::EquivocationProof<470                <Block as BlockT>::Hash,471                NumberFor<Block>,472            >,473            _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,474        ) -> Option<()> {475            None476        }477478        fn generate_key_ownership_proof(479            _set_id: fg_primitives::SetId,480            _authority_id: GrandpaId,481        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {482            // NOTE: this is the only implementation possible since we've483            // defined our key owner proof type as a bottom type (i.e. a type484            // with no values).485            None486        }487    }488}
after · runtime/src/lib.rs
1//! The Substrate Node Template runtime. This can be compiled with `#[no_std]`, ready for Wasm.23#![cfg_attr(not(feature = "std"), no_std)]4// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.5#![recursion_limit = "256"]67// Make the WASM binary available.8#[cfg(feature = "std")]9include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));1011use contracts_rpc_runtime_api::ContractExecResult;12use grandpa::fg_primitives;13use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::{18    create_runtime_str, generic, impl_opaque_keys,19    transaction_validity::{TransactionSource, TransactionValidity},20    ApplyExtrinsicResult, MultiSignature,21	traits::{22        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,23	},24};25use sp_std::prelude::*;26#[cfg(feature = "std")]27use sp_version::NativeVersion;28use sp_version::RuntimeVersion;2930// A few exports that help ease life for downstream crates.31pub use balances::Call as BalancesCall;32pub use contracts::Schedule as ContractsSchedule;33pub use frame_support::{34    construct_runtime, parameter_types,35    traits::{Currency, Get, ExistenceRequirement, KeyOwnerProofSystem, OnUnbalanced, Randomness, WithdrawReason},36    weights::{37        DispatchInfo, PostDispatchInfo, constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},38        IdentityFee, Weight, WeightToFeePolynomial, GetDispatchInfo, Pays,39    },40    StorageValue,41	dispatch::DispatchResult,42};43use system::{self as system};44#[cfg(any(feature = "std", test))]45pub use sp_runtime::BuildStorage;46use sp_runtime::{47	Perbill,48};495051pub use timestamp::Call as TimestampCall;5253/// Importing a nft pallet54pub use nft;5556/// An index to a block.57pub type BlockNumber = u32;5859/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.60pub type Signature = MultiSignature;6162/// Some way of identifying an account on the chain. We intentionally make it equivalent63/// to the public key of our transaction signing scheme.64pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;6566/// The type for looking up accounts. We don't expect more than 4 billion of them, but you67/// never know...68pub type AccountIndex = u32;6970/// Balance of an account.71pub type Balance = u128;7273/// Index of a transaction in the chain.74pub type Index = u32;7576/// A hash of some data used by the chain.77pub type Hash = sp_core::H256;7879/// Digest item type.80pub type DigestItem = generic::DigestItem<Hash>;8182/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know83/// the specifics of the runtime. They can then be made to be agnostic over specific formats84/// of data like extrinsics, allowing for them to continue syncing the network through upgrades85/// to even the core data structures.86pub mod opaque {87    use super::*;8889    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9091    /// Opaque block header type.92    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;93    /// Opaque block type.94    pub type Block = generic::Block<Header, UncheckedExtrinsic>;95    /// Opaque block identifier type.96    pub type BlockId = generic::BlockId<Block>;9798    impl_opaque_keys! {99        pub struct SessionKeys {100            pub aura: Aura,101            pub grandpa: Grandpa,102        }103    }104}105106/// This runtime version.107pub const VERSION: RuntimeVersion = RuntimeVersion {108    spec_name: create_runtime_str!("nft"),109    impl_name: create_runtime_str!("nft"),110    authoring_version: 1,111    spec_version: 1,112    impl_version: 1,113    apis: RUNTIME_API_VERSIONS,114    transaction_version: 1,115};116117pub const MILLISECS_PER_BLOCK: u64 = 6000;118119pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;120121// These time units are defined in number of blocks.122pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);123pub const HOURS: BlockNumber = MINUTES * 60;124pub const DAYS: BlockNumber = HOURS * 24;125126/// The version information used to identify this runtime when compiled natively.127#[cfg(feature = "std")]128pub fn native_version() -> NativeVersion {129    NativeVersion {130        runtime_version: VERSION,131        can_author_with: Default::default(),132    }133}134135parameter_types! {136    pub const BlockHashCount: BlockNumber = 2400;137    /// We allow for 2 seconds of compute with a 6 second average block time.138    pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;139    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);140    /// Assume 10% of weight for average on_initialize calls.141    pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()142        .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();143    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;144    pub const Version: RuntimeVersion = VERSION;145}146147impl system::Trait for Runtime {148    /// The basic call filter to use in dispatchable.149    type BaseCallFilter = ();150    /// The identifier used to distinguish between accounts.151    type AccountId = AccountId;152    /// The aggregated dispatch type that is available for extrinsics.153    type Call = Call;154    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.155    type Lookup = IdentityLookup<AccountId>;156    /// The index type for storing how many extrinsics an account has signed.157    type Index = Index;158    /// The index type for blocks.159    type BlockNumber = BlockNumber;160    /// The type for hashing blocks and tries.161    type Hash = Hash;162    /// The hashing algorithm used.163    type Hashing = BlakeTwo256;164    /// The header type.165    type Header = generic::Header<BlockNumber, BlakeTwo256>;166    /// The ubiquitous event type.167    type Event = Event;168    /// The ubiquitous origin type.169    type Origin = Origin;170    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).171    type BlockHashCount = BlockHashCount;172    /// Maximum weight of each block.173    type MaximumBlockWeight = MaximumBlockWeight;174    /// The weight of database operations that the runtime can invoke.175    type DbWeight = RocksDbWeight;176    /// The weight of the overhead invoked on the block import process, independent of the177    /// extrinsics included in that block.178    type BlockExecutionWeight = BlockExecutionWeight;179    /// The base weight of any extrinsic processed by the runtime, independent of the180    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)181    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;182    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,183    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on184    /// initialize cost).185    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;186    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.187    type MaximumBlockLength = MaximumBlockLength;188    /// Portion of the block weight that is available to all normal transactions.189    type AvailableBlockRatio = AvailableBlockRatio;190    /// Version of the runtime.191    type Version = Version;192    /// Converts a module to the index of the module in `construct_runtime!`.193    ///194    /// This type is being generated by `construct_runtime!`.195    type ModuleToIndex = ModuleToIndex;196    /// What to do if a new account is created.197    type OnNewAccount = ();198    /// What to do if an account is fully reaped from the system.199    type OnKilledAccount = ();200    /// The data to be stored in an account.201    type AccountData = balances::AccountData<Balance>;202}203204impl aura::Trait for Runtime {205    type AuthorityId = AuraId;206}207208impl grandpa::Trait for Runtime {209    type Event = Event;210    type Call = Call;211212    type KeyOwnerProofSystem = ();213214    type KeyOwnerProof =215        <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;216217    type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(218        KeyTypeId,219        GrandpaId,220    )>>::IdentificationTuple;221222    type HandleEquivocation = ();223}224225parameter_types! {226    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;227}228229impl timestamp::Trait for Runtime {230    /// A timestamp: milliseconds since the unix epoch.231    type Moment = u64;232    type OnTimestampSet = Aura;233    type MinimumPeriod = MinimumPeriod;234}235236parameter_types! {237    // pub const ExistentialDeposit: u128 = 500;238    pub const ExistentialDeposit: u128 = 0;239}240241impl balances::Trait for Runtime {242    /// The type for recording an account's balance.243    type Balance = Balance;244    /// The ubiquitous event type.245    type Event = Event;246    type DustRemoval = ();247    type ExistentialDeposit = ExistentialDeposit;248    type AccountStore = System;249}250251pub const MILLICENTS: Balance = 1_000_000_000;252pub const CENTS: Balance = 1_000 * MILLICENTS;253pub const DOLLARS: Balance = 100 * CENTS;254255parameter_types! {256    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;257    pub const RentByteFee: Balance = 4 * MILLICENTS;258    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;259    pub const SurchargeReward: Balance = 150 * MILLICENTS;260}261262impl contracts::Trait for Runtime {263    type Call = Call;264    type Time = Timestamp;265    type Randomness = RandomnessCollectiveFlip;266    type Currency = Balances;267    type Event = Event;268    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;269    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;270    type RentPayment = ();271    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;272    type TombstoneDeposit = TombstoneDeposit;273    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;274    type RentByteFee = RentByteFee;275    type RentDepositOffset = RentDepositOffset;276    type SurchargeReward = SurchargeReward;277    type MaxDepth = contracts::DefaultMaxDepth;278    type MaxValueSize = contracts::DefaultMaxValueSize;279    type WeightPrice = transaction_payment::Module<Self>;280}281282parameter_types! {283    pub const TransactionByteFee: Balance = 1;284}285286impl transaction_payment::Trait for Runtime {287    type Currency = balances::Module<Runtime>;288    type OnTransactionPayment = ();289    type TransactionByteFee = TransactionByteFee;290    type WeightToFee = IdentityFee<Balance>;291    type FeeMultiplierUpdate = ();292}293294impl sudo::Trait for Runtime {295    type Event = Event;296    type Call = Call;297}298299/// Used for the module nft in `./nft.rs`300impl nft::Trait for Runtime {301    type Event = Event;302}303304construct_runtime!(305    pub enum Runtime where306        Block = Block,307        NodeBlock = opaque::Block,308        UncheckedExtrinsic = UncheckedExtrinsic309    {310        System: system::{Module, Call, Config, Storage, Event<T>},311        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},312        Contracts: contracts::{Module, Call, Config, Storage, Event<T>},313        Timestamp: timestamp::{Module, Call, Storage, Inherent},314        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},315        Grandpa: grandpa::{Module, Call, Storage, Config, Event},316        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},317        TransactionPayment: transaction_payment::{Module, Storage},318        Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},319        Nft: nft::{Module, Call, Storage, Event<T>},320    }321);322323/// The address format for describing accounts.324pub type Address = AccountId;325/// Block header type as expected by this runtime.326pub type Header = generic::Header<BlockNumber, BlakeTwo256>;327/// Block type as expected by this runtime.328pub type Block = generic::Block<Header, UncheckedExtrinsic>;329/// A Block signed with a Justification330pub type SignedBlock = generic::SignedBlock<Block>;331/// BlockId type as expected by this runtime.332pub type BlockId = generic::BlockId<Block>;333/// The SignedExtension to the basic transaction logic.334pub type SignedExtra = (335    system::CheckSpecVersion<Runtime>,336    system::CheckTxVersion<Runtime>,337    system::CheckGenesis<Runtime>,338    system::CheckEra<Runtime>,339    system::CheckNonce<Runtime>,340    system::CheckWeight<Runtime>,341    nft::ChargeTransactionPayment<Runtime>,342);343/// Unchecked extrinsic type as expected by this runtime.344pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;345/// Extrinsic type that has already been checked.346pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;347/// Executive: handles dispatch to the various modules.348pub type Executive =349    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;350351impl_runtime_apis! {352353    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>354    for Runtime355    {356        fn call(357            origin: AccountId,358            dest: AccountId,359            value: Balance,360            gas_limit: u64,361            input_data: Vec<u8>,362        ) -> ContractExecResult {363            let exec_result =364                Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);365            match exec_result {366                Ok(v) => ContractExecResult::Success {367                    status: v.status,368                    data: v.data,369                },370                Err(_) => ContractExecResult::Error,371            }372        }373374        fn get_storage(375            address: AccountId,376            key: [u8; 32],377        ) -> contracts_primitives::GetStorageResult {378            Contracts::get_storage(address, key)379        }380381        fn rent_projection(382            address: AccountId,383        ) -> contracts_primitives::RentProjectionResult<BlockNumber> {384            Contracts::rent_projection(address)385        }386    }387388    impl sp_api::Core<Block> for Runtime {389        fn version() -> RuntimeVersion {390            VERSION391        }392393        fn execute_block(block: Block) {394            Executive::execute_block(block)395        }396397        fn initialize_block(header: &<Block as BlockT>::Header) {398            Executive::initialize_block(header)399        }400    }401402    impl sp_api::Metadata<Block> for Runtime {403        fn metadata() -> OpaqueMetadata {404            Runtime::metadata().into()405        }406    }407408    impl sp_block_builder::BlockBuilder<Block> for Runtime {409        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {410            Executive::apply_extrinsic(extrinsic)411        }412413        fn finalize_block() -> <Block as BlockT>::Header {414            Executive::finalize_block()415        }416417        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {418            data.create_extrinsics()419        }420421        fn check_inherents(422            block: Block,423            data: sp_inherents::InherentData,424        ) -> sp_inherents::CheckInherentsResult {425            data.check_extrinsics(&block)426        }427428        fn random_seed() -> <Block as BlockT>::Hash {429            RandomnessCollectiveFlip::random_seed()430        }431    }432433    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {434        fn validate_transaction(435            source: TransactionSource,436            tx: <Block as BlockT>::Extrinsic,437        ) -> TransactionValidity {438            Executive::validate_transaction(source, tx)439        }440    }441442    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {443        fn offchain_worker(header: &<Block as BlockT>::Header) {444            Executive::offchain_worker(header)445        }446    }447448    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {449        fn slot_duration() -> u64 {450            Aura::slot_duration()451        }452453        fn authorities() -> Vec<AuraId> {454            Aura::authorities()455        }456    }457458    impl sp_session::SessionKeys<Block> for Runtime {459        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {460            opaque::SessionKeys::generate(seed)461        }462463        fn decode_session_keys(464            encoded: Vec<u8>,465        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {466            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)467        }468    }469470    impl fg_primitives::GrandpaApi<Block> for Runtime {471        fn grandpa_authorities() -> GrandpaAuthorityList {472            Grandpa::grandpa_authorities()473        }474475        fn submit_report_equivocation_extrinsic(476            _equivocation_proof: fg_primitives::EquivocationProof<477                <Block as BlockT>::Hash,478                NumberFor<Block>,479            >,480            _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,481        ) -> Option<()> {482            None483        }484485        fn generate_key_ownership_proof(486            _set_id: fg_primitives::SetId,487            _authority_id: GrandpaId,488        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {489            // NOTE: this is the only implementation possible since we've490            // defined our key owner proof type as a bottom type (i.e. a type491            // with no values).492            None493        }494    }495}496