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

difftreelog

source

runtime/src/lib.rs15.4 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::{crypto::KeyTypeId, OpaqueMetadata};13use sp_runtime::{14	ApplyExtrinsicResult, generic, create_runtime_str, impl_opaque_keys, MultiSignature,15	transaction_validity::{TransactionValidity, TransactionSource},16};17use sp_runtime::traits::{18	BlakeTwo256, Block as BlockT, IdentityLookup, Verify, IdentifyAccount, NumberFor, Saturating,19};20use sp_api::impl_runtime_apis;21use sp_consensus_aura::sr25519::AuthorityId as AuraId;22use grandpa::{AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList};23use grandpa::fg_primitives;24use sp_version::RuntimeVersion;25#[cfg(feature = "std")]26use sp_version::NativeVersion;27use contracts_rpc_runtime_api::ContractExecResult;2829// A few exports that help ease life for downstream crates.30#[cfg(any(feature = "std", test))]31pub use sp_runtime::BuildStorage;32pub use timestamp::Call as TimestampCall;33pub use staking::Call as StakingCall;34pub use balances::Call as BalancesCall;35pub use sp_runtime::{Permill, Perbill};36pub use contracts::Schedule as ContractsSchedule;37pub use frame_support::{38	construct_runtime, parameter_types, StorageValue,39	traits::{KeyOwnerProofSystem, Randomness},40	weights::{41		Weight, IdentityFee,42		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},43	},44};4546/// Importing a template pallet47pub use nft;4849/// An index to a block.50pub type BlockNumber = u32;5152/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.53pub type Signature = MultiSignature;5455/// Some way of identifying an account on the chain. We intentionally make it equivalent56/// to the public key of our transaction signing scheme.57pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5859/// The type for looking up accounts. We don't expect more than 4 billion of them, but you60/// never know...61pub type AccountIndex = u32;6263/// Balance of an account.64pub type Balance = u128;6566/// Index of a transaction in the chain.67pub type Index = u32;6869/// A hash of some data used by the chain.70pub type Hash = sp_core::H256;7172/// Digest item type.73pub type DigestItem = generic::DigestItem<Hash>;7475pub const MILLICENTS: Balance = 1_000_000_000;76pub const CENTS: Balance = 1_000 * MILLICENTS;77pub const DOLLARS: Balance = 100 * CENTS;7879/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know80/// the specifics of the runtime. They can then be made to be agnostic over specific formats81/// of data like extrinsics, allowing for them to continue syncing the network through upgrades82/// to even the core data structures.83pub mod opaque {84	use super::*;8586	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;8788	/// Opaque block header type.89	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;90	/// Opaque block type.91	pub type Block = generic::Block<Header, UncheckedExtrinsic>;92	/// Opaque block identifier type.93	pub type BlockId = generic::BlockId<Block>;9495	impl_opaque_keys! {96		pub struct SessionKeys {97			pub aura: Aura,98			pub grandpa: Grandpa,99		}100	}101}102103/// This runtime version.104pub const VERSION: RuntimeVersion = RuntimeVersion {105    spec_name: create_runtime_str!("nft"),106    impl_name: create_runtime_str!("nft"),107	authoring_version: 1,108	spec_version: 1,109	impl_version: 1,110	apis: RUNTIME_API_VERSIONS,111	transaction_version: 1,112};113114pub const MILLISECS_PER_BLOCK: u64 = 6000;115116pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;117118// These time units are defined in number of blocks.119pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);120pub const HOURS: BlockNumber = MINUTES * 60;121pub const DAYS: BlockNumber = HOURS * 24;122123/// The version information used to identify this runtime when compiled natively.124#[cfg(feature = "std")]125pub fn native_version() -> NativeVersion {126	NativeVersion {127		runtime_version: VERSION,128		can_author_with: Default::default(),129	}130}131132parameter_types! {133	pub const BlockHashCount: BlockNumber = 2400;134	/// We allow for 2 seconds of compute with a 6 second average block time.135	pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;136	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);137	/// Assume 10% of weight for average on_initialize calls.138	pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()139		.saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();140	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;141	pub const Version: RuntimeVersion = VERSION;142}143144impl system::Trait for Runtime {145	/// The basic call filter to use in dispatchable.146	type BaseCallFilter = ();147	/// The identifier used to distinguish between accounts.148	type AccountId = AccountId;149	/// The aggregated dispatch type that is available for extrinsics.150	type Call = Call;151	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.152	type Lookup = IdentityLookup<AccountId>;153	/// The index type for storing how many extrinsics an account has signed.154	type Index = Index;155	/// The index type for blocks.156	type BlockNumber = BlockNumber;157	/// The type for hashing blocks and tries.158	type Hash = Hash;159	/// The hashing algorithm used.160	type Hashing = BlakeTwo256;161	/// The header type.162	type Header = generic::Header<BlockNumber, BlakeTwo256>;163	/// The ubiquitous event type.164	type Event = Event;165	/// The ubiquitous origin type.166	type Origin = Origin;167	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).168	type BlockHashCount = BlockHashCount;169	/// Maximum weight of each block.170	type MaximumBlockWeight = MaximumBlockWeight;171	/// The weight of database operations that the runtime can invoke.172	type DbWeight = RocksDbWeight;173	/// The weight of the overhead invoked on the block import process, independent of the174	/// extrinsics included in that block.175	type BlockExecutionWeight = BlockExecutionWeight;176	/// The base weight of any extrinsic processed by the runtime, independent of the177	/// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)178	type ExtrinsicBaseWeight = ExtrinsicBaseWeight;179	/// The maximum weight that a single extrinsic of `Normal` dispatch class can have,180	/// idependent of the logic of that extrinsics. (Roughly max block weight - average on181	/// initialize cost).182	type MaximumExtrinsicWeight = MaximumExtrinsicWeight;183	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.184	type MaximumBlockLength = MaximumBlockLength;185	/// Portion of the block weight that is available to all normal transactions.186	type AvailableBlockRatio = AvailableBlockRatio;187	/// Version of the runtime.188	type Version = Version;189	/// Converts a module to the index of the module in `construct_runtime!`.190	///191	/// This type is being generated by `construct_runtime!`.192	type ModuleToIndex = ModuleToIndex;193	/// What to do if a new account is created.194	type OnNewAccount = ();195	/// What to do if an account is fully reaped from the system.196	type OnKilledAccount = ();197	/// The data to be stored in an account.198	type AccountData = balances::AccountData<Balance>;199}200201impl aura::Trait for Runtime {202	type AuthorityId = AuraId;203}204205impl grandpa::Trait for Runtime {206	type Event = Event;207	type Call = Call;208209	type KeyOwnerProofSystem = ();210211	type KeyOwnerProof =212		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;213214	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(215		KeyTypeId,216		GrandpaId,217	)>>::IdentificationTuple;218219	type HandleEquivocation = ();220}221222parameter_types! {223	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;224}225226impl timestamp::Trait for Runtime {227	/// A timestamp: milliseconds since the unix epoch.228	type Moment = u64;229	type OnTimestampSet = Aura;230	type MinimumPeriod = MinimumPeriod;231}232233234parameter_types! {235    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;236    pub const RentByteFee: Balance = 4 * MILLICENTS;237    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;238    pub const SurchargeReward: Balance = 150 * MILLICENTS;239}240241impl contracts::Trait for Runtime {242    type Time = Timestamp;243    type Randomness = RandomnessCollectiveFlip;244    type Currency = Balances;245    type Event = Event;246    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;247    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;248    type RentPayment = ();249    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;250    type TombstoneDeposit = TombstoneDeposit;251    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;252    type RentByteFee = RentByteFee;253    type RentDepositOffset = RentDepositOffset;254    type SurchargeReward = SurchargeReward;255    type MaxDepth = contracts::DefaultMaxDepth;256    type MaxValueSize = contracts::DefaultMaxValueSize;257    type WeightPrice = transaction_payment::Module<Self>;258}259260parameter_types! {261	pub const ExistentialDeposit: u128 = 500;262}263264impl balances::Trait for Runtime {265	/// The type for recording an account's balance.266	type Balance = Balance;267	/// The ubiquitous event type.268	type Event = Event;269	type DustRemoval = ();270	type ExistentialDeposit = ExistentialDeposit;271	type AccountStore = System;272}273274parameter_types! {275	pub const TransactionByteFee: Balance = 1;276}277278impl transaction_payment::Trait for Runtime {279	type Currency = balances::Module<Runtime>;280	type OnTransactionPayment = ();281	type TransactionByteFee = TransactionByteFee;282	type WeightToFee = IdentityFee<Balance>;283	type FeeMultiplierUpdate = ();284}285286impl sudo::Trait for Runtime {287	type Event = Event;288	type Call = Call;289}290291/// Used for the module template in `./template.rs`292impl nft::Trait for Runtime {293    type Event = Event;294}295296construct_runtime!(297	pub enum Runtime where298		Block = Block,299		NodeBlock = opaque::Block,300		UncheckedExtrinsic = UncheckedExtrinsic301	{302		System: system::{Module, Call, Config, Storage, Event<T>},303		RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},304		Contracts: contracts::{Module, Call, Config, Storage, Event<T>},305		Timestamp: timestamp::{Module, Call, Storage, Inherent},306		Aura: aura::{Module, Config<T>, Inherent(Timestamp)},307		Grandpa: grandpa::{Module, Call, Storage, Config, Event},308		Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},309		TransactionPayment: transaction_payment::{Module, Storage},310		Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},311		// Staking: staking::{Module, Call, Config<T>, Storage, Event<T>},312		// Used for the module template in `./template.rs`313        Nft: nft::{Module, Call, Storage, Event<T>},314	}315);316317/// The address format for describing accounts.318pub type Address = AccountId;319/// Block header type as expected by this runtime.320pub type Header = generic::Header<BlockNumber, BlakeTwo256>;321/// Block type as expected by this runtime.322pub type Block = generic::Block<Header, UncheckedExtrinsic>;323/// A Block signed with a Justification324pub type SignedBlock = generic::SignedBlock<Block>;325/// BlockId type as expected by this runtime.326pub type BlockId = generic::BlockId<Block>;327/// The SignedExtension to the basic transaction logic.328pub type SignedExtra = (329	system::CheckSpecVersion<Runtime>,330	system::CheckTxVersion<Runtime>,331	system::CheckGenesis<Runtime>,332	system::CheckEra<Runtime>,333	system::CheckNonce<Runtime>,334	system::CheckWeight<Runtime>,335	transaction_payment::ChargeTransactionPayment<Runtime>336);337/// Unchecked extrinsic type as expected by this runtime.338pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;339/// Extrinsic type that has already been checked.340pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;341/// Executive: handles dispatch to the various modules.342pub type Executive = frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;343344impl_runtime_apis! {345	impl sp_api::Core<Block> for Runtime {346		fn version() -> RuntimeVersion {347			VERSION348		}349350		fn execute_block(block: Block) {351			Executive::execute_block(block)352		}353354		fn initialize_block(header: &<Block as BlockT>::Header) {355			Executive::initialize_block(header)356		}357	}358359	impl sp_api::Metadata<Block> for Runtime {360		fn metadata() -> OpaqueMetadata {361			Runtime::metadata().into()362		}363	}364365	impl sp_block_builder::BlockBuilder<Block> for Runtime {366		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {367			Executive::apply_extrinsic(extrinsic)368		}369370		fn finalize_block() -> <Block as BlockT>::Header {371			Executive::finalize_block()372		}373374		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {375			data.create_extrinsics()376		}377378		fn check_inherents(379			block: Block,380			data: sp_inherents::InherentData,381		) -> sp_inherents::CheckInherentsResult {382			data.check_extrinsics(&block)383		}384385		fn random_seed() -> <Block as BlockT>::Hash {386			RandomnessCollectiveFlip::random_seed()387		}388	}389390	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {391		fn validate_transaction(392			source: TransactionSource,393			tx: <Block as BlockT>::Extrinsic,394		) -> TransactionValidity {395			Executive::validate_transaction(source, tx)396		}397	}398399	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {400		fn offchain_worker(header: &<Block as BlockT>::Header) {401			Executive::offchain_worker(header)402		}403	}404405	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {406		fn slot_duration() -> u64 {407			Aura::slot_duration()408		}409410		fn authorities() -> Vec<AuraId> {411			Aura::authorities()412		}413	}414415	impl sp_session::SessionKeys<Block> for Runtime {416		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {417			opaque::SessionKeys::generate(seed)418		}419420		fn decode_session_keys(421			encoded: Vec<u8>,422		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {423			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)424		}425	}426427	impl fg_primitives::GrandpaApi<Block> for Runtime {428		fn grandpa_authorities() -> GrandpaAuthorityList {429			Grandpa::grandpa_authorities()430		}431432		fn submit_report_equivocation_extrinsic(433			_equivocation_proof: fg_primitives::EquivocationProof<434				<Block as BlockT>::Hash,435				NumberFor<Block>,436			>,437			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,438		) -> Option<()> {439			None440		}441442		fn generate_key_ownership_proof(443			_set_id: fg_primitives::SetId,444			_authority_id: GrandpaId,445		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {446			// NOTE: this is the only implementation possible since we've447			// defined our key owner proof type as a bottom type (i.e. a type448			// with no values).449			None450		}451	}452453	impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>454	for Runtime455	{456		fn call(457			origin: AccountId,458			dest: AccountId,459			value: Balance,460			gas_limit: u64,461			input_data: Vec<u8>,462		) -> ContractExecResult {463			let exec_result =464				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);465			match exec_result {466				Ok(v) => ContractExecResult::Success {467					status: v.status,468					data: v.data,469				},470				Err(_) => ContractExecResult::Error,471			}472		}473474		fn get_storage(475			address: AccountId,476			key: [u8; 32],477		) -> contracts_primitives::GetStorageResult {478			Contracts::get_storage(address, key)479		}480481		fn rent_projection(482			address: AccountId,483		) -> contracts_primitives::RentProjectionResult<BlockNumber> {484			Contracts::rent_projection(address)485		}486	}487488}