git.delta.rocks / unique-network / refs/commits / 89d693c101e5

difftreelog

source

runtime/src/lib.rs15.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::{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 balances::Call as BalancesCall;34pub use sp_runtime::{Permill, Perbill};35pub use contracts::Schedule as ContractsSchedule;36pub use frame_support::{37	construct_runtime, parameter_types, StorageValue,38	traits::{KeyOwnerProofSystem, Randomness},39	weights::{40		Weight, IdentityFee,41		constants::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_PER_SECOND},42	},43};4445/// Importing a template pallet46pub use nft;4748/// An index to a block.49pub type BlockNumber = u32;5051/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.52pub type Signature = MultiSignature;5354/// Some way of identifying an account on the chain. We intentionally make it equivalent55/// to the public key of our transaction signing scheme.56pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5758/// The type for looking up accounts. We don't expect more than 4 billion of them, but you59/// never know...60pub type AccountIndex = u32;6162/// Balance of an account.63pub type Balance = u128;6465/// Index of a transaction in the chain.66pub type Index = u32;6768/// A hash of some data used by the chain.69pub type Hash = sp_core::H256;7071/// Digest item type.72pub type DigestItem = generic::DigestItem<Hash>;7374pub const MILLICENTS: Balance = 1_000_000_000;75pub const CENTS: Balance = 1_000 * MILLICENTS;76pub const DOLLARS: Balance = 100 * CENTS;7778/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know79/// the specifics of the runtime. They can then be made to be agnostic over specific formats80/// of data like extrinsics, allowing for them to continue syncing the network through upgrades81/// to even the core data structures.82pub mod opaque {83	use super::*;8485	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;8687	/// Opaque block header type.88	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;89	/// Opaque block type.90	pub type Block = generic::Block<Header, UncheckedExtrinsic>;91	/// Opaque block identifier type.92	pub type BlockId = generic::BlockId<Block>;9394	impl_opaque_keys! {95		pub struct SessionKeys {96			pub aura: Aura,97			pub grandpa: Grandpa,98		}99	}100}101102/// This runtime version.103pub const VERSION: RuntimeVersion = RuntimeVersion {104    spec_name: create_runtime_str!("nft"),105    impl_name: create_runtime_str!("nft"),106	authoring_version: 1,107	spec_version: 1,108	impl_version: 1,109	apis: RUNTIME_API_VERSIONS,110	transaction_version: 1,111};112113pub const MILLISECS_PER_BLOCK: u64 = 6000;114115pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;116117// These time units are defined in number of blocks.118pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);119pub const HOURS: BlockNumber = MINUTES * 60;120pub const DAYS: BlockNumber = HOURS * 24;121122/// The version information used to identify this runtime when compiled natively.123#[cfg(feature = "std")]124pub fn native_version() -> NativeVersion {125	NativeVersion {126		runtime_version: VERSION,127		can_author_with: Default::default(),128	}129}130131parameter_types! {132	pub const BlockHashCount: BlockNumber = 2400;133	/// We allow for 2 seconds of compute with a 6 second average block time.134	pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;135	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);136	/// Assume 10% of weight for average on_initialize calls.137	pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()138		.saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();139	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;140	pub const Version: RuntimeVersion = VERSION;141}142143impl system::Trait for Runtime {144	/// The basic call filter to use in dispatchable.145	type BaseCallFilter = ();146	/// The identifier used to distinguish between accounts.147	type AccountId = AccountId;148	/// The aggregated dispatch type that is available for extrinsics.149	type Call = Call;150	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.151	type Lookup = IdentityLookup<AccountId>;152	/// The index type for storing how many extrinsics an account has signed.153	type Index = Index;154	/// The index type for blocks.155	type BlockNumber = BlockNumber;156	/// The type for hashing blocks and tries.157	type Hash = Hash;158	/// The hashing algorithm used.159	type Hashing = BlakeTwo256;160	/// The header type.161	type Header = generic::Header<BlockNumber, BlakeTwo256>;162	/// The ubiquitous event type.163	type Event = Event;164	/// The ubiquitous origin type.165	type Origin = Origin;166	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).167	type BlockHashCount = BlockHashCount;168	/// Maximum weight of each block.169	type MaximumBlockWeight = MaximumBlockWeight;170	/// The weight of database operations that the runtime can invoke.171	type DbWeight = RocksDbWeight;172	/// The weight of the overhead invoked on the block import process, independent of the173	/// extrinsics included in that block.174	type BlockExecutionWeight = BlockExecutionWeight;175	/// The base weight of any extrinsic processed by the runtime, independent of the176	/// logic of that extrinsic. (Signature verification, nonce increment, fee, etc...)177	type ExtrinsicBaseWeight = ExtrinsicBaseWeight;178	/// The maximum weight that a single extrinsic of `Normal` dispatch class can have,179	/// idependent of the logic of that extrinsics. (Roughly max block weight - average on180	/// initialize cost).181	type MaximumExtrinsicWeight = MaximumExtrinsicWeight;182	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.183	type MaximumBlockLength = MaximumBlockLength;184	/// Portion of the block weight that is available to all normal transactions.185	type AvailableBlockRatio = AvailableBlockRatio;186	/// Version of the runtime.187	type Version = Version;188	/// Converts a module to the index of the module in `construct_runtime!`.189	///190	/// This type is being generated by `construct_runtime!`.191	type ModuleToIndex = ModuleToIndex;192	/// What to do if a new account is created.193	type OnNewAccount = ();194	/// What to do if an account is fully reaped from the system.195	type OnKilledAccount = ();196	/// The data to be stored in an account.197	type AccountData = balances::AccountData<Balance>;198}199200impl aura::Trait for Runtime {201	type AuthorityId = AuraId;202}203204impl grandpa::Trait for Runtime {205	type Event = Event;206	type Call = Call;207208	type KeyOwnerProofSystem = ();209210	type KeyOwnerProof =211		<Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(KeyTypeId, GrandpaId)>>::Proof;212213	type KeyOwnerIdentification = <Self::KeyOwnerProofSystem as KeyOwnerProofSystem<(214		KeyTypeId,215		GrandpaId,216	)>>::IdentificationTuple;217218	type HandleEquivocation = ();219}220221parameter_types! {222	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;223}224225impl timestamp::Trait for Runtime {226	/// A timestamp: milliseconds since the unix epoch.227	type Moment = u64;228	type OnTimestampSet = Aura;229	type MinimumPeriod = MinimumPeriod;230}231232parameter_types! {233	pub const ExistentialDeposit: u128 = 500;234}235236impl balances::Trait for Runtime {237	/// The type for recording an account's balance.238	type Balance = Balance;239	/// The ubiquitous event type.240	type Event = Event;241	type DustRemoval = ();242	type ExistentialDeposit = ExistentialDeposit;243	type AccountStore = System;244}245246parameter_types! {247	pub const TransactionByteFee: Balance = 1;248}249250impl transaction_payment::Trait for Runtime {251	type Currency = balances::Module<Runtime>;252	type OnTransactionPayment = ();253	type TransactionByteFee = TransactionByteFee;254	type WeightToFee = IdentityFee<Balance>;255	type FeeMultiplierUpdate = ();256}257258impl sudo::Trait for Runtime {259	type Event = Event;260	type Call = Call;261}262263parameter_types! {264    pub const TombstoneDeposit: Balance = 16 * MILLICENTS;265    pub const RentByteFee: Balance = 4 * MILLICENTS;266    pub const RentDepositOffset: Balance = 1000 * MILLICENTS;267    pub const SurchargeReward: Balance = 150 * MILLICENTS;268}269270impl contracts::Trait for Runtime {271    type Time = Timestamp;272    type Randomness = RandomnessCollectiveFlip;273    type Currency = Balances;274    type Event = Event;275    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;276    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;277    type RentPayment = ();278    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;279    type TombstoneDeposit = TombstoneDeposit;280    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;281    type RentByteFee = RentByteFee;282    type RentDepositOffset = RentDepositOffset;283    type SurchargeReward = SurchargeReward;284    type MaxDepth = contracts::DefaultMaxDepth;285    type MaxValueSize = contracts::DefaultMaxValueSize;286    type WeightPrice = transaction_payment::Module<Self>;287}288289/// Used for the module template in `./template.rs`290impl nft::Trait for Runtime {291    type Event = Event;292}293294construct_runtime!(295	pub enum Runtime where296		Block = Block,297		NodeBlock = opaque::Block,298		UncheckedExtrinsic = UncheckedExtrinsic299	{300		System: system::{Module, Call, Config, Storage, Event<T>},301		RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},302		Contracts: contracts::{Module, Call, Config, Storage, Event<T>},303		Timestamp: timestamp::{Module, Call, Storage, Inherent},304		Aura: aura::{Module, Config<T>, Inherent(Timestamp)},305		Grandpa: grandpa::{Module, Call, Storage, Config, Event},306		Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},307		TransactionPayment: transaction_payment::{Module, Storage},308		Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},309		// Used for the module template in `./template.rs`310        Nft: nft::{Module, Call, Storage, Event<T>},311	}312);313314/// The address format for describing accounts.315pub type Address = AccountId;316/// Block header type as expected by this runtime.317pub type Header = generic::Header<BlockNumber, BlakeTwo256>;318/// Block type as expected by this runtime.319pub type Block = generic::Block<Header, UncheckedExtrinsic>;320/// A Block signed with a Justification321pub type SignedBlock = generic::SignedBlock<Block>;322/// BlockId type as expected by this runtime.323pub type BlockId = generic::BlockId<Block>;324/// The SignedExtension to the basic transaction logic.325pub type SignedExtra = (326	system::CheckSpecVersion<Runtime>,327	system::CheckTxVersion<Runtime>,328	system::CheckGenesis<Runtime>,329	system::CheckEra<Runtime>,330	system::CheckNonce<Runtime>,331	system::CheckWeight<Runtime>,332	transaction_payment::ChargeTransactionPayment<Runtime>333);334/// Unchecked extrinsic type as expected by this runtime.335pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;336/// Extrinsic type that has already been checked.337pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;338/// Executive: handles dispatch to the various modules.339pub type Executive = frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;340341impl_runtime_apis! {342	impl sp_api::Core<Block> for Runtime {343		fn version() -> RuntimeVersion {344			VERSION345		}346347		fn execute_block(block: Block) {348			Executive::execute_block(block)349		}350351		fn initialize_block(header: &<Block as BlockT>::Header) {352			Executive::initialize_block(header)353		}354	}355356	impl sp_api::Metadata<Block> for Runtime {357		fn metadata() -> OpaqueMetadata {358			Runtime::metadata().into()359		}360	}361362	impl sp_block_builder::BlockBuilder<Block> for Runtime {363		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {364			Executive::apply_extrinsic(extrinsic)365		}366367		fn finalize_block() -> <Block as BlockT>::Header {368			Executive::finalize_block()369		}370371		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {372			data.create_extrinsics()373		}374375		fn check_inherents(376			block: Block,377			data: sp_inherents::InherentData,378		) -> sp_inherents::CheckInherentsResult {379			data.check_extrinsics(&block)380		}381382		fn random_seed() -> <Block as BlockT>::Hash {383			RandomnessCollectiveFlip::random_seed()384		}385	}386387	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {388		fn validate_transaction(389			source: TransactionSource,390			tx: <Block as BlockT>::Extrinsic,391		) -> TransactionValidity {392			Executive::validate_transaction(source, tx)393		}394	}395396	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {397		fn offchain_worker(header: &<Block as BlockT>::Header) {398			Executive::offchain_worker(header)399		}400	}401402	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {403		fn slot_duration() -> u64 {404			Aura::slot_duration()405		}406407		fn authorities() -> Vec<AuraId> {408			Aura::authorities()409		}410	}411412	impl sp_session::SessionKeys<Block> for Runtime {413		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {414			opaque::SessionKeys::generate(seed)415		}416417		fn decode_session_keys(418			encoded: Vec<u8>,419		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {420			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)421		}422	}423424	impl fg_primitives::GrandpaApi<Block> for Runtime {425		fn grandpa_authorities() -> GrandpaAuthorityList {426			Grandpa::grandpa_authorities()427		}428429		fn submit_report_equivocation_extrinsic(430			_equivocation_proof: fg_primitives::EquivocationProof<431				<Block as BlockT>::Hash,432				NumberFor<Block>,433			>,434			_key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof,435		) -> Option<()> {436			None437		}438439		fn generate_key_ownership_proof(440			_set_id: fg_primitives::SetId,441			_authority_id: GrandpaId,442		) -> Option<fg_primitives::OpaqueKeyOwnershipProof> {443			// NOTE: this is the only implementation possible since we've444			// defined our key owner proof type as a bottom type (i.e. a type445			// with no values).446			None447		}448	}449450	impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>451	for Runtime452	{453		fn call(454			origin: AccountId,455			dest: AccountId,456			value: Balance,457			gas_limit: u64,458			input_data: Vec<u8>,459		) -> ContractExecResult {460			let exec_result =461				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);462			match exec_result {463				Ok(v) => ContractExecResult::Success {464					status: v.status,465					data: v.data,466				},467				Err(_) => ContractExecResult::Error,468			}469		}470471		fn get_storage(472			address: AccountId,473			key: [u8; 32],474		) -> contracts_primitives::GetStorageResult {475			Contracts::get_storage(address, key)476		}477478		fn rent_projection(479			address: AccountId,480		) -> contracts_primitives::RentProjectionResult<BlockNumber> {481			Contracts::rent_projection(address)482		}483	}484485}