referrerpolicy=no-referrer-when-downgrade

polkadot_sdk_docs_first_runtime/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Runtime used in `your_first_runtime`.
19
20#![cfg_attr(not(feature = "std"), no_std)]
21
22extern crate alloc;
23use alloc::{vec, vec::Vec};
24use first_pallet::pallet_v2 as our_first_pallet;
25use frame::{
26	prelude::*,
27	runtime::{apis, prelude::*},
28};
29use pallet_transaction_payment_rpc_runtime_api::{FeeDetails, RuntimeDispatchInfo};
30
31#[docify::export]
32#[runtime_version]
33pub const VERSION: RuntimeVersion = RuntimeVersion {
34	spec_name: alloc::borrow::Cow::Borrowed("first-runtime"),
35	impl_name: alloc::borrow::Cow::Borrowed("first-runtime"),
36	authoring_version: 1,
37	spec_version: 0,
38	impl_version: 1,
39	apis: RUNTIME_API_VERSIONS,
40	transaction_version: 1,
41	system_version: 1,
42};
43
44#[docify::export(cr)]
45construct_runtime!(
46	pub struct Runtime {
47		// Mandatory for all runtimes
48		System: frame_system,
49
50		// A number of other pallets from FRAME.
51		Timestamp: pallet_timestamp,
52		Balances: pallet_balances,
53		Sudo: pallet_sudo,
54		TransactionPayment: pallet_transaction_payment,
55
56		// Our local pallet
57		FirstPallet: our_first_pallet,
58	}
59);
60
61#[docify::export_content]
62mod runtime_types {
63	use super::*;
64	pub(super) type SignedExtra = (
65		// `frame` already provides all the signed extensions from `frame-system`. We just add the
66		// one related to tx-payment here.
67		frame::runtime::types_common::SystemTransactionExtensionsOf<Runtime>,
68		pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
69	);
70
71	pub(super) type Block = frame::runtime::types_common::BlockOf<Runtime, SignedExtra>;
72	pub(super) type Header = HeaderFor<Runtime>;
73
74	pub(super) type RuntimeExecutive = Executive<
75		Runtime,
76		Block,
77		frame_system::ChainContext<Runtime>,
78		Runtime,
79		AllPalletsWithSystem,
80	>;
81}
82use runtime_types::*;
83
84#[docify::export_content]
85mod config_impls {
86	use super::*;
87
88	parameter_types! {
89		pub const Version: RuntimeVersion = VERSION;
90	}
91
92	#[derive_impl(frame_system::config_preludes::SolochainDefaultConfig)]
93	impl frame_system::Config for Runtime {
94		type Block = Block;
95		type Version = Version;
96		type AccountData =
97			pallet_balances::AccountData<<Runtime as pallet_balances::Config>::Balance>;
98	}
99
100	#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
101	impl pallet_balances::Config for Runtime {
102		type AccountStore = System;
103	}
104
105	#[derive_impl(pallet_sudo::config_preludes::TestDefaultConfig)]
106	impl pallet_sudo::Config for Runtime {}
107
108	#[derive_impl(pallet_timestamp::config_preludes::TestDefaultConfig)]
109	impl pallet_timestamp::Config for Runtime {}
110
111	#[derive_impl(pallet_transaction_payment::config_preludes::TestDefaultConfig)]
112	impl pallet_transaction_payment::Config for Runtime {
113		type OnChargeTransaction = pallet_transaction_payment::FungibleAdapter<Balances, ()>;
114		// We specify a fixed length to fee here, which essentially means all transactions charge
115		// exactly 1 unit of fee.
116		type LengthToFee = FixedFee<1, <Self as pallet_balances::Config>::Balance>;
117		type WeightToFee = NoFee<<Self as pallet_balances::Config>::Balance>;
118	}
119}
120
121#[docify::export(our_config_impl)]
122impl our_first_pallet::Config for Runtime {
123	type RuntimeEvent = RuntimeEvent;
124}
125
126/// Provides getters for genesis configuration presets.
127pub mod genesis_config_presets {
128	use super::*;
129	use crate::{
130		interface::{Balance, MinimumBalance},
131		BalancesConfig, RuntimeGenesisConfig, SudoConfig,
132	};
133	use frame::deps::frame_support::build_struct_json_patch;
134	use serde_json::Value;
135
136	/// Returns a development genesis config preset.
137	#[docify::export]
138	pub fn development_config_genesis() -> Value {
139		let endowment = <MinimumBalance as Get<Balance>>::get().max(1) * 1000;
140		build_struct_json_patch!(RuntimeGenesisConfig {
141			balances: BalancesConfig {
142				balances: Sr25519Keyring::iter()
143					.map(|a| (a.to_account_id(), endowment))
144					.collect::<Vec<_>>(),
145			},
146			sudo: SudoConfig { key: Some(Sr25519Keyring::Alice.to_account_id()) },
147		})
148	}
149
150	/// Get the set of the available genesis config presets.
151	#[docify::export]
152	pub fn get_preset(id: &PresetId) -> Option<Vec<u8>> {
153		let patch = match id.as_ref() {
154			DEV_RUNTIME_PRESET => development_config_genesis(),
155			_ => return None,
156		};
157		Some(
158			serde_json::to_string(&patch)
159				.expect("serialization to json is expected to work. qed.")
160				.into_bytes(),
161		)
162	}
163
164	/// List of supported presets.
165	#[docify::export]
166	pub fn preset_names() -> Vec<PresetId> {
167		vec![PresetId::from(DEV_RUNTIME_PRESET)]
168	}
169}
170
171impl_runtime_apis! {
172	impl apis::Core<Block> for Runtime {
173		fn version() -> RuntimeVersion {
174			VERSION
175		}
176
177		fn execute_block(block: Block) {
178			RuntimeExecutive::execute_block(block)
179		}
180
181		fn initialize_block(header: &Header) -> ExtrinsicInclusionMode {
182			RuntimeExecutive::initialize_block(header)
183		}
184	}
185
186	impl apis::Metadata<Block> for Runtime {
187		fn metadata() -> OpaqueMetadata {
188			OpaqueMetadata::new(Runtime::metadata().into())
189		}
190
191		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
192			Runtime::metadata_at_version(version)
193		}
194
195		fn metadata_versions() -> Vec<u32> {
196			Runtime::metadata_versions()
197		}
198	}
199
200	impl apis::BlockBuilder<Block> for Runtime {
201		fn apply_extrinsic(extrinsic: ExtrinsicFor<Runtime>) -> ApplyExtrinsicResult {
202			RuntimeExecutive::apply_extrinsic(extrinsic)
203		}
204
205		fn finalize_block() -> HeaderFor<Runtime> {
206			RuntimeExecutive::finalize_block()
207		}
208
209		fn inherent_extrinsics(data: InherentData) -> Vec<ExtrinsicFor<Runtime>> {
210			data.create_extrinsics()
211		}
212
213		fn check_inherents(
214			block: Block,
215			data: InherentData,
216		) -> CheckInherentsResult {
217			data.check_extrinsics(&block)
218		}
219	}
220
221	impl apis::TaggedTransactionQueue<Block> for Runtime {
222		fn validate_transaction(
223			source: TransactionSource,
224			tx: ExtrinsicFor<Runtime>,
225			block_hash: <Runtime as frame_system::Config>::Hash,
226		) -> TransactionValidity {
227			RuntimeExecutive::validate_transaction(source, tx, block_hash)
228		}
229	}
230
231	impl apis::OffchainWorkerApi<Block> for Runtime {
232		fn offchain_worker(header: &HeaderFor<Runtime>) {
233			RuntimeExecutive::offchain_worker(header)
234		}
235	}
236
237	impl apis::SessionKeys<Block> for Runtime {
238		fn generate_session_keys(_seed: Option<Vec<u8>>) -> Vec<u8> {
239			Default::default()
240		}
241
242		fn decode_session_keys(
243			_encoded: Vec<u8>,
244		) -> Option<Vec<(Vec<u8>, apis::KeyTypeId)>> {
245			Default::default()
246		}
247	}
248
249	impl apis::AccountNonceApi<Block, interface::AccountId, interface::Nonce> for Runtime {
250		fn account_nonce(account: interface::AccountId) -> interface::Nonce {
251			System::account_nonce(account)
252		}
253	}
254
255	impl apis::GenesisBuilder<Block> for Runtime {
256		fn build_state(config: Vec<u8>) -> GenesisBuilderResult {
257			build_state::<RuntimeGenesisConfig>(config)
258		}
259
260		fn get_preset(id: &Option<PresetId>) -> Option<Vec<u8>> {
261			get_preset::<RuntimeGenesisConfig>(id, self::genesis_config_presets::get_preset)
262		}
263
264		fn preset_names() -> Vec<PresetId> {
265			crate::genesis_config_presets::preset_names()
266		}
267	}
268
269	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
270		Block,
271		interface::Balance,
272	> for Runtime {
273		fn query_info(uxt: ExtrinsicFor<Runtime>, len: u32) -> RuntimeDispatchInfo<interface::Balance> {
274			TransactionPayment::query_info(uxt, len)
275		}
276		fn query_fee_details(uxt: ExtrinsicFor<Runtime>, len: u32) -> FeeDetails<interface::Balance> {
277			TransactionPayment::query_fee_details(uxt, len)
278		}
279		fn query_weight_to_fee(weight: Weight) -> interface::Balance {
280			TransactionPayment::weight_to_fee(weight)
281		}
282		fn query_length_to_fee(length: u32) -> interface::Balance {
283			TransactionPayment::length_to_fee(length)
284		}
285	}
286}
287
288/// Just a handy re-definition of some types based on what is already provided to the pallet
289/// configs.
290pub mod interface {
291	use super::Runtime;
292	use frame::prelude::frame_system;
293
294	pub type AccountId = <Runtime as frame_system::Config>::AccountId;
295	pub type Nonce = <Runtime as frame_system::Config>::Nonce;
296	pub type Hash = <Runtime as frame_system::Config>::Hash;
297	pub type Balance = <Runtime as pallet_balances::Config>::Balance;
298	pub type MinimumBalance = <Runtime as pallet_balances::Config>::ExistentialDeposit;
299}