git.delta.rocks / unique-network / refs/commits / 97765fef60a1

difftreelog

source

runtime/src/lib.rs16.3 KiBsourcehistory
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 grandpa::fg_primitives;12use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};13use sp_api::impl_runtime_apis;14use sp_consensus_aura::sr25519::AuthorityId as AuraId;15use sp_core::{crypto::KeyTypeId, OpaqueMetadata};16use sp_runtime::traits::{17    BlakeTwo256, Block as BlockT, IdentifyAccount, IdentityLookup, NumberFor, Saturating, Verify,18};19use sp_runtime::{20    create_runtime_str, generic, impl_opaque_keys,21    transaction_validity::{TransactionSource, TransactionValidity},22    ApplyExtrinsicResult, MultiSignature,23};24use contracts_rpc_runtime_api::ContractExecResult;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 identifier used to distinguish between accounts.143    type AccountId = AccountId;144    /// The aggregated dispatch type that is available for extrinsics.145    type Call = Call;146    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.147    type Lookup = IdentityLookup<AccountId>;148    /// The index type for storing how many extrinsics an account has signed.149    type Index = Index;150    /// The index type for blocks.151    type BlockNumber = BlockNumber;152    /// The type for hashing blocks and tries.153    type Hash = Hash;154    /// The hashing algorithm used.155    type Hashing = BlakeTwo256;156    /// The header type.157    type Header = generic::Header<BlockNumber, BlakeTwo256>;158    /// The ubiquitous event type.159    type Event = Event;160    /// The ubiquitous origin type.161    type Origin = Origin;162    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).163    type BlockHashCount = BlockHashCount;164    /// Maximum weight of each block.165    type MaximumBlockWeight = MaximumBlockWeight;166    /// The weight of database operations that the runtime can invoke.167    type DbWeight = RocksDbWeight;168    /// The weight of the overhead invoked on the block import process, independent of the169    /// extrinsics included in that block.170    type BlockExecutionWeight = BlockExecutionWeight;171    /// The base weight of any extrinsic processed by the runtime, independent of the172    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)173    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;174    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,175    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on176    /// initialize cost).177    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;178    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.179    type MaximumBlockLength = MaximumBlockLength;180    /// Portion of the block weight that is available to all normal transactions.181    type AvailableBlockRatio = AvailableBlockRatio;182    /// Version of the runtime.183    type Version = Version;184    /// Converts a module to the index of the module in `construct_runtime!`.185    ///186    /// This type is being generated by `construct_runtime!`.187    type ModuleToIndex = ModuleToIndex;188    /// What to do if a new account is created.189    type OnNewAccount = ();190    /// What to do if an account is fully reaped from the system.191    type OnKilledAccount = ();192    /// The data to be stored in an account.193    type AccountData = balances::AccountData<Balance>;194}195196impl aura::Trait for Runtime {197    type AuthorityId = AuraId;198}199200impl grandpa::Trait for Runtime {201    type Event = Event;202    type Call = Call;203204    type KeyOwnerProofSystem = ();205206    type KeyOwnerProof =207        <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;208209    type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(210        KeyTypeId,211        GrandpaId,212    )>>::IdentificationTuple;213214    type HandleEquivocation = ();215}216217parameter_types! {218    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;219}220221impl timestamp::Trait for Runtime {222    /// A timestamp: milliseconds since the unix epoch.223    type Moment = u64;224    type OnTimestampSet = Aura;225    type MinimumPeriod = MinimumPeriod;226}227228parameter_types! {229    pub const ExistentialDeposit: u128 = 500;230}231232impl balances::Trait for Runtime {233    /// The type for recording an account's balance.234    type Balance = Balance;235    /// The ubiquitous event type.236    type Event = Event;237    type DustRemoval = ();238    type ExistentialDeposit = ExistentialDeposit;239    type AccountStore = System;240}241242parameter_types! {243    pub const TombstoneDeposit: Balance = 1;244    pub const RentByteFee: Balance = 1;245    pub const RentDepositOffset: Balance = 1000;246    pub const SurchargeReward: Balance = 150;247}248249impl contracts::Trait for Runtime {250    type Time = Timestamp;251    type Randomness = RandomnessCollectiveFlip;252    type Call = Call;253    type Event = Event;254    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;255    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;256    type RentPayment = ();257    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;258    type TombstoneDeposit = TombstoneDeposit;259    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;260    type RentByteFee = RentByteFee;261    type RentDepositOffset = RentDepositOffset;262    type SurchargeReward = SurchargeReward;263    type MaxDepth = contracts::DefaultMaxDepth;264    type MaxValueSize = contracts::DefaultMaxValueSize;265}266267parameter_types! {268    pub const TransactionByteFee: Balance = 1;269}270271impl transaction_payment::Trait for Runtime {272    type Currency = balances::Module<Runtime>;273    type OnTransactionPayment = ();274    type TransactionByteFee = TransactionByteFee;275    type WeightToFee = IdentityFee<Balance>;276    type FeeMultiplierUpdate = ();277}278279impl sudo::Trait for Runtime {280    type Event = Event;281    type Call = Call;282}283284/// Used for the module nft in `./nft.rs`285impl nft::Trait for Runtime {286    type Event = Event;287}288289construct_runtime!(290    pub enum Runtime where291        Block = Block,292        NodeBlock = opaque::Block,293        UncheckedExtrinsic = UncheckedExtrinsic294    {295        System: system::{Module, Call, Config, Storage, Event<T>},296        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},297        Contracts: contracts::{Module, Call, Config, Storage, Event<T>},298        Timestamp: timestamp::{Module, Call, Storage, Inherent},299        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},300        Grandpa: grandpa::{Module, Call, Storage, Config, Event},301        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},302        TransactionPayment: transaction_payment::{Module, Storage},303        Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},304        Nft: nft::{Module, Call, Storage, Event<T>},305    }306);307308/// The address format for describing accounts.309pub type Address = AccountId;310/// Block header type as expected by this runtime.311pub type Header = generic::Header<BlockNumber, BlakeTwo256>;312/// Block type as expected by this runtime.313pub type Block = generic::Block<Header, UncheckedExtrinsic>;314/// A Block signed with a Justification315pub type SignedBlock = generic::SignedBlock<Block>;316/// BlockId type as expected by this runtime.317pub type BlockId = generic::BlockId<Block>;318/// The SignedExtension to the basic transaction logic.319pub type SignedExtra = (320    system::CheckSpecVersion<Runtime>,321    system::CheckTxVersion<Runtime>,322    system::CheckGenesis<Runtime>,323    system::CheckEra<Runtime>,324    system::CheckNonce<Runtime>,325    system::CheckWeight<Runtime>,326    transaction_payment::ChargeTransactionPayment<Runtime>,327);328/// Unchecked extrinsic type as expected by this runtime.329pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;330/// Extrinsic type that has already been checked.331pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;332/// Executive: handles dispatch to the various modules.333pub type Executive =334    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;335336impl_runtime_apis! {337338    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>339    for Runtime340    {341        fn call(342            origin: AccountId,343            dest: AccountId,344            value: Balance,345            gas_limit: u64,346            input_data: Vec<u8>,347        ) -> ContractExecResult {348            let exec_result =349                Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);350            match exec_result {351                Ok(v) => ContractExecResult::Success {352                    status: v.status,353                    data: v.data,354                },355                Err(_) => ContractExecResult::Error,356            }357        }358359        fn get_storage(360            address: AccountId,361            key: [u8; 32],362        ) -> contracts_primitives::GetStorageResult {363            Contracts::get_storage(address, key)364        }365366        fn rent_projection(367            address: AccountId,368        ) -> contracts_primitives::RentProjectionResult<BlockNumber> {369            Contracts::rent_projection(address)370        }371    }372373    impl sp_api::Core<Block> for Runtime {374        fn version() -> RuntimeVersion {375            VERSION376        }377378        fn execute_block(block: Block) {379            Executive::execute_block(block)380        }381382        fn initialize_block(header: &<Block as BlockT>::Header) {383            Executive::initialize_block(header)384        }385    }386387    impl sp_api::Metadata<Block> for Runtime {388        fn metadata() -> OpaqueMetadata {389            Runtime::metadata().into()390        }391    }392393    impl sp_block_builder::BlockBuilder<Block> for Runtime {394        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {395            Executive::apply_extrinsic(extrinsic)396        }397398        fn finalize_block() -> <Block as BlockT>::Header {399            Executive::finalize_block()400        }401402        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {403            data.create_extrinsics()404        }405406        fn check_inherents(407            block: Block,408            data: sp_inherents::InherentData,409        ) -> sp_inherents::CheckInherentsResult {410            data.check_extrinsics(&block)411        }412413        fn random_seed() -> <Block as BlockT>::Hash {414            RandomnessCollectiveFlip::random_seed()415        }416    }417418    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {419        fn validate_transaction(420            source: TransactionSource,421            tx: <Block as BlockT>::Extrinsic,422        ) -> TransactionValidity {423            Executive::validate_transaction(source, tx)424        }425    }426427    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {428        fn offchain_worker(header: &<Block as BlockT>::Header) {429            Executive::offchain_worker(header)430        }431    }432433    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {434        fn slot_duration() -> u64 {435            Aura::slot_duration()436        }437438        fn authorities() -> Vec<AuraId> {439            Aura::authorities()440        }441    }442443    impl sp_session::SessionKeys<Block> for Runtime {444        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {445            opaque::SessionKeys::generate(seed)446        }447448        fn decode_session_keys(449            encoded: Vec<u8>,450        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {451            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)452        }453    }454455    impl fg_primitives::GrandpaApi<Block> for Runtime {456        fn grandpa_authorities() -> GrandpaAuthorityList {457            Grandpa::grandpa_authorities()458        }459460        fn submit_report_equivocation_extrinsic(461            _equivocation_proof: fg_primitives::EquivocationProof<462                <Block as BlockT>::Hash,463                NumberFor<Block>,464            >,465            _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,466        ) -> Option<()> {467            None468        }469470        fn generate_key_ownership_proof(471            _set_id: fg_primitives::SetId,472            _authority_id: GrandpaId,473        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {474            // NOTE: this is the only implementation possible since we've475            // defined our key owner proof type as a bottom type (i.e. a type476            // with no values).477            None478        }479    }480}