git.delta.rocks / unique-network / refs/commits / 31c3cec78d0b

difftreelog

Contract sponsoring in progress as is

Greg Zaitsev2020-11-05parent: #3f1f974.patch.diff
in: master

4 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3737,6 +3737,7 @@
  "frame-support",
  "frame-system",
  "log",
+ "pallet-contracts",
  "pallet-transaction-payment",
  "parity-scale-codec",
  "serde",
modifiedpallets/nft/Cargo.tomldiffbeforeafterboth
--- a/pallets/nft/Cargo.toml
+++ b/pallets/nft/Cargo.toml
@@ -73,6 +73,13 @@
 branch = 'v2.0.0_release'
 optional = true
 
+[dependencies.pallet-contracts]
+default-features = false
+git = 'https://github.com/usetech-llc/substrate.git'
+package = 'pallet-contracts'
+branch = 'v2.0.0_release'
+version = '2.0.0'
+
 [features]
 default = ['std']
 std = [
modifiedpallets/nft/src/lib.rsdiffbeforeafterboth
--- a/pallets/nft/src/lib.rs
+++ b/pallets/nft/src/lib.rs
@@ -11,6 +11,7 @@
     construct_runtime, decl_event, decl_module, decl_storage,
     dispatch::DispatchResult,
     ensure, parameter_types,
+    debug,
     traits::{
         Currency, ExistenceRequirement, Get, Imbalance, KeyOwnerProofSystem, OnUnbalanced,
         Randomness, WithdrawReason,
@@ -22,6 +23,7 @@
     },
     IsSubType, StorageValue,
 };
+use sp_runtime::print;
 // use frame_support::weights::{Weight, constants::RocksDbWeight as DbWeight};
 
 use frame_system::{self as system, ensure_signed, ensure_root};
@@ -205,7 +207,7 @@
     fn set_offchain_schema() -> Weight;
 }
 
-pub trait Trait: system::Trait + Sized  {
+pub trait Trait: system::Trait + Sized + transaction_payment::Trait + pallet_contracts::Trait {
     type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
 
     /// Weight information for extrinsics in this pallet.
@@ -1737,11 +1739,11 @@
 /// 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>,
+pub struct ChargeTransactionPayment<T: Trait + Send + Sync>(
+    #[codec(compact)] BalanceOf<T>
 );
 
-impl<T: Trait + transaction_payment::Trait + Send + Sync> sp_std::fmt::Debug
+impl<T: Trait + Send + Sync> sp_std::fmt::Debug
     for ChargeTransactionPayment<T>
 {
     #[cfg(feature = "std")]
@@ -1754,10 +1756,9 @@
     }
 }
 
-impl<T: Trait + transaction_payment::Trait + Send + Sync> ChargeTransactionPayment<T>
+impl<T: Trait + Send + Sync> ChargeTransactionPayment<T>
 where
-    T::Call:
-        Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>>,
+    T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<Call<T>>,
     BalanceOf<T>: Send + Sync + FixedPointOperand,
 {
     /// utility constructor. Used only in client/factory code.
@@ -1787,11 +1788,12 @@
 
         // 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)
-        };
+        // 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)
+        // };
+        let fee = Self::traditional_fee(len, info, tip);
 
         // Determine who is paying transaction fee based on ecnomic model
         // Parse call to extract collection ID and access collection sponsor
@@ -1861,6 +1863,11 @@
                 }
             }
 
+            // Some(pallet_contracts::Call::call(_dest, _value, _gas_limit, _data)) => {
+            // Some(pallet_contracts::Call::call(..)) => {
+            //     T::AccountId::default()
+            // }
+
             _ => T::AccountId::default(),
         };
 
@@ -1890,7 +1897,8 @@
     }
 }
 
-impl<T: Trait + transaction_payment::Trait + Send + Sync> SignedExtension
+
+impl<T: Trait + Send + Sync> SignedExtension
     for ChargeTransactionPayment<T>
 where
     BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
@@ -1900,12 +1908,13 @@
     type AccountId = T::AccountId;
     type Call = T::Call;
     type AdditionalSigned = ();
-    type Pre = (
-        BalanceOf<T>,
-        Self::AccountId,
-        Option<NegativeImbalanceOf<T>>,
-        BalanceOf<T>,
-    );
+    type Pre = ();
+    // type Pre = (
+    //     BalanceOf<T>,
+    //     Self::AccountId,
+    //     Option<NegativeImbalanceOf<T>>,
+    //     BalanceOf<T>,
+    // );
     fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> {
         Ok(())
     }
@@ -1919,11 +1928,9 @@
     ) -> 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)
+        print("====== validate");
+
+        Ok(ValidTransaction::default())
     }
 
     fn pre_dispatch(
@@ -1933,8 +1940,15 @@
         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))
+
+        print("========= PreDispatch");
+
+        // let (fee, imbalance) = self.withdraw_fee(who, call, info, len)?;
+
+        // debug::info!("Fee: {:?}", fee);
+
+        // Ok((self.0, who.clone(), imbalance, fee))
+        Ok(())
     }
 
     fn post_dispatch(
@@ -1944,36 +1958,223 @@
         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)),
-            );
-        }
+        // 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(())
+    }
+}
+
+/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
+
+
+#[derive(Encode, Decode, Clone, Eq, PartialEq)]
+pub struct ChargeContractTransactionPayment<T: Trait + Send + Sync>(
+    #[codec(compact)] BalanceOf<T>
+);
+
+impl<T: Trait + Send + Sync> sp_std::fmt::Debug
+    for ChargeContractTransactionPayment<T>
+{
+    #[cfg(feature = "std")]
+    fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
+        write!(f, "ChargeContractTransactionPayment<{:?}>", self.0)
+    }
+    #[cfg(not(feature = "std"))]
+    fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result {
         Ok(())
     }
 }
+
+// impl<T: Trait + Send + Sync> ChargeContractTransactionPayment<T>
+// where
+//     // T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
+//     T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<pallet_contracts::Call<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;
+
+//         let mut fee = Self::traditional_fee(len, info, tip);
+
+//         // 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(pallet_contracts::Call::call(_dest, _value, _gas_limit, _data)) => {
+//         //     Some(pallet_contracts::Call::call(..)) => {
+//         //         // fee = <BalanceOf<T>>::from(0);
+//         //         T::AccountId::default()
+//         //     }
+//         //     _ => T::AccountId::default(),
+//         // };
+//         let 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 + Send + Sync> SignedExtension
+    for ChargeContractTransactionPayment<T>
+where
+    BalanceOf<T>: Send + Sync + From<u64> + FixedPointOperand,
+    // T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
+    T::Call: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo> + IsSubType<pallet_contracts::Call<T>>,
+{
+    const IDENTIFIER: &'static str = "ChargeContractTransactionPayment";
+    type AccountId = T::AccountId;
+    type Call = T::Call;
+    type AdditionalSigned = ();
+    type Pre = ();
+
+    // 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)?;
+
+        print("====== Contracts validate");
+
+        Ok(ValidTransaction::default())
+    }
+
+    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))
+
+        print("====== Contracts pre-dispatch");
+        // debug::info!("Fee: {:?}", fee);
+
+        Ok(())
+    }
+
+    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(())
+    }
+}
+
+
 // #endregion
 
 
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 pallet_contracts_rpc_runtime_api::ContractExecResult;12use pallet_grandpa::fg_primitives;13use pallet_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    traits::{20        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,21        Verify,22    },23    transaction_validity::{TransactionSource, TransactionValidity},24    ApplyExtrinsicResult, MultiSignature,25};26use sp_std::prelude::*;27#[cfg(feature = "std")]28use sp_version::NativeVersion;29use sp_version::RuntimeVersion;3031// A few exports that help ease life for downstream crates.32pub use pallet_balances::Call as BalancesCall;33pub use pallet_contracts::Schedule as ContractsSchedule;34pub use frame_support::{35    construct_runtime,36    dispatch::DispatchResult,37    parameter_types,38    traits::{39        Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,40        WithdrawReason,41    },42    weights::{43        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},44        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,45        WeightToFeePolynomial,46    },47    StorageValue,48};49#[cfg(any(feature = "std", test))]50pub use sp_runtime::BuildStorage;51use sp_runtime::Perbill;52use frame_system::{self as system};5354pub use pallet_timestamp::Call as TimestampCall;5556/// Re-export a nft pallet57/// TODO: Check this re-export. Is this safe and good style?58extern crate pallet_nft;59pub use pallet_nft::*;6061/// An index to a block.62pub type BlockNumber = u32;6364/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.65pub type Signature = MultiSignature;6667/// Some way of identifying an account on the chain. We intentionally make it equivalent68/// to the public key of our transaction signing scheme.69pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;7071/// The type for looking up accounts. We don't expect more than 4 billion of them, but you72/// never know...73pub type AccountIndex = u32;7475/// Balance of an account.76pub type Balance = u128;7778/// Index of a transaction in the chain.79pub type Index = u32;8081/// A hash of some data used by the chain.82pub type Hash = sp_core::H256;8384/// Digest item type.85pub type DigestItem = generic::DigestItem<Hash>;8687mod nft_weights;8889/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know90/// the specifics of the runtime. They can then be made to be agnostic over specific formats91/// of data like extrinsics, allowing for them to continue syncing the network through upgrades92/// to even the core data structures.93pub mod opaque {94    use super::*;9596    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9798    /// Opaque block header type.99    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;100    /// Opaque block type.101    pub type Block = generic::Block<Header, UncheckedExtrinsic>;102    /// Opaque block identifier type.103    pub type BlockId = generic::BlockId<Block>;104105    impl_opaque_keys! {106        pub struct SessionKeys {107            pub aura: Aura,108            pub grandpa: Grandpa,109        }110    }111}112113/// This runtime version.114pub const VERSION: RuntimeVersion = RuntimeVersion {115    spec_name: create_runtime_str!("nft"),116    impl_name: create_runtime_str!("nft"),117    authoring_version: 1,118    spec_version: 2,119    impl_version: 1,120    apis: RUNTIME_API_VERSIONS,121    transaction_version: 1,122};123124pub const MILLISECS_PER_BLOCK: u64 = 6000;125126pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;127128// These time units are defined in number of blocks.129pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);130pub const HOURS: BlockNumber = MINUTES * 60;131pub const DAYS: BlockNumber = HOURS * 24;132133/// The version information used to identify this runtime when compiled natively.134#[cfg(feature = "std")]135pub fn native_version() -> NativeVersion {136    NativeVersion {137        runtime_version: VERSION,138        can_author_with: Default::default(),139    }140}141142parameter_types! {143    pub const BlockHashCount: BlockNumber = 2400;144    /// We allow for 2 seconds of compute with a 6 second average block time.145    pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;146    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);147    /// Assume 10% of weight for average on_initialize calls.148    pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()149        .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();150    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;151    pub const Version: RuntimeVersion = VERSION;152}153154impl system::Trait for Runtime {155    /// The basic call filter to use in dispatchable.156    type BaseCallFilter = ();157    /// The identifier used to distinguish between accounts.158    type AccountId = AccountId;159    /// The aggregated dispatch type that is available for extrinsics.160    type Call = Call;161    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.162    type Lookup = IdentityLookup<AccountId>;163    /// The index type for storing how many extrinsics an account has signed.164    type Index = Index;165    /// The index type for blocks.166    type BlockNumber = BlockNumber;167    /// The type for hashing blocks and tries.168    type Hash = Hash;169    /// The hashing algorithm used.170    type Hashing = BlakeTwo256;171    /// The header type.172    type Header = generic::Header<BlockNumber, BlakeTwo256>;173    /// The ubiquitous event type.174    type Event = Event;175    /// The ubiquitous origin type.176    type Origin = Origin;177    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).178    type BlockHashCount = BlockHashCount;179    /// Maximum weight of each block.180    type MaximumBlockWeight = MaximumBlockWeight;181    /// The weight of database operations that the runtime can invoke.182    type DbWeight = RocksDbWeight;183    /// The weight of the overhead invoked on the block import process, independent of the184    /// extrinsics included in that block.185    type BlockExecutionWeight = BlockExecutionWeight;186    /// The base weight of any extrinsic processed by the runtime, independent of the187    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)188    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;189    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,190    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on191    /// initialize cost).192    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;193    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.194    type MaximumBlockLength = MaximumBlockLength;195    /// Portion of the block weight that is available to all normal transactions.196    type AvailableBlockRatio = AvailableBlockRatio;197    /// Version of the runtime.198    type Version = Version;199 	/// This type is being generated by `construct_runtime!`.200    type PalletInfo = PalletInfo;201    /// What to do if a new account is created.202    type OnNewAccount = ();203    /// What to do if an account is fully reaped from the system.204    type OnKilledAccount = ();205    /// The data to be stored in an account.206    type AccountData = pallet_balances::AccountData<Balance>;207	/// Weight information for the extrinsics of this pallet.208	type SystemWeightInfo = ();209}210211impl pallet_aura::Trait for Runtime {212    type AuthorityId = AuraId;213}214215impl pallet_grandpa::Trait for Runtime {216	type Event = Event;217	type Call = Call;218219	type KeyOwnerProofSystem = ();220221	type KeyOwnerProof =222		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;223224	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(225		KeyTypeId,226		GrandpaId,227	)>>::IdentificationTuple;228229	type HandleEquivocation = ();230231	type WeightInfo = ();232}233234parameter_types! {235    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;236}237238impl pallet_timestamp::Trait for Runtime {239	/// A timestamp: milliseconds since the unix epoch.240	type Moment = u64;241	type OnTimestampSet = Aura;242	type MinimumPeriod = MinimumPeriod;243	type WeightInfo = ();244}245246parameter_types! {247    // pub const ExistentialDeposit: u128 = 500;248    pub const ExistentialDeposit: u128 = 0;249	pub const MaxLocks: u32 = 50;250}251252impl pallet_balances::Trait for Runtime {253	type MaxLocks = MaxLocks;254	/// The type for recording an account's balance.255	type Balance = Balance;256	/// The ubiquitous event type.257	type Event = Event;258	type DustRemoval = ();259	type ExistentialDeposit = ExistentialDeposit;260	type AccountStore = System;261	type WeightInfo = ();262}263264pub const MILLICENTS: Balance = 1_000_000_000;265pub const CENTS: Balance = 1_000 * MILLICENTS;266pub const DOLLARS: Balance = 100 * CENTS;267268parameter_types! {269    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;270    pub const RentByteFee: Balance = 4 * MILLICENTS;271    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;272    pub const SurchargeReward: Balance = 150 * MILLICENTS;273}274275impl pallet_contracts::Trait for Runtime {276	type Time = Timestamp;277	type Randomness = RandomnessCollectiveFlip;278	type Currency = Balances;279	type Event = Event;280	type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminer<Runtime>;281	type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter<Runtime>;282	type RentPayment = ();283	type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap;284	type TombstoneDeposit = TombstoneDeposit;285	type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset;286	type RentByteFee = RentByteFee;287	type RentDepositOffset = RentDepositOffset;288	type SurchargeReward = SurchargeReward;289	type MaxDepth = pallet_contracts::DefaultMaxDepth;290	type MaxValueSize = pallet_contracts::DefaultMaxValueSize;291	type WeightPrice = pallet_transaction_payment::Module<Self>;292}293294parameter_types! {295	pub const TransactionByteFee: Balance = 10 * MILLICENTS;296}297298impl pallet_transaction_payment::Trait for Runtime {299    type Currency = pallet_balances::Module<Runtime>;300    type OnTransactionPayment = ();301    type TransactionByteFee = TransactionByteFee;302    type WeightToFee = IdentityFee<Balance>;303    type FeeMultiplierUpdate =  ();304}305306impl pallet_sudo::Trait for Runtime {307    type Event = Event;308    type Call = Call;309}310311/// Used for the module nft in `./nft.rs`312impl pallet_nft::Trait for Runtime {313    type Event = Event;314    type WeightInfo = nft_weights::WeightInfo;315}316317construct_runtime!(318    pub enum Runtime where319        Block = Block,320        NodeBlock = opaque::Block,321        UncheckedExtrinsic = UncheckedExtrinsic322    {323        System: system::{Module, Call, Config, Storage, Event<T>},324        RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},325        Contracts: pallet_contracts::{Module, Call, Config, Storage, Event<T>},326        Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},327        Aura: pallet_aura::{Module, Config<T>, Inherent},328        Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},329        Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},330        TransactionPayment: pallet_transaction_payment::{Module, Storage},331        Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},332        Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},333    }334);335336/// The address format for describing accounts.337pub type Address = AccountId;338/// Block header type as expected by this runtime.339pub type Header = generic::Header<BlockNumber, BlakeTwo256>;340/// Block type as expected by this runtime.341pub type Block = generic::Block<Header, UncheckedExtrinsic>;342/// A Block signed with a Justification343pub type SignedBlock = generic::SignedBlock<Block>;344/// BlockId type as expected by this runtime.345pub type BlockId = generic::BlockId<Block>;346/// The SignedExtension to the basic transaction logic.347pub type SignedExtra = (348    system::CheckSpecVersion<Runtime>,349    system::CheckTxVersion<Runtime>,350    system::CheckGenesis<Runtime>,351    system::CheckEra<Runtime>,352    system::CheckNonce<Runtime>,353    system::CheckWeight<Runtime>,354    pallet_nft::ChargeTransactionPayment<Runtime>,355);356/// Unchecked extrinsic type as expected by this runtime.357pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;358/// Extrinsic type that has already been checked.359pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;360/// Executive: handles dispatch to the various modules.361pub type Executive =362    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;363364impl_runtime_apis! {365366    impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>367    for Runtime368    {369        fn call(370            origin: AccountId,371            dest: AccountId,372            value: Balance,373            gas_limit: u64,374            input_data: Vec<u8>,375        ) -> ContractExecResult {376			let (exec_result, gas_consumed) =377				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);378			match exec_result {379				Ok(v) => ContractExecResult::Success {380					flags: v.flags.bits(),381					data: v.data,382					gas_consumed: gas_consumed,383				},384				Err(_) => ContractExecResult::Error,385			}386        }387388        fn get_storage(389            address: AccountId,390            key: [u8; 32],391        ) -> pallet_contracts_primitives::GetStorageResult {392            Contracts::get_storage(address, key)393        }394395        fn rent_projection(396            address: AccountId,397        ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {398            Contracts::rent_projection(address)399        }400    }401402    impl sp_api::Core<Block> for Runtime {403        fn version() -> RuntimeVersion {404            VERSION405        }406407        fn execute_block(block: Block) {408            Executive::execute_block(block)409        }410411        fn initialize_block(header: &<Block as BlockT>::Header) {412            Executive::initialize_block(header)413        }414    }415416    impl sp_api::Metadata<Block> for Runtime {417        fn metadata() -> OpaqueMetadata {418            Runtime::metadata().into()419        }420    }421422    impl sp_block_builder::BlockBuilder<Block> for Runtime {423        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {424            Executive::apply_extrinsic(extrinsic)425        }426427        fn finalize_block() -> <Block as BlockT>::Header {428            Executive::finalize_block()429        }430431        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {432            data.create_extrinsics()433        }434435        fn check_inherents(436            block: Block,437            data: sp_inherents::InherentData,438        ) -> sp_inherents::CheckInherentsResult {439            data.check_extrinsics(&block)440        }441442        fn random_seed() -> <Block as BlockT>::Hash {443            RandomnessCollectiveFlip::random_seed()444        }445    }446447    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {448        fn validate_transaction(449            source: TransactionSource,450            tx: <Block as BlockT>::Extrinsic,451        ) -> TransactionValidity {452            Executive::validate_transaction(source, tx)453        }454    }455456    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {457        fn offchain_worker(header: &<Block as BlockT>::Header) {458            Executive::offchain_worker(header)459        }460    }461462    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {463        fn slot_duration() -> u64 {464            Aura::slot_duration()465        }466467        fn authorities() -> Vec<AuraId> {468            Aura::authorities()469        }470    }471472    impl sp_session::SessionKeys<Block> for Runtime {473        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {474            opaque::SessionKeys::generate(seed)475        }476477        fn decode_session_keys(478            encoded: Vec<u8>,479        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {480            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)481        }482    }483484	impl fg_primitives::GrandpaApi<Block> for Runtime {485		fn grandpa_authorities() -> GrandpaAuthorityList {486			Grandpa::grandpa_authorities()487		}488489		fn submit_report_equivocation_unsigned_extrinsic(490			_equivocation_proof: fg_primitives::EquivocationProof<491				<Block as BlockT>::Hash,492				NumberFor<Block>,493			>,494			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,495		) -> Option<()> {496			None497		}498499		fn generate_key_ownership_proof(500			_set_id: fg_primitives::SetId,501			_authority_id: GrandpaId,502		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {503			// NOTE: this is the only implementation possible since we've504			// defined our key owner proof type as a bottom type (i.e. a type505			// with no values).506			None507		}508    }509    510	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {511		fn account_nonce(account: AccountId) -> Index {512			System::account_nonce(account)513		}514	}515516	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {517		fn query_info(518			uxt: <Block as BlockT>::Extrinsic,519			len: u32,520		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {521			TransactionPayment::query_info(uxt, len)522		}523	}524525    #[cfg(feature = "runtime-benchmarks")]526	impl frame_benchmarking::Benchmark<Block> for Runtime {527		fn dispatch_benchmark(528			config: frame_benchmarking::BenchmarkConfig529		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {530			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};531532			let whitelist: Vec<TrackedStorageKey> = vec![533				// Alice account534				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),535				// // Total Issuance536				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),537				// // Execution Phase538				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),539				// // Event Count540				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),541				// // System Events542				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),543            ];544545			let mut batches = Vec::<BenchmarkBatch>::new();546			let params = (&config, &whitelist);547548			add_benchmark!(params, batches, pallet_nft, Nft);549550			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }551			Ok(batches)552		}553	}554}
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 pallet_contracts_rpc_runtime_api::ContractExecResult;12use pallet_grandpa::fg_primitives;13use pallet_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    traits::{20        BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating,21        Verify,22    },23    transaction_validity::{TransactionSource, TransactionValidity},24    ApplyExtrinsicResult, MultiSignature,25};26use sp_std::prelude::*;27#[cfg(feature = "std")]28use sp_version::NativeVersion;29use sp_version::RuntimeVersion;3031// A few exports that help ease life for downstream crates.32pub use pallet_balances::Call as BalancesCall;33pub use pallet_contracts::Schedule as ContractsSchedule;34pub use frame_support::{35    construct_runtime,36    dispatch::DispatchResult,37    parameter_types,38    traits::{39        Currency, ExistenceRequirement, Get, KeyOwnerProofSystem, OnUnbalanced, Randomness,40        WithdrawReason,41    },42    weights::{43        constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},44        DispatchInfo, GetDispatchInfo, IdentityFee, Pays, PostDispatchInfo, Weight,45        WeightToFeePolynomial,46    },47    StorageValue,48};49#[cfg(any(feature = "std", test))]50pub use sp_runtime::BuildStorage;51use sp_runtime::Perbill;52use frame_system::{self as system};5354pub use pallet_timestamp::Call as TimestampCall;5556/// Re-export a nft pallet57/// TODO: Check this re-export. Is this safe and good style?58extern crate pallet_nft;59pub use pallet_nft::*;6061/// An index to a block.62pub type BlockNumber = u32;6364/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.65pub type Signature = MultiSignature;6667/// Some way of identifying an account on the chain. We intentionally make it equivalent68/// to the public key of our transaction signing scheme.69pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;7071/// The type for looking up accounts. We don't expect more than 4 billion of them, but you72/// never know...73pub type AccountIndex = u32;7475/// Balance of an account.76pub type Balance = u128;7778/// Index of a transaction in the chain.79pub type Index = u32;8081/// A hash of some data used by the chain.82pub type Hash = sp_core::H256;8384/// Digest item type.85pub type DigestItem = generic::DigestItem<Hash>;8687mod nft_weights;8889/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know90/// the specifics of the runtime. They can then be made to be agnostic over specific formats91/// of data like extrinsics, allowing for them to continue syncing the network through upgrades92/// to even the core data structures.93pub mod opaque {94    use super::*;9596    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9798    /// Opaque block header type.99    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;100    /// Opaque block type.101    pub type Block = generic::Block<Header, UncheckedExtrinsic>;102    /// Opaque block identifier type.103    pub type BlockId = generic::BlockId<Block>;104105    impl_opaque_keys! {106        pub struct SessionKeys {107            pub aura: Aura,108            pub grandpa: Grandpa,109        }110    }111}112113/// This runtime version.114pub const VERSION: RuntimeVersion = RuntimeVersion {115    spec_name: create_runtime_str!("nft"),116    impl_name: create_runtime_str!("nft"),117    authoring_version: 1,118    spec_version: 2,119    impl_version: 1,120    apis: RUNTIME_API_VERSIONS,121    transaction_version: 1,122};123124pub const MILLISECS_PER_BLOCK: u64 = 6000;125126pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;127128// These time units are defined in number of blocks.129pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);130pub const HOURS: BlockNumber = MINUTES * 60;131pub const DAYS: BlockNumber = HOURS * 24;132133/// The version information used to identify this runtime when compiled natively.134#[cfg(feature = "std")]135pub fn native_version() -> NativeVersion {136    NativeVersion {137        runtime_version: VERSION,138        can_author_with: Default::default(),139    }140}141142parameter_types! {143    pub const BlockHashCount: BlockNumber = 2400;144    /// We allow for 2 seconds of compute with a 6 second average block time.145    pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;146    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);147    /// Assume 10% of weight for average on_initialize calls.148    pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()149        .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();150    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;151    pub const Version: RuntimeVersion = VERSION;152}153154impl system::Trait for Runtime {155    /// The basic call filter to use in dispatchable.156    type BaseCallFilter = ();157    /// The identifier used to distinguish between accounts.158    type AccountId = AccountId;159    /// The aggregated dispatch type that is available for extrinsics.160    type Call = Call;161    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.162    type Lookup = IdentityLookup<AccountId>;163    /// The index type for storing how many extrinsics an account has signed.164    type Index = Index;165    /// The index type for blocks.166    type BlockNumber = BlockNumber;167    /// The type for hashing blocks and tries.168    type Hash = Hash;169    /// The hashing algorithm used.170    type Hashing = BlakeTwo256;171    /// The header type.172    type Header = generic::Header<BlockNumber, BlakeTwo256>;173    /// The ubiquitous event type.174    type Event = Event;175    /// The ubiquitous origin type.176    type Origin = Origin;177    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).178    type BlockHashCount = BlockHashCount;179    /// Maximum weight of each block.180    type MaximumBlockWeight = MaximumBlockWeight;181    /// The weight of database operations that the runtime can invoke.182    type DbWeight = RocksDbWeight;183    /// The weight of the overhead invoked on the block import process, independent of the184    /// extrinsics included in that block.185    type BlockExecutionWeight = BlockExecutionWeight;186    /// The base weight of any extrinsic processed by the runtime, independent of the187    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)188    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;189    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,190    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on191    /// initialize cost).192    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;193    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.194    type MaximumBlockLength = MaximumBlockLength;195    /// Portion of the block weight that is available to all normal transactions.196    type AvailableBlockRatio = AvailableBlockRatio;197    /// Version of the runtime.198    type Version = Version;199 	/// This type is being generated by `construct_runtime!`.200    type PalletInfo = PalletInfo;201    /// What to do if a new account is created.202    type OnNewAccount = ();203    /// What to do if an account is fully reaped from the system.204    type OnKilledAccount = ();205    /// The data to be stored in an account.206    type AccountData = pallet_balances::AccountData<Balance>;207	/// Weight information for the extrinsics of this pallet.208	type SystemWeightInfo = ();209}210211impl pallet_aura::Trait for Runtime {212    type AuthorityId = AuraId;213}214215impl pallet_grandpa::Trait for Runtime {216	type Event = Event;217	type Call = Call;218219	type KeyOwnerProofSystem = ();220221	type KeyOwnerProof =222		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;223224	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(225		KeyTypeId,226		GrandpaId,227	)>>::IdentificationTuple;228229	type HandleEquivocation = ();230231	type WeightInfo = ();232}233234parameter_types! {235    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;236}237238impl pallet_timestamp::Trait for Runtime {239	/// A timestamp: milliseconds since the unix epoch.240	type Moment = u64;241	type OnTimestampSet = Aura;242	type MinimumPeriod = MinimumPeriod;243	type WeightInfo = ();244}245246parameter_types! {247    // pub const ExistentialDeposit: u128 = 500;248    pub const ExistentialDeposit: u128 = 0;249	pub const MaxLocks: u32 = 50;250}251252impl pallet_balances::Trait for Runtime {253	type MaxLocks = MaxLocks;254	/// The type for recording an account's balance.255	type Balance = Balance;256	/// The ubiquitous event type.257	type Event = Event;258	type DustRemoval = ();259	type ExistentialDeposit = ExistentialDeposit;260	type AccountStore = System;261	type WeightInfo = ();262}263264pub const MILLICENTS: Balance = 1_000_000_000;265pub const CENTS: Balance = 1_000 * MILLICENTS;266pub const DOLLARS: Balance = 100 * CENTS;267268parameter_types! {269    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;270    pub const RentByteFee: Balance = 4 * MILLICENTS;271    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;272    pub const SurchargeReward: Balance = 150 * MILLICENTS;273}274275impl pallet_contracts::Trait for Runtime {276	type Time = Timestamp;277	type Randomness = RandomnessCollectiveFlip;278	type Currency = Balances;279	type Event = Event;280	type DetermineContractAddress = pallet_contracts::SimpleAddressDeterminer<Runtime>;281	type TrieIdGenerator = pallet_contracts::TrieIdFromParentCounter<Runtime>;282	type RentPayment = ();283	type SignedClaimHandicap = pallet_contracts::DefaultSignedClaimHandicap;284	type TombstoneDeposit = TombstoneDeposit;285	type StorageSizeOffset = pallet_contracts::DefaultStorageSizeOffset;286	type RentByteFee = RentByteFee;287	type RentDepositOffset = RentDepositOffset;288	type SurchargeReward = SurchargeReward;289	type MaxDepth = pallet_contracts::DefaultMaxDepth;290	type MaxValueSize = pallet_contracts::DefaultMaxValueSize;291	type WeightPrice = pallet_transaction_payment::Module<Self>;292}293294parameter_types! {295	pub const TransactionByteFee: Balance = 10 * MILLICENTS;296}297298impl pallet_transaction_payment::Trait for Runtime {299    type Currency = pallet_balances::Module<Runtime>;300    type OnTransactionPayment = ();301    type TransactionByteFee = TransactionByteFee;302    type WeightToFee = IdentityFee<Balance>;303    type FeeMultiplierUpdate =  ();304}305306impl pallet_sudo::Trait for Runtime {307    type Event = Event;308    type Call = Call;309}310311/// Used for the module nft in `./nft.rs`312impl pallet_nft::Trait for Runtime {313    type Event = Event;314    type WeightInfo = nft_weights::WeightInfo;315}316317construct_runtime!(318    pub enum Runtime where319        Block = Block,320        NodeBlock = opaque::Block,321        UncheckedExtrinsic = UncheckedExtrinsic322    {323        System: system::{Module, Call, Config, Storage, Event<T>},324        RandomnessCollectiveFlip: pallet_randomness_collective_flip::{Module, Call, Storage},325        Contracts: pallet_contracts::{Module, Call, Config, Storage, Event<T>},326        Timestamp: pallet_timestamp::{Module, Call, Storage, Inherent},327        Aura: pallet_aura::{Module, Config<T>, Inherent},328        Grandpa: pallet_grandpa::{Module, Call, Storage, Config, Event},329        Balances: pallet_balances::{Module, Call, Storage, Config<T>, Event<T>},330        TransactionPayment: pallet_transaction_payment::{Module, Storage},331        Sudo: pallet_sudo::{Module, Call, Config<T>, Storage, Event<T>},332        Nft: pallet_nft::{Module, Call, Config<T>, Storage, Event<T>},333    }334);335336/// The address format for describing accounts.337pub type Address = AccountId;338/// Block header type as expected by this runtime.339pub type Header = generic::Header<BlockNumber, BlakeTwo256>;340/// Block type as expected by this runtime.341pub type Block = generic::Block<Header, UncheckedExtrinsic>;342/// A Block signed with a Justification343pub type SignedBlock = generic::SignedBlock<Block>;344/// BlockId type as expected by this runtime.345pub type BlockId = generic::BlockId<Block>;346/// The SignedExtension to the basic transaction logic.347pub type SignedExtra = (348    system::CheckSpecVersion<Runtime>,349    system::CheckTxVersion<Runtime>,350    system::CheckGenesis<Runtime>,351    system::CheckEra<Runtime>,352    system::CheckNonce<Runtime>,353    system::CheckWeight<Runtime>,354    pallet_nft::ChargeTransactionPayment<Runtime>,355    pallet_nft::ChargeContractTransactionPayment<Runtime>,356);357/// Unchecked extrinsic type as expected by this runtime.358pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;359/// Extrinsic type that has already been checked.360pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;361/// Executive: handles dispatch to the various modules.362pub type Executive =363    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;364365impl_runtime_apis! {366367    impl pallet_contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>368    for Runtime369    {370        fn call(371            origin: AccountId,372            dest: AccountId,373            value: Balance,374            gas_limit: u64,375            input_data: Vec<u8>,376        ) -> ContractExecResult {377			let (exec_result, gas_consumed) =378				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);379			match exec_result {380				Ok(v) => ContractExecResult::Success {381					flags: v.flags.bits(),382					data: v.data,383					gas_consumed: gas_consumed,384				},385				Err(_) => ContractExecResult::Error,386			}387        }388389        fn get_storage(390            address: AccountId,391            key: [u8; 32],392        ) -> pallet_contracts_primitives::GetStorageResult {393            Contracts::get_storage(address, key)394        }395396        fn rent_projection(397            address: AccountId,398        ) -> pallet_contracts_primitives::RentProjectionResult<BlockNumber> {399            Contracts::rent_projection(address)400        }401    }402403    impl sp_api::Core<Block> for Runtime {404        fn version() -> RuntimeVersion {405            VERSION406        }407408        fn execute_block(block: Block) {409            Executive::execute_block(block)410        }411412        fn initialize_block(header: &<Block as BlockT>::Header) {413            Executive::initialize_block(header)414        }415    }416417    impl sp_api::Metadata<Block> for Runtime {418        fn metadata() -> OpaqueMetadata {419            Runtime::metadata().into()420        }421    }422423    impl sp_block_builder::BlockBuilder<Block> for Runtime {424        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {425            Executive::apply_extrinsic(extrinsic)426        }427428        fn finalize_block() -> <Block as BlockT>::Header {429            Executive::finalize_block()430        }431432        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {433            data.create_extrinsics()434        }435436        fn check_inherents(437            block: Block,438            data: sp_inherents::InherentData,439        ) -> sp_inherents::CheckInherentsResult {440            data.check_extrinsics(&block)441        }442443        fn random_seed() -> <Block as BlockT>::Hash {444            RandomnessCollectiveFlip::random_seed()445        }446    }447448    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {449        fn validate_transaction(450            source: TransactionSource,451            tx: <Block as BlockT>::Extrinsic,452        ) -> TransactionValidity {453            Executive::validate_transaction(source, tx)454        }455    }456457    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {458        fn offchain_worker(header: &<Block as BlockT>::Header) {459            Executive::offchain_worker(header)460        }461    }462463    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {464        fn slot_duration() -> u64 {465            Aura::slot_duration()466        }467468        fn authorities() -> Vec<AuraId> {469            Aura::authorities()470        }471    }472473    impl sp_session::SessionKeys<Block> for Runtime {474        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {475            opaque::SessionKeys::generate(seed)476        }477478        fn decode_session_keys(479            encoded: Vec<u8>,480        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {481            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)482        }483    }484485	impl fg_primitives::GrandpaApi<Block> for Runtime {486		fn grandpa_authorities() -> GrandpaAuthorityList {487			Grandpa::grandpa_authorities()488		}489490		fn submit_report_equivocation_unsigned_extrinsic(491			_equivocation_proof: fg_primitives::EquivocationProof<492				<Block as BlockT>::Hash,493				NumberFor<Block>,494			>,495			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,496		) -> Option<()> {497			None498		}499500		fn generate_key_ownership_proof(501			_set_id: fg_primitives::SetId,502			_authority_id: GrandpaId,503		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {504			// NOTE: this is the only implementation possible since we've505			// defined our key owner proof type as a bottom type (i.e. a type506			// with no values).507			None508		}509    }510    511	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {512		fn account_nonce(account: AccountId) -> Index {513			System::account_nonce(account)514		}515	}516517	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {518		fn query_info(519			uxt: <Block as BlockT>::Extrinsic,520			len: u32,521		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {522			TransactionPayment::query_info(uxt, len)523		}524	}525526    #[cfg(feature = "runtime-benchmarks")]527	impl frame_benchmarking::Benchmark<Block> for Runtime {528		fn dispatch_benchmark(529			config: frame_benchmarking::BenchmarkConfig530		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {531			use frame_benchmarking::{Benchmarking, BenchmarkBatch, add_benchmark, TrackedStorageKey};532533			let whitelist: Vec<TrackedStorageKey> = vec![534				// Alice account535				hex_literal::hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d").to_vec().into(),536				// // Total Issuance537				// hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80").to_vec().into(),538				// // Execution Phase539				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a").to_vec().into(),540				// // Event Count541				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850").to_vec().into(),542				// // System Events543				// hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7").to_vec().into(),544            ];545546			let mut batches = Vec::<BenchmarkBatch>::new();547			let params = (&config, &whitelist);548549			add_benchmark!(params, batches, pallet_nft, Nft);550551			if batches.is_empty() { return Err("Benchmark not found for this pallet.".into()) }552			Ok(batches)553		}554	}555}