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

difftreelog

source

runtime/src/lib.rs13.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, 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, 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;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;33// pub 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, traits::Randomness, weights::Weight, StorageValue,39};4041/// Importing a template pallet42pub use nft;4344/// An index to a block.45pub type BlockNumber = u32;4647/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.48pub type Signature = MultiSignature;4950/// Some way of identifying an account on the chain. We intentionally make it equivalent51/// to the public key of our transaction signing scheme.52pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;5354/// The type for looking up accounts. We don't expect more than 4 billion of them, but you55/// never know...56pub type AccountIndex = u32;5758/// Balance of an account.59pub type Balance = u128;6061/// Index of a transaction in the chain.62pub type Index = u32;6364/// A hash of some data used by the chain.65pub type Hash = sp_core::H256;6667/// Digest item type.68pub type DigestItem = generic::DigestItem<Hash>;6970pub const MILLICENTS: Balance = 1_000_000_000;71pub const CENTS: Balance = 1_000 * MILLICENTS;72pub const DOLLARS: Balance = 100 * CENTS;7374/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know75/// the specifics of the runtime. They can then be made to be agnostic over specific formats76/// of data like extrinsics, allowing for them to continue syncing the network through upgrades77/// to even the core data structures.78pub mod opaque {79	use super::*;8081	pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;8283	/// Opaque block header type.84	pub type Header = generic::Header<BlockNumber, BlakeTwo256>;85	/// Opaque block type.86	pub type Block = generic::Block<Header, UncheckedExtrinsic>;87	/// Opaque block identifier type.88	pub type BlockId = generic::BlockId<Block>;8990	impl_opaque_keys! {91		pub struct SessionKeys {92			pub aura: Aura,93			pub grandpa: Grandpa,94		}95	}96}9798/// This runtime version.99pub const VERSION: RuntimeVersion = RuntimeVersion {100    spec_name: create_runtime_str!("nft"),101    impl_name: create_runtime_str!("nft"),102	authoring_version: 1,103	spec_version: 1,104	impl_version: 1,105	apis: RUNTIME_API_VERSIONS,106	transaction_version: 1,107};108109pub const MILLISECS_PER_BLOCK: u64 = 6000;110111pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;112113// These time units are defined in number of blocks.114pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);115pub const HOURS: BlockNumber = MINUTES * 60;116pub const DAYS: BlockNumber = HOURS * 24;117118/// The version information used to identify this runtime when compiled natively.119#[cfg(feature = "std")]120pub fn native_version() -> NativeVersion {121	NativeVersion {122		runtime_version: VERSION,123		can_author_with: Default::default(),124	}125}126127parameter_types! {128	pub const BlockHashCount: BlockNumber = 2400;129	/// We allow for 2 seconds of compute with a 6 second average block time.130	// pub const MaximumBlockWeight: Weight = 2 * WEIGHT_PER_SECOND;131    pub const MaximumBlockWeight: Weight = 1_000_000_000;132	pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);133	/// Assume 10% of weight for average on_initialize calls.134	// pub MaximumExtrinsicWeight: Weight = AvailableBlockRatio::get()135	// 	.saturating_sub(Perbill::from_percent(10)) * MaximumBlockWeight::get();136	pub const MaximumBlockLength: u32 = 5 * 1024 * 1024;137	pub const Version: RuntimeVersion = VERSION;138}139140impl system::Trait for Runtime {141	/// The identifier used to distinguish between accounts.142	type AccountId = AccountId;143	/// The aggregated dispatch type that is available for extrinsics.144	type Call = Call;145	/// The lookup mechanism to get account ID from whatever is passed in dispatchers.146	type Lookup = IdentityLookup<AccountId>;147	/// The index type for storing how many extrinsics an account has signed.148	type Index = Index;149	/// The index type for blocks.150	type BlockNumber = BlockNumber;151	/// The type for hashing blocks and tries.152	type Hash = Hash;153	/// The hashing algorithm used.154	type Hashing = BlakeTwo256;155	/// The header type.156	type Header = generic::Header<BlockNumber, BlakeTwo256>;157	/// The ubiquitous event type.158	type Event = Event;159	/// The ubiquitous origin type.160	type Origin = Origin;161	/// Maximum number of block number to block hash mappings to keep (oldest pruned first).162	type BlockHashCount = BlockHashCount;163	/// Maximum weight of each block.164	type MaximumBlockWeight = MaximumBlockWeight;165	/// Maximum size of all encoded transactions (in bytes) that are allowed in one block.166	type MaximumBlockLength = MaximumBlockLength;167	/// Portion of the block weight that is available to all normal transactions.168	type AvailableBlockRatio = AvailableBlockRatio;169	/// Version of the runtime.170	type Version = Version;171	/// Converts a module to the index of the module in `construct_runtime!`.172	///173	/// This type is being generated by `construct_runtime!`.174	type ModuleToIndex = ModuleToIndex;175	/// What to do if a new account is created.176	type OnNewAccount = ();177	/// What to do if an account is fully reaped from the system.178	type OnKilledAccount = ();179	/// The data to be stored in an account.180	type AccountData = balances::AccountData<Balance>;181}182183impl aura::Trait for Runtime {184	type AuthorityId = AuraId;185}186187impl grandpa::Trait for Runtime {188	type Event = Event;189}190191parameter_types! {192	pub const MinimumPeriod: u64 = SLOT_DURATION / 2;193}194195impl timestamp::Trait for Runtime {196	/// A timestamp: milliseconds since the unix epoch.197	type Moment = u64;198	type OnTimestampSet = Aura;199	type MinimumPeriod = MinimumPeriod;200}201202impl contracts::Trait for Runtime {203    type Time = Timestamp;204    type Randomness = RandomnessCollectiveFlip;205    type Currency = Balances;206    type Event = Event;207    type DetermineContractAddress = contracts::SimpleAddressDeterminer<Runtime>;208    type TrieIdGenerator = contracts::TrieIdFromParentCounter<Runtime>;209    type RentPayment = ();210    type SignedClaimHandicap = contracts::DefaultSignedClaimHandicap;211    // type TombstoneDeposit = TombstoneDeposit;212    type StorageSizeOffset = contracts::DefaultStorageSizeOffset;213    // type RentByteFee = RentByteFee;214    // type RentDepositOffset = RentDepositOffset;215    // type SurchargeReward = SurchargeReward;216    type MaxDepth = contracts::DefaultMaxDepth;217    type MaxValueSize = contracts::DefaultMaxValueSize;218    // type WeightPrice = transaction_payment::Module<Self>;219}220221parameter_types! {222	pub const ExistentialDeposit: u128 = 500;223}224225impl balances::Trait for Runtime {226	/// The type for recording an account's balance.227	type Balance = Balance;228	/// The ubiquitous event type.229	type Event = Event;230	type DustRemoval = ();231	type ExistentialDeposit = ExistentialDeposit;232	type AccountStore = System;233}234235parameter_types! {236	pub const TransactionBaseFee: Balance = 0;237	pub const TransactionByteFee: Balance = 1;238}239240impl transaction_payment::Trait for Runtime {241	type Currency = balances::Module<Runtime>;242	type OnTransactionPayment = ();243	type TransactionBaseFee = TransactionBaseFee;244	type TransactionByteFee = TransactionByteFee;245	type WeightToFee = ConvertInto;246	type FeeMultiplierUpdate = ();247}248249impl sudo::Trait for Runtime {250	type Event = Event;251	type Call = Call;252}253254/// Used for the module template in `./template.rs`255impl nft::Trait for Runtime {256	type Event = Event;257}258259construct_runtime!(260	pub enum Runtime where261		Block = Block,262		NodeBlock = opaque::Block,263		UncheckedExtrinsic = UncheckedExtrinsic264	{265		System: system::{Module, Call, Config, Storage, Event<T>},266		RandomnessCollectiveFlip: randomness_collective_flip::{Module, Call, Storage},267		Contracts: contracts::{Module, Call, Config, Storage, Event<T>},268		Timestamp: timestamp::{Module, Call, Storage, Inherent},269		Aura: aura::{Module, Config<T>, Inherent(Timestamp)},270		Grandpa: grandpa::{Module, Call, Storage, Config, Event},271		Balances: balances::{Module, Call, Storage, Config<T>, Event<T>},272		TransactionPayment: transaction_payment::{Module, Storage},273		Sudo: sudo::{Module, Call, Config<T>, Storage, Event<T>},274		// Used for the module template in `./template.rs`275		Nft: nft::{Module, Call, Storage, Event<T>},276	}277);278279/// The address format for describing accounts.280pub type Address = AccountId;281/// Block header type as expected by this runtime.282pub type Header = generic::Header<BlockNumber, BlakeTwo256>;283/// Block type as expected by this runtime.284pub type Block = generic::Block<Header, UncheckedExtrinsic>;285/// A Block signed with a Justification286pub type SignedBlock = generic::SignedBlock<Block>;287/// BlockId type as expected by this runtime.288pub type BlockId = generic::BlockId<Block>;289/// The SignedExtension to the basic transaction logic.290pub type SignedExtra = (291	system::CheckVersion<Runtime>,292	system::CheckGenesis<Runtime>,293	system::CheckEra<Runtime>,294	system::CheckNonce<Runtime>,295	system::CheckWeight<Runtime>,296	transaction_payment::ChargeTransactionPayment<Runtime>297);298/// Unchecked extrinsic type as expected by this runtime.299pub type UncheckedExtrinsic = generic::UncheckedExtrinsic<Address, Call, Signature, SignedExtra>;300/// Extrinsic type that has already been checked.301pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, Call, SignedExtra>;302/// Executive: handles dispatch to the various modules.303pub type Executive = frame_executive::Executive<Runtime, Block, system::ChainContext<Runtime>, Runtime, AllModules>;304305impl_runtime_apis! {306	impl sp_api::Core<Block> for Runtime {307		fn version() -> RuntimeVersion {308			VERSION309		}310311		fn execute_block(block: Block) {312			Executive::execute_block(block)313		}314315		fn initialize_block(header: &<Block as BlockT>::Header) {316			Executive::initialize_block(header)317		}318	}319320	impl sp_api::Metadata<Block> for Runtime {321		fn metadata() -> OpaqueMetadata {322			Runtime::metadata().into()323		}324	}325326	impl sp_block_builder::BlockBuilder<Block> for Runtime {327		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {328			Executive::apply_extrinsic(extrinsic)329		}330331		fn finalize_block() -> <Block as BlockT>::Header {332			Executive::finalize_block()333		}334335		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {336			data.create_extrinsics()337		}338339		fn check_inherents(340			block: Block,341			data: sp_inherents::InherentData,342		) -> sp_inherents::CheckInherentsResult {343			data.check_extrinsics(&block)344		}345346		fn random_seed() -> <Block as BlockT>::Hash {347			RandomnessCollectiveFlip::random_seed()348		}349	}350351	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {352		fn validate_transaction(353			source: TransactionSource,354			tx: <Block as BlockT>::Extrinsic,355		) -> TransactionValidity {356			Executive::validate_transaction(source, tx)357		}358	}359360	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {361		fn offchain_worker(header: &<Block as BlockT>::Header) {362			Executive::offchain_worker(header)363		}364	}365366	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {367		fn slot_duration() -> u64 {368			Aura::slot_duration()369		}370371		fn authorities() -> Vec<AuraId> {372			Aura::authorities()373		}374	}375376	impl sp_session::SessionKeys<Block> for Runtime {377		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {378			opaque::SessionKeys::generate(seed)379		}380381		fn decode_session_keys(382			encoded: Vec<u8>,383		) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {384			opaque::SessionKeys::decode_into_raw_public_keys(&encoded)385		}386	}387388	impl fg_primitives::GrandpaApi<Block> for Runtime {389		fn grandpa_authorities() -> GrandpaAuthorityList {390			Grandpa::grandpa_authorities()391		}392	}393394	impl contracts_rpc_runtime_api::ContractsApi<Block, AccountId, Balance, BlockNumber>395	for Runtime396	{397		fn call(398			origin: AccountId,399			dest: AccountId,400			value: Balance,401			gas_limit: u64,402			input_data: Vec<u8>,403		) -> ContractExecResult {404			let exec_result =405				Contracts::bare_call(origin, dest.into(), value, gas_limit, input_data);406			match exec_result {407				Ok(v) => ContractExecResult::Success {408					status: v.status,409					data: v.data,410				},411				Err(_) => ContractExecResult::Error,412			}413		}414415		fn get_storage(416			address: AccountId,417			key: [u8; 32],418		) -> contracts_primitives::GetStorageResult {419			Contracts::get_storage(address, key)420		}421422		fn rent_projection(423			address: AccountId,424		) -> contracts_primitives::RentProjectionResult<BlockNumber> {425			Contracts::rent_projection(address)426		}427	}428429}