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

difftreelog

source

runtime/src/lib.rs16.5 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}241242pub const MILLICENTS: Balance = 1_000_000_000;243pub const CENTS: Balance = 1_000 * MILLICENTS;244pub const DOLLARS: Balance = 100 * CENTS;245246parameter_types! {247    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;248    pub const RentByteFee: Balance = 4 * MILLICENTS;249    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;250    pub const SurchargeReward: Balance = 150 * MILLICENTS;251}252253impl contracts::Trait for Runtime {254    type Time = Timestamp;255    type Randomness = RandomnessCollectiveFlip;256    type Call = Call;257    type Event = Event;258    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;259    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;260    type RentPayment = ();261    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;262    type TombstoneDeposit = TombstoneDeposit;263    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;264    type RentByteFee = RentByteFee;265    type RentDepositOffset = RentDepositOffset;266    type SurchargeReward = SurchargeReward;267    type MaxDepth = contracts::DefaultMaxDepth;268    type MaxValueSize = contracts::DefaultMaxValueSize;269}270271parameter_types! {272    pub const TransactionByteFee: Balance = 1;273}274275impl transaction_payment::Trait for Runtime {276    type Currency = balances::Module<Runtime>;277    type OnTransactionPayment = ();278    type TransactionByteFee = TransactionByteFee;279    type WeightToFee = IdentityFee<Balance>;280    type FeeMultiplierUpdate = ();281}282283impl sudo::Trait for Runtime {284    type Event = Event;285    type Call = Call;286}287288/// Used for the module nft in `./nft.rs`289impl nft::Trait for Runtime {290    type Event = Event;291}292293construct_runtime!(294    pub enum Runtime where295        Block = Block,296        NodeBlock = opaque::Block,297        UncheckedExtrinsic = UncheckedExtrinsic298    {299        System: system::{Module, Call, Config, Storage, Event<T>},300        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},301        Contracts: contracts::{Module, Call, Config, Storage, Event<T>},302        Timestamp: timestamp::{Module, Call, Storage, Inherent},303        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},304        Grandpa: grandpa::{Module, Call, Storage, Config, Event},305        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},306        TransactionPayment: transaction_payment::{Module, Storage},307        Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},308        Nft: nft::{Module, Call, Storage, Event<T>},309    }310);311312/// The address format for describing accounts.313pub type Address = AccountId;314/// Block header type as expected by this runtime.315pub type Header = generic::Header<BlockNumber, BlakeTwo256>;316/// Block type as expected by this runtime.317pub type Block = generic::Block<Header, UncheckedExtrinsic>;318/// A Block signed with a Justification319pub type SignedBlock = generic::SignedBlock<Block>;320/// BlockId type as expected by this runtime.321pub type BlockId = generic::BlockId<Block>;322/// The SignedExtension to the basic transaction logic.323pub type SignedExtra = (324    system::CheckSpecVersion<Runtime>,325    system::CheckTxVersion<Runtime>,326    system::CheckGenesis<Runtime>,327    system::CheckEra<Runtime>,328    system::CheckNonce<Runtime>,329    system::CheckWeight<Runtime>,330    transaction_payment::ChargeTransactionPayment<Runtime>,331);332/// Unchecked extrinsic type as expected by this runtime.333pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;334/// Extrinsic type that has already been checked.335pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;336/// Executive: handles dispatch to the various modules.337pub type Executive =338    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;339340impl_runtime_apis! {341342    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>343    for Runtime344    {345        fn call(346            origin: AccountId,347            dest: AccountId,348            value: Balance,349            gas_limit: u64,350            input_data: Vec<u8>,351        ) -> ContractExecResult {352            let exec_result =353                Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);354            match exec_result {355                Ok(v) => ContractExecResult::Success {356                    status: v.status,357                    data: v.data,358                },359                Err(_) => ContractExecResult::Error,360            }361        }362363        fn get_storage(364            address: AccountId,365            key: [u8; 32],366        ) -> contracts_primitives::GetStorageResult {367            Contracts::get_storage(address, key)368        }369370        fn rent_projection(371            address: AccountId,372        ) -> contracts_primitives::RentProjectionResult<BlockNumber> {373            Contracts::rent_projection(address)374        }375    }376377    impl sp_api::Core<Block> for Runtime {378        fn version() -> RuntimeVersion {379            VERSION380        }381382        fn execute_block(block: Block) {383            Executive::execute_block(block)384        }385386        fn initialize_block(header: &<Block as BlockT>::Header) {387            Executive::initialize_block(header)388        }389    }390391    impl sp_api::Metadata<Block> for Runtime {392        fn metadata() -> OpaqueMetadata {393            Runtime::metadata().into()394        }395    }396397    impl sp_block_builder::BlockBuilder<Block> for Runtime {398        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {399            Executive::apply_extrinsic(extrinsic)400        }401402        fn finalize_block() -> <Block as BlockT>::Header {403            Executive::finalize_block()404        }405406        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {407            data.create_extrinsics()408        }409410        fn check_inherents(411            block: Block,412            data: sp_inherents::InherentData,413        ) -> sp_inherents::CheckInherentsResult {414            data.check_extrinsics(&block)415        }416417        fn random_seed() -> <Block as BlockT>::Hash {418            RandomnessCollectiveFlip::random_seed()419        }420    }421422    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {423        fn validate_transaction(424            source: TransactionSource,425            tx: <Block as BlockT>::Extrinsic,426        ) -> TransactionValidity {427            Executive::validate_transaction(source, tx)428        }429    }430431    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {432        fn offchain_worker(header: &<Block as BlockT>::Header) {433            Executive::offchain_worker(header)434        }435    }436437    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {438        fn slot_duration() -> u64 {439            Aura::slot_duration()440        }441442        fn authorities() -> Vec<AuraId> {443            Aura::authorities()444        }445    }446447    impl sp_session::SessionKeys<Block> for Runtime {448        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {449            opaque::SessionKeys::generate(seed)450        }451452        fn decode_session_keys(453            encoded: Vec<u8>,454        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {455            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)456        }457    }458459    impl fg_primitives::GrandpaApi<Block> for Runtime {460        fn grandpa_authorities() -> GrandpaAuthorityList {461            Grandpa::grandpa_authorities()462        }463464        fn submit_report_equivocation_extrinsic(465            _equivocation_proof: fg_primitives::EquivocationProof<466                <Block as BlockT>::Hash,467                NumberFor<Block>,468            >,469            _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,470        ) -> Option<()> {471            None472        }473474        fn generate_key_ownership_proof(475            _set_id: fg_primitives::SetId,476            _authority_id: GrandpaId,477        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {478            // NOTE: this is the only implementation possible since we've479            // defined our key owner proof type as a bottom type (i.e. a type480            // with no values).481            None482        }483    }484}