referrerpolicy=no-referrer-when-downgrade

solochain_template_runtime/
apis.rs

1// This is free and unencumbered software released into the public domain.
2//
3// Anyone is free to copy, modify, publish, use, compile, sell, or
4// distribute this software, either in source code form or as a compiled
5// binary, for any purpose, commercial or non-commercial, and by any
6// means.
7//
8// In jurisdictions that recognize copyright laws, the author or authors
9// of this software dedicate any and all copyright interest in the
10// software to the public domain. We make this dedication for the benefit
11// of the public at large and to the detriment of our heirs and
12// successors. We intend this dedication to be an overt act of
13// relinquishment in perpetuity of all present and future rights to this
14// software under copyright law.
15//
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19// IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
20// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
21// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
22// OTHER DEALINGS IN THE SOFTWARE.
23//
24// For more information, please refer to <http://unlicense.org>
25
26// External crates imports
27use alloc::vec::Vec;
28use frame_support::{
29	genesis_builder_helper::{build_state, get_preset},
30	weights::Weight,
31};
32use pallet_grandpa::AuthorityId as GrandpaId;
33use sp_api::impl_runtime_apis;
34use sp_consensus_aura::sr25519::AuthorityId as AuraId;
35use sp_core::{crypto::KeyTypeId, OpaqueMetadata};
36use sp_runtime::{
37	traits::{Block as BlockT, NumberFor},
38	transaction_validity::{TransactionSource, TransactionValidity},
39	ApplyExtrinsicResult,
40};
41use sp_version::RuntimeVersion;
42
43// Local module imports
44use super::{
45	AccountId, Aura, Balance, Block, Executive, Grandpa, InherentDataExt, Nonce, Runtime,
46	RuntimeCall, RuntimeGenesisConfig, SessionKeys, System, TransactionPayment, VERSION,
47};
48
49impl_runtime_apis! {
50	impl sp_api::Core<Block> for Runtime {
51		fn version() -> RuntimeVersion {
52			VERSION
53		}
54
55		fn execute_block(block: Block) {
56			Executive::execute_block(block);
57		}
58
59		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
60			Executive::initialize_block(header)
61		}
62	}
63
64	impl sp_api::Metadata<Block> for Runtime {
65		fn metadata() -> OpaqueMetadata {
66			OpaqueMetadata::new(Runtime::metadata().into())
67		}
68
69		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
70			Runtime::metadata_at_version(version)
71		}
72
73		fn metadata_versions() -> Vec<u32> {
74			Runtime::metadata_versions()
75		}
76	}
77
78	impl frame_support::view_functions::runtime_api::RuntimeViewFunction<Block> for Runtime {
79		fn execute_view_function(id: frame_support::view_functions::ViewFunctionId, input: Vec<u8>) -> Result<Vec<u8>, frame_support::view_functions::ViewFunctionDispatchError> {
80			Runtime::execute_view_function(id, input)
81		}
82	}
83
84	impl sp_block_builder::BlockBuilder<Block> for Runtime {
85		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
86			Executive::apply_extrinsic(extrinsic)
87		}
88
89		fn finalize_block() -> <Block as BlockT>::Header {
90			Executive::finalize_block()
91		}
92
93		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
94			data.create_extrinsics()
95		}
96
97		fn check_inherents(
98			block: Block,
99			data: sp_inherents::InherentData,
100		) -> sp_inherents::CheckInherentsResult {
101			data.check_extrinsics(&block)
102		}
103	}
104
105	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
106		fn validate_transaction(
107			source: TransactionSource,
108			tx: <Block as BlockT>::Extrinsic,
109			block_hash: <Block as BlockT>::Hash,
110		) -> TransactionValidity {
111			Executive::validate_transaction(source, tx, block_hash)
112		}
113	}
114
115	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
116		fn offchain_worker(header: &<Block as BlockT>::Header) {
117			Executive::offchain_worker(header)
118		}
119	}
120
121	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
122		fn slot_duration() -> sp_consensus_aura::SlotDuration {
123			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
124		}
125
126		fn authorities() -> Vec<AuraId> {
127			pallet_aura::Authorities::<Runtime>::get().into_inner()
128		}
129	}
130
131	impl sp_session::SessionKeys<Block> for Runtime {
132		fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
133			SessionKeys::generate(seed)
134		}
135
136		fn decode_session_keys(
137			encoded: Vec<u8>,
138		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
139			SessionKeys::decode_into_raw_public_keys(&encoded)
140		}
141	}
142
143	impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
144		fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
145			Grandpa::grandpa_authorities()
146		}
147
148		fn current_set_id() -> sp_consensus_grandpa::SetId {
149			Grandpa::current_set_id()
150		}
151
152		fn submit_report_equivocation_unsigned_extrinsic(
153			_equivocation_proof: sp_consensus_grandpa::EquivocationProof<
154				<Block as BlockT>::Hash,
155				NumberFor<Block>,
156			>,
157			_key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
158		) -> Option<()> {
159			None
160		}
161
162		fn generate_key_ownership_proof(
163			_set_id: sp_consensus_grandpa::SetId,
164			_authority_id: GrandpaId,
165		) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
166			// NOTE: this is the only implementation possible since we've
167			// defined our key owner proof type as a bottom type (i.e. a type
168			// with no values).
169			None
170		}
171	}
172
173	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
174		fn account_nonce(account: AccountId) -> Nonce {
175			System::account_nonce(account)
176		}
177	}
178
179	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
180		fn query_info(
181			uxt: <Block as BlockT>::Extrinsic,
182			len: u32,
183		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
184			TransactionPayment::query_info(uxt, len)
185		}
186		fn query_fee_details(
187			uxt: <Block as BlockT>::Extrinsic,
188			len: u32,
189		) -> pallet_transaction_payment::FeeDetails<Balance> {
190			TransactionPayment::query_fee_details(uxt, len)
191		}
192		fn query_weight_to_fee(weight: Weight) -> Balance {
193			TransactionPayment::weight_to_fee(weight)
194		}
195		fn query_length_to_fee(length: u32) -> Balance {
196			TransactionPayment::length_to_fee(length)
197		}
198	}
199
200	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
201		for Runtime
202	{
203		fn query_call_info(
204			call: RuntimeCall,
205			len: u32,
206		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
207			TransactionPayment::query_call_info(call, len)
208		}
209		fn query_call_fee_details(
210			call: RuntimeCall,
211			len: u32,
212		) -> pallet_transaction_payment::FeeDetails<Balance> {
213			TransactionPayment::query_call_fee_details(call, len)
214		}
215		fn query_weight_to_fee(weight: Weight) -> Balance {
216			TransactionPayment::weight_to_fee(weight)
217		}
218		fn query_length_to_fee(length: u32) -> Balance {
219			TransactionPayment::length_to_fee(length)
220		}
221	}
222
223	#[cfg(feature = "runtime-benchmarks")]
224	impl frame_benchmarking::Benchmark<Block> for Runtime {
225		fn benchmark_metadata(extra: bool) -> (
226			Vec<frame_benchmarking::BenchmarkList>,
227			Vec<frame_support::traits::StorageInfo>,
228		) {
229			use frame_benchmarking::{baseline, BenchmarkList};
230			use frame_support::traits::StorageInfoTrait;
231			use frame_system_benchmarking::Pallet as SystemBench;
232			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
233			use baseline::Pallet as BaselineBench;
234			use super::*;
235
236			let mut list = Vec::<BenchmarkList>::new();
237			list_benchmarks!(list, extra);
238
239			let storage_info = AllPalletsWithSystem::storage_info();
240
241			(list, storage_info)
242		}
243
244		#[allow(non_local_definitions)]
245		fn dispatch_benchmark(
246			config: frame_benchmarking::BenchmarkConfig
247		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
248			use frame_benchmarking::{baseline, BenchmarkBatch};
249			use sp_storage::TrackedStorageKey;
250			use frame_system_benchmarking::Pallet as SystemBench;
251			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
252			use baseline::Pallet as BaselineBench;
253			use super::*;
254
255			impl frame_system_benchmarking::Config for Runtime {}
256			impl baseline::Config for Runtime {}
257
258			use frame_support::traits::WhitelistedStorageKeys;
259			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
260
261			let mut batches = Vec::<BenchmarkBatch>::new();
262			let params = (&config, &whitelist);
263			add_benchmarks!(params, batches);
264
265			Ok(batches)
266		}
267	}
268
269	#[cfg(feature = "try-runtime")]
270	impl frame_try_runtime::TryRuntime<Block> for Runtime {
271		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
272			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
273			// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
274			// right here and right now.
275			let weight = Executive::try_runtime_upgrade(checks).unwrap();
276			(weight, super::configs::RuntimeBlockWeights::get().max_block)
277		}
278
279		fn execute_block(
280			block: Block,
281			state_root_check: bool,
282			signature_check: bool,
283			select: frame_try_runtime::TryStateSelect
284		) -> Weight {
285			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
286			// have a backtrace here.
287			Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed")
288		}
289	}
290
291	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
292		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
293			build_state::<RuntimeGenesisConfig>(config)
294		}
295
296		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
297			get_preset::<RuntimeGenesisConfig>(id, crate::genesis_config_presets::get_preset)
298		}
299
300		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
301			crate::genesis_config_presets::preset_names()
302		}
303	}
304}