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

difftreelog

source

runtime/src/lib.rs17.0 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 contracts_rpc_runtime_api::ContractExecResult;12use grandpa::fg_primitives;13use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};14use sp_api::impl_runtime_apis;15use sp_consensus_aura::sr25519::AuthorityId as AuraId;16use sp_core::{crypto::KeyTypeId, OpaqueMetadata};17use sp_runtime::{18    create_runtime_str, generic, impl_opaque_keys,19    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 balances::Call as BalancesCall;33pub use 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 system::{self as system};5354pub use timestamp::Call as TimestampCall;5556/// Re-export a nft pallet57/// TODO: Check this re-export. Is this safe and good style?58extern crate nft;59pub use 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>;8687/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know88/// the specifics of the runtime. They can then be made to be agnostic over specific formats89/// of data like extrinsics, allowing for them to continue syncing the network through upgrades90/// to even the core data structures.91pub mod opaque {92    use super::*;9394    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;9596    /// Opaque block header type.97    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;98    /// Opaque block type.99    pub type Block = generic::Block<Header, UncheckedExtrinsic>;100    /// Opaque block identifier type.101    pub type BlockId = generic::BlockId<Block>;102103    impl_opaque_keys! {104        pub struct SessionKeys {105            pub aura: Aura,106            pub grandpa: Grandpa,107        }108    }109}110111/// This runtime version.112pub const VERSION: RuntimeVersion = RuntimeVersion {113    spec_name: create_runtime_str!("nft"),114    impl_name: create_runtime_str!("nft"),115    authoring_version: 1,116    spec_version: 2,117    impl_version: 1,118    apis: RUNTIME_API_VERSIONS,119    transaction_version: 1,120};121122pub const MILLISECS_PER_BLOCK: u64 = 6000;123124pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;125126// These time units are defined in number of blocks.127pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);128pub const HOURS: BlockNumber = MINUTES * 60;129pub const DAYS: BlockNumber = HOURS * 24;130131/// The version information used to identify this runtime when compiled natively.132#[cfg(feature = "std")]133pub fn native_version() -> NativeVersion {134    NativeVersion {135        runtime_version: VERSION,136        can_author_with: Default::default(),137    }138}139140parameter_types! {141    pub const BlockHashCount: BlockNumber = 2400;142    /// We allow for 2 seconds of compute with a 6 second average block time.143    pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;144    pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);145    /// Assume 10% of weight for average on_initialize calls.146    pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()147        .saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();148    pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;149    pub const Version: RuntimeVersion = VERSION;150}151152impl system::Trait for Runtime {153    /// The basic call filter to use in dispatchable.154    type BaseCallFilter = ();155    /// The identifier used to distinguish between accounts.156    type AccountId = AccountId;157    /// The aggregated dispatch type that is available for extrinsics.158    type Call = Call;159    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.160    type Lookup = IdentityLookup<AccountId>;161    /// The index type for storing how many extrinsics an account has signed.162    type Index = Index;163    /// The index type for blocks.164    type BlockNumber = BlockNumber;165    /// The type for hashing blocks and tries.166    type Hash = Hash;167    /// The hashing algorithm used.168    type Hashing = BlakeTwo256;169    /// The header type.170    type Header = generic::Header<BlockNumber, BlakeTwo256>;171    /// The ubiquitous event type.172    type Event = Event;173    /// The ubiquitous origin type.174    type Origin = Origin;175    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).176    type BlockHashCount = BlockHashCount;177    /// Maximum weight of each block.178    type MaximumBlockWeight = MaximumBlockWeight;179    /// The weight of database operations that the runtime can invoke.180    type DbWeight = RocksDbWeight;181    /// The weight of the overhead invoked on the block import process, independent of the182    /// extrinsics included in that block.183    type BlockExecutionWeight = BlockExecutionWeight;184    /// The base weight of any extrinsic processed by the runtime, independent of the185    /// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)186    type ExtrinsicBaseWeight = ExtrinsicBaseWeight;187    /// The maximum weight that a single extrinsic of `Normal` dispatch class can have,188    /// idependent of the logic of that extrinsics. (Roughly max block weight - average on189    /// initialize cost).190    type MaximumExtrinsicWeight = MaximumExtrinsicWeight;191    /// Maximum size of all encoded transactions (in bytes) that are allowed in one block.192    type MaximumBlockLength = MaximumBlockLength;193    /// Portion of the block weight that is available to all normal transactions.194    type AvailableBlockRatio = AvailableBlockRatio;195    /// Version of the runtime.196    type Version = Version;197    /// Converts a module to the index of the module in `construct_runtime!`.198    /// This type is being generated by `construct_runtime!`.199    type ModuleToIndex = ModuleToIndex;200    /// What to do if a new account is created.201    type OnNewAccount = ();202    /// What to do if an account is fully reaped from the system.203    type OnKilledAccount = ();204    /// The data to be stored in an account.205    type AccountData = balances::AccountData<Balance>;206}207208impl aura::Trait for Runtime {209    type AuthorityId = AuraId;210}211212impl grandpa::Trait for Runtime {213    type Event = Event;214    type Call = Call;215216    type KeyOwnerProofSystem = ();217218    type KeyOwnerProof =219        <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;220221    type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(222        KeyTypeId,223        GrandpaId,224    )>>::IdentificationTuple;225226    type HandleEquivocation = ();227}228229parameter_types! {230    pub const MinimumPeriod: u64 = SLOT_DURATION / 2;231}232233impl timestamp::Trait for Runtime {234    /// A timestamp: milliseconds since the unix epoch.235    type Moment = u64;236    type OnTimestampSet = Aura;237    type MinimumPeriod = MinimumPeriod;238}239240parameter_types! {241    // pub const ExistentialDeposit: u128 = 500;242    pub const ExistentialDeposit: u128 = 0;243}244245impl balances::Trait for Runtime {246    /// The type for recording an account's balance.247    type Balance = Balance;248    /// The ubiquitous event type.249    type Event = Event;250    type DustRemoval = ();251    type ExistentialDeposit = ExistentialDeposit;252    type AccountStore = System;253}254255pub const MILLICENTS: Balance = 1_000_000_000;256pub const CENTS: Balance = 1_000 * MILLICENTS;257pub const DOLLARS: Balance = 100 * CENTS;258259parameter_types! {260    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;261    pub const RentByteFee: Balance = 4 * MILLICENTS;262    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;263    pub const SurchargeReward: Balance = 150 * MILLICENTS;264}265266impl contracts::Trait for Runtime {267    type Call = Call;268    type Time = Timestamp;269    type Randomness = RandomnessCollectiveFlip;270    type Currency = Balances;271    type Event = Event;272    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;273    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;274    type RentPayment = ();275    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;276    type TombstoneDeposit = TombstoneDeposit;277    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;278    type RentByteFee = RentByteFee;279    type RentDepositOffset = RentDepositOffset;280    type SurchargeReward = SurchargeReward;281    type MaxDepth = contracts::DefaultMaxDepth;282    type MaxValueSize = contracts::DefaultMaxValueSize;283    type WeightPrice = transaction_payment::Module<Self>;284}285286parameter_types! {287    pub const TransactionByteFee: Balance = 1;288}289290impl transaction_payment::Trait for Runtime {291    type Currency = balances::Module<Runtime>;292    type OnTransactionPayment = ();293    type TransactionByteFee = TransactionByteFee;294    type WeightToFee = IdentityFee<Balance>;295    type FeeMultiplierUpdate = ();296}297298impl sudo::Trait for Runtime {299    type Event = Event;300    type Call = Call;301}302303/// Used for the module nft in `./nft.rs`304impl nft::Trait for Runtime {305    type Event = Event;306}307308construct_runtime!(309    pub enum Runtime where310        Block = Block,311        NodeBlock = opaque::Block,312        UncheckedExtrinsic = UncheckedExtrinsic313    {314        System: system::{Module, Call, Config, Storage, Event<T>},315        RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},316        Contracts: contracts::{Module, Call, Config, Storage, Event<T>},317        Timestamp: timestamp::{Module, Call, Storage, Inherent},318        Aura: aura::{Module, Config<T>, Inherent(Timestamp)},319        Grandpa: grandpa::{Module, Call, Storage, Config, Event},320        Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},321        TransactionPayment: transaction_payment::{Module, Storage},322        Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},323        Nft: nft::{Module, Call, Config<T>, Storage, Event<T>},324    }325);326327/// The address format for describing accounts.328pub type Address = AccountId;329/// Block header type as expected by this runtime.330pub type Header = generic::Header<BlockNumber, BlakeTwo256>;331/// Block type as expected by this runtime.332pub type Block = generic::Block<Header, UncheckedExtrinsic>;333/// A Block signed with a Justification334pub type SignedBlock = generic::SignedBlock<Block>;335/// BlockId type as expected by this runtime.336pub type BlockId = generic::BlockId<Block>;337/// The SignedExtension to the basic transaction logic.338pub type SignedExtra = (339    system::CheckSpecVersion<Runtime>,340    system::CheckTxVersion<Runtime>,341    system::CheckGenesis<Runtime>,342    system::CheckEra<Runtime>,343    system::CheckNonce<Runtime>,344    system::CheckWeight<Runtime>,345    nft::ChargeTransactionPayment<Runtime>,346);347/// Unchecked extrinsic type as expected by this runtime.348pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;349/// Extrinsic type that has already been checked.350pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;351/// Executive: handles dispatch to the various modules.352pub type Executive =353    frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;354355impl_runtime_apis! {356357    impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>358    for Runtime359    {360        fn call(361            origin: AccountId,362            dest: AccountId,363            value: Balance,364            gas_limit: u64,365            input_data: Vec<u8>,366        ) -> ContractExecResult {367            let exec_result =368                Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);369            match exec_result {370                Ok(v) => ContractExecResult::Success {371                    status: v.status,372                    data: v.data,373                },374                Err(_) => ContractExecResult::Error,375            }376        }377378        fn get_storage(379            address: AccountId,380            key: [u8; 32],381        ) -> contracts_primitives::GetStorageResult {382            Contracts::get_storage(address, key)383        }384385        fn rent_projection(386            address: AccountId,387        ) -> contracts_primitives::RentProjectionResult<BlockNumber> {388            Contracts::rent_projection(address)389        }390    }391392    impl sp_api::Core<Block> for Runtime {393        fn version() -> RuntimeVersion {394            VERSION395        }396397        fn execute_block(block: Block) {398            Executive::execute_block(block)399        }400401        fn initialize_block(header: &<Block as BlockT>::Header) {402            Executive::initialize_block(header)403        }404    }405406    impl sp_api::Metadata<Block> for Runtime {407        fn metadata() -> OpaqueMetadata {408            Runtime::metadata().into()409        }410    }411412    impl sp_block_builder::BlockBuilder<Block> for Runtime {413        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {414            Executive::apply_extrinsic(extrinsic)415        }416417        fn finalize_block() -> <Block as BlockT>::Header {418            Executive::finalize_block()419        }420421        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {422            data.create_extrinsics()423        }424425        fn check_inherents(426            block: Block,427            data: sp_inherents::InherentData,428        ) -> sp_inherents::CheckInherentsResult {429            data.check_extrinsics(&block)430        }431432        fn random_seed() -> <Block as BlockT>::Hash {433            RandomnessCollectiveFlip::random_seed()434        }435    }436437    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {438        fn validate_transaction(439            source: TransactionSource,440            tx: <Block as BlockT>::Extrinsic,441        ) -> TransactionValidity {442            Executive::validate_transaction(source, tx)443        }444    }445446    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {447        fn offchain_worker(header: &<Block as BlockT>::Header) {448            Executive::offchain_worker(header)449        }450    }451452    impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {453        fn slot_duration() -> u64 {454            Aura::slot_duration()455        }456457        fn authorities() -> Vec<AuraId> {458            Aura::authorities()459        }460    }461462    impl sp_session::SessionKeys<Block> for Runtime {463        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {464            opaque::SessionKeys::generate(seed)465        }466467        fn decode_session_keys(468            encoded: Vec<u8>,469        ) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {470            opaque::SessionKeys::decode_into_raw_public_keys(&encoded)471        }472    }473474    impl fg_primitives::GrandpaApi<Block> for Runtime {475        fn grandpa_authorities() -> GrandpaAuthorityList {476            Grandpa::grandpa_authorities()477        }478479        fn submit_report_equivocation_extrinsic(480            _equivocation_proof: fg_primitives::EquivocationProof<481                <Block as BlockT>::Hash,482                NumberFor<Block>,483            >,484            _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,485        ) -> Option<()> {486            None487        }488489        fn generate_key_ownership_proof(490            _set_id: fg_primitives::SetId,491            _authority_id: GrandpaId,492        ) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {493            // NOTE: this is the only implementation possible since we've494            // defined our key owner proof type as a bottom type (i.e. a type495            // with no values).496            None497        }498    }499}