git.delta.rocks / unique-network / refs/commits / 8b6fe6666d58

difftreelog

source

runtime/src/lib.rs11.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 sp_std::prelude::*;12use sp_core::OpaqueMetadata;13use sp_runtime::{14	ApplyExtrinsicResult, transaction_validity::TransactionValidity, generic, create_runtime_str,15	impl_opaque_keys, MultiSignature16};17use sp_runtime::traits::{18	NumberFor, BlakeTwo256, Block as BlockT, StaticLookup, Verify, ConvertInto, IdentifyAccount19};20use sp_api::impl_runtime_apis;21use sp_consensus_aura::sr25519::AuthorityId as AuraId;22use grandpa::AuthorityList as GrandpaAuthorityList;23use grandpa::fg_primitives;24use sp_version::RuntimeVersion;25#[cfg(feature = "std")]26use sp_version::NativeVersion;2728// A few exports that help ease life for downstream crates.29#[cfg(any(feature = "std", test))]30pub use sp_runtime::BuildStorage;31pub use timestamp::Call as TimestampCall;32pub use balances::Call as BalancesCall;33pub use sp_runtime::{Permill, Perbill};34pub use frame_support::{35	StorageValue, construct_runtime, parameter_types,36	traits::Randomness,37	weights::Weight,38};3940/// An index to a block.41pub type BlockNumber = u32;4243/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.44pub type Signature = MultiSignature;4546/// Some way of identifying an account on the chain. We intentionally make it equivalent47/// to the public key of our transaction signing scheme.48pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;4950/// The type for looking up accounts. We don't expect more than 4 billion of them, but you51/// never know...52pub type AccountIndex = u32;5354/// Balance of an account.55pub type Balance = u128;5657/// Index of a transaction in the chain.58pub type Index = u32;5960/// A hash of some data used by the chain.61pub type Hash = sp_core::H256;6263/// Digest item type.64pub type DigestItem = generic::DigestItem<Hash>;6566/// Used for the module template in `./template.rs`67mod template;6869/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know70/// the specifics of the runtime. They can then be made to be agnostic over specific formats71/// of data like extrinsics, allowing for them to continue syncing the network through upgrades72/// to even the core datastructures.73pub mod opaque {74	use super::*;7576	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;7778	/// Opaque block header type.79	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;80	/// Opaque block type.81	pub type Block = generic::Block<Header, UncheckedExtrinsic>;82	/// Opaque block identifier type.83	pub type BlockId = generic::BlockId<Block>;8485	impl_opaque_keys! {86		pub struct SessionKeys {87			pub aura: Aura,88			pub grandpa: Grandpa,89		}90	}91}9293/// This runtime version.94pub const VERSION: RuntimeVersion = RuntimeVersion {95	spec_name: create_runtime_str!("node-template"),96	impl_name: create_runtime_str!("node-template"),97	authoring_version: 1,98	spec_version: 1,99	impl_version: 1,100	apis: RUNTIME_API_VERSIONS,101};102103pub const MILLISECS_PER_BLOCK: u64 = 6000;104105pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;106107// These time units are defined in number of blocks.108pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);109pub const HOURS: BlockNumber = MINUTES * 60;110pub const DAYS: BlockNumber = HOURS * 24;111112/// The version infromation used to identify this runtime when compiled natively.113#[cfg(feature = "std")]114pub fn native_version() -> NativeVersion {115	NativeVersion {116		runtime_version: VERSION,117		can_author_with: Default::default(),118	}119}120121parameter_types! {122	pub const BlockHashCount: BlockNumber = 250;123	pub const MaximumBlockWeight: Weight = 1_000_000;124	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);125	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;126	pub const Version: RuntimeVersion = VERSION;127}128129impl system::Trait for Runtime {130	/// The identifier used to distinguish between accounts.131	type AccountId = AccountId;132	/// The aggregated dispatch type that is available for extrinsics.133	type Call = Call;134	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.135	type Lookup = Indices;136	/// The index type for storing how many extrinsics an account has signed.137	type Index = Index;138	/// The index type for blocks.139	type BlockNumber = BlockNumber;140	/// The type for hashing blocks and tries.141	type Hash = Hash;142	/// The hashing algorithm used.143	type Hashing = BlakeTwo256;144	/// The header type.145	type Header = generic::Header<BlockNumber, BlakeTwo256>;146	/// The ubiquitous event type.147	type Event = Event;148	/// The ubiquitous origin type.149	type Origin = Origin;150	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).151	type BlockHashCount = BlockHashCount;152	/// Maximum weight of each block.153	type MaximumBlockWeight = MaximumBlockWeight;154	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.155	type MaximumBlockLength = MaximumBlockLength;156	/// Portion of the block weight that is available to all normal transactions.157	type AvailableBlockRatio = AvailableBlockRatio;158	/// Version of the runtime.159	type Version = Version;160	/// Converts a module to the index of the module in `construct_runtime!`.161	///162	/// This type is being generated by `construct_runtime!`.163	type ModuleToIndex = ModuleToIndex;164}165166impl aura::Trait for Runtime {167	type AuthorityId = AuraId;168}169170impl grandpa::Trait for Runtime {171	type Event = Event;172}173174impl indices::Trait for Runtime {175	/// The type for recording indexing into the account enumeration. If this ever overflows, there176	/// will be problems!177	type AccountIndex = AccountIndex;178	/// Use the standard means of resolving an index hint from an id.179	type ResolveHint = indices::SimpleResolveHint<Self::AccountId, Self::AccountIndex>;180	/// Determine whether an account is dead.181	type IsDeadAccount = Balances;182	/// The ubiquitous event type.183	type Event = Event;184}185186parameter_types! {187	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;188}189190impl timestamp::Trait for Runtime {191	/// A timestamp: milliseconds since the unix epoch.192	type Moment = u64;193	type OnTimestampSet = Aura;194	type MinimumPeriod = MinimumPeriod;195}196197parameter_types! {198	pub const ExistentialDeposit: u128 = 500;199	pub const TransferFee: u128 = 0;200	pub const CreationFee: u128 = 0;201}202203impl balances::Trait for Runtime {204	/// The type for recording an account's balance.205	type Balance = Balance;206	/// What to do if an account's free balance gets zeroed.207	type OnFreeBalanceZero = ();208	/// What to do if a new account is created.209	type OnNewAccount = Indices;210	/// The ubiquitous event type.211	type Event = Event;212	type DustRemoval = ();213	type TransferPayment = ();214	type ExistentialDeposit = ExistentialDeposit;215	type TransferFee = TransferFee;216	type CreationFee = CreationFee;217}218219parameter_types! {220	pub const TransactionBaseFee: Balance = 0;221	pub const TransactionByteFee: Balance = 1;222}223224impl transaction_payment::Trait for Runtime {225	type Currency = balances::Module<Runtime>;226	type OnTransactionPayment = ();227	type TransactionBaseFee = TransactionBaseFee;228	type TransactionByteFee = TransactionByteFee;229	type WeightToFee = ConvertInto;230	type FeeMultiplierUpdate = ();231}232233impl sudo::Trait for Runtime {234	type Event = Event;235	type Proposal = Call;236}237238/// Used for the module template in `./template.rs`239impl template::Trait for Runtime {240	type Event = Event;241}242243construct_runtime!(244	pub enum Runtime where245		Block = Block,246		NodeBlock = opaque::Block,247		UncheckedExtrinsic = UncheckedExtrinsic248	{249		System: system::{Module, Call, Storage, Config, Event},250		Timestamp: timestamp::{Module, Call, Storage, Inherent},251		Aura: aura::{Module, Config<T>, Inherent(Timestamp)},252		Grandpa: grandpa::{Module, Call, Storage, Config, Event},253		Indices: indices,254		Balances: balances,255		TransactionPayment: transaction_payment::{Module, Storage},256		Sudo: sudo,257		// Used for the module template in `./template.rs`258		TemplateModule: template::{Module, Call, Storage, Event<T>},259		RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},260	}261);262263/// The address format for describing accounts.264pub type Address = <Indices as StaticLookup>::Source;265/// Block header type as expected by this runtime.266pub type Header = generic::Header<BlockNumber, BlakeTwo256>;267/// Block type as expected by this runtime.268pub type Block = generic::Block<Header, UncheckedExtrinsic>;269/// A Block signed with a Justification270pub type SignedBlock = generic::SignedBlock<Block>;271/// BlockId type as expected by this runtime.272pub type BlockId = generic::BlockId<Block>;273/// The SignedExtension to the basic transaction logic.274pub type SignedExtra = (275	system::CheckVersion<Runtime>,276	system::CheckGenesis<Runtime>,277	system::CheckEra<Runtime>,278	system::CheckNonce<Runtime>,279	system::CheckWeight<Runtime>,280	transaction_payment::ChargeTransactionPayment<Runtime>281);282/// Unchecked extrinsic type as expected by this runtime.283pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;284/// Extrinsic type that has already been checked.285pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;286/// Executive: handles dispatch to the various modules.287pub type Executive = frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;288289impl_runtime_apis! {290	impl sp_api::Core<Block> for Runtime {291		fn version() -> RuntimeVersion {292			VERSION293		}294295		fn execute_block(block: Block) {296			Executive::execute_block(block)297		}298299		fn initialize_block(header: &<Block as BlockT>::Header) {300			Executive::initialize_block(header)301		}302	}303304	impl sp_api::Metadata<Block> for Runtime {305		fn metadata() -> OpaqueMetadata {306			Runtime::metadata().into()307		}308	}309310	impl sp_block_builder::BlockBuilder<Block> for Runtime {311		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {312			Executive::apply_extrinsic(extrinsic)313		}314315		fn finalize_block() -> <Block as BlockT>::Header {316			Executive::finalize_block()317		}318319		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {320			data.create_extrinsics()321		}322323		fn check_inherents(324			block: Block,325			data: sp_inherents::InherentData,326		) -> sp_inherents::CheckInherentsResult {327			data.check_extrinsics(&block)328		}329330		fn random_seed() -> <Block as BlockT>::Hash {331			RandomnessCollectiveFlip::random_seed()332		}333	}334335	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {336		fn validate_transaction(tx: <Block as BlockT>::Extrinsic) -> TransactionValidity {337			Executive::validate_transaction(tx)338		}339	}340341	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {342		fn offchain_worker(number: NumberFor<Block>) {343			Executive::offchain_worker(number)344		}345	}346347	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {348		fn slot_duration() -> u64 {349			Aura::slot_duration()350		}351352		fn authorities() -> Vec<AuraId> {353			Aura::authorities()354		}355	}356357	impl sp_session::SessionKeys<Block> for Runtime {358		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {359			opaque::SessionKeys::generate(seed)360		}361	}362363	impl fg_primitives::GrandpaApi<Block> for Runtime {364		fn grandpa_authorities() -> GrandpaAuthorityList {365			Grandpa::grandpa_authorities()366		}367	}368}