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_session::OpaqueGeneratedSessionKeys;
42use sp_version::RuntimeVersion;
43
44// Local module imports
45use super::{
46	AccountId, Aura, Balance, Block, Executive, Grandpa, InherentDataExt, Nonce, Runtime,
47	RuntimeCall, RuntimeGenesisConfig, SessionKeys, System, TransactionPayment, VERSION,
48};
49
50impl_runtime_apis! {
51	impl sp_api::Core<Block> for Runtime {
52		fn version() -> RuntimeVersion {
53			VERSION
54		}
55
56		fn execute_block(block: <Block as BlockT>::LazyBlock) {
57			Executive::execute_block(block);
58		}
59
60		fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
61			Executive::initialize_block(header)
62		}
63	}
64
65	impl sp_api::Metadata<Block> for Runtime {
66		fn metadata() -> OpaqueMetadata {
67			OpaqueMetadata::new(Runtime::metadata().into())
68		}
69
70		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
71			Runtime::metadata_at_version(version)
72		}
73
74		fn metadata_versions() -> Vec<u32> {
75			Runtime::metadata_versions()
76		}
77	}
78
79	impl frame_support::view_functions::runtime_api::RuntimeViewFunction<Block> for Runtime {
80		fn execute_view_function(id: frame_support::view_functions::ViewFunctionId, input: Vec<u8>) -> Result<Vec<u8>, frame_support::view_functions::ViewFunctionDispatchError> {
81			Runtime::execute_view_function(id, input)
82		}
83	}
84
85	impl sp_block_builder::BlockBuilder<Block> for Runtime {
86		fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
87			Executive::apply_extrinsic(extrinsic)
88		}
89
90		fn finalize_block() -> <Block as BlockT>::Header {
91			Executive::finalize_block()
92		}
93
94		fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
95			data.create_extrinsics()
96		}
97
98		fn check_inherents(
99			block: <Block as BlockT>::LazyBlock,
100			data: sp_inherents::InherentData,
101		) -> sp_inherents::CheckInherentsResult {
102			data.check_extrinsics(&block)
103		}
104	}
105
106	impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
107		fn validate_transaction(
108			source: TransactionSource,
109			tx: <Block as BlockT>::Extrinsic,
110			block_hash: <Block as BlockT>::Hash,
111		) -> TransactionValidity {
112			Executive::validate_transaction(source, tx, block_hash)
113		}
114	}
115
116	impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
117		fn offchain_worker(header: &<Block as BlockT>::Header) {
118			Executive::offchain_worker(header)
119		}
120	}
121
122	impl sp_consensus_aura::AuraApi<Block, AuraId> for Runtime {
123		fn slot_duration() -> sp_consensus_aura::SlotDuration {
124			sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration())
125		}
126
127		fn authorities() -> Vec<AuraId> {
128			pallet_aura::Authorities::<Runtime>::get().into_inner()
129		}
130	}
131
132	impl sp_session::SessionKeys<Block> for Runtime {
133		fn generate_session_keys(owner: Vec<u8>, seed: Option<Vec<u8>>) -> OpaqueGeneratedSessionKeys {
134			SessionKeys::generate(&owner, seed).into()
135		}
136
137		fn decode_session_keys(
138			encoded: Vec<u8>,
139		) -> Option<Vec<(Vec<u8>, KeyTypeId)>> {
140			SessionKeys::decode_into_raw_public_keys(&encoded)
141		}
142	}
143
144	impl sp_consensus_grandpa::GrandpaApi<Block> for Runtime {
145		fn grandpa_authorities() -> sp_consensus_grandpa::AuthorityList {
146			Grandpa::grandpa_authorities()
147		}
148
149		fn current_set_id() -> sp_consensus_grandpa::SetId {
150			Grandpa::current_set_id()
151		}
152
153		fn submit_report_equivocation_unsigned_extrinsic(
154			_equivocation_proof: sp_consensus_grandpa::EquivocationProof<
155				<Block as BlockT>::Hash,
156				NumberFor<Block>,
157			>,
158			_key_owner_proof: sp_consensus_grandpa::OpaqueKeyOwnershipProof,
159		) -> Option<()> {
160			None
161		}
162
163		fn generate_key_ownership_proof(
164			_set_id: sp_consensus_grandpa::SetId,
165			_authority_id: GrandpaId,
166		) -> Option<sp_consensus_grandpa::OpaqueKeyOwnershipProof> {
167			// NOTE: this is the only implementation possible since we've
168			// defined our key owner proof type as a bottom type (i.e. a type
169			// with no values).
170			None
171		}
172	}
173
174	impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Nonce> for Runtime {
175		fn account_nonce(account: AccountId) -> Nonce {
176			System::account_nonce(account)
177		}
178	}
179
180	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance> for Runtime {
181		fn query_info(
182			uxt: <Block as BlockT>::Extrinsic,
183			len: u32,
184		) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
185			TransactionPayment::query_info(uxt, len)
186		}
187		fn query_fee_details(
188			uxt: <Block as BlockT>::Extrinsic,
189			len: u32,
190		) -> pallet_transaction_payment::FeeDetails<Balance> {
191			TransactionPayment::query_fee_details(uxt, len)
192		}
193		fn query_weight_to_fee(weight: Weight) -> Balance {
194			TransactionPayment::weight_to_fee(weight)
195		}
196		fn query_length_to_fee(length: u32) -> Balance {
197			TransactionPayment::length_to_fee(length)
198		}
199	}
200
201	impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi<Block, Balance, RuntimeCall>
202		for Runtime
203	{
204		fn query_call_info(
205			call: RuntimeCall,
206			len: u32,
207		) -> pallet_transaction_payment::RuntimeDispatchInfo<Balance> {
208			TransactionPayment::query_call_info(call, len)
209		}
210		fn query_call_fee_details(
211			call: RuntimeCall,
212			len: u32,
213		) -> pallet_transaction_payment::FeeDetails<Balance> {
214			TransactionPayment::query_call_fee_details(call, len)
215		}
216		fn query_weight_to_fee(weight: Weight) -> Balance {
217			TransactionPayment::weight_to_fee(weight)
218		}
219		fn query_length_to_fee(length: u32) -> Balance {
220			TransactionPayment::length_to_fee(length)
221		}
222	}
223
224	#[cfg(feature = "runtime-benchmarks")]
225	impl frame_benchmarking::Benchmark<Block> for Runtime {
226		fn benchmark_metadata(extra: bool) -> (
227			Vec<frame_benchmarking::BenchmarkList>,
228			Vec<frame_support::traits::StorageInfo>,
229		) {
230			use frame_benchmarking::{baseline, BenchmarkList};
231			use frame_support::traits::StorageInfoTrait;
232			use frame_system_benchmarking::Pallet as SystemBench;
233			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
234			use baseline::Pallet as BaselineBench;
235			use super::*;
236
237			let mut list = Vec::<BenchmarkList>::new();
238			list_benchmarks!(list, extra);
239
240			let storage_info = AllPalletsWithSystem::storage_info();
241
242			(list, storage_info)
243		}
244
245		#[allow(non_local_definitions)]
246		fn dispatch_benchmark(
247			config: frame_benchmarking::BenchmarkConfig
248		) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
249			use frame_benchmarking::{baseline, BenchmarkBatch};
250			use sp_storage::TrackedStorageKey;
251			use frame_system_benchmarking::Pallet as SystemBench;
252			use frame_system_benchmarking::extensions::Pallet as SystemExtensionsBench;
253			use baseline::Pallet as BaselineBench;
254			use super::*;
255
256			impl frame_system_benchmarking::Config for Runtime {}
257			impl baseline::Config for Runtime {}
258
259			use frame_support::traits::WhitelistedStorageKeys;
260			let whitelist: Vec<TrackedStorageKey> = AllPalletsWithSystem::whitelisted_storage_keys();
261
262			let mut batches = Vec::<BenchmarkBatch>::new();
263			let params = (&config, &whitelist);
264			add_benchmarks!(params, batches);
265
266			Ok(batches)
267		}
268	}
269
270	#[cfg(feature = "try-runtime")]
271	impl frame_try_runtime::TryRuntime<Block> for Runtime {
272		fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
273			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
274			// have a backtrace here. If any of the pre/post migration checks fail, we shall stop
275			// right here and right now.
276			let weight = Executive::try_runtime_upgrade(checks).unwrap();
277			(weight, super::configs::RuntimeBlockWeights::get().max_block)
278		}
279
280		fn execute_block(
281			block: <Block as BlockT>::LazyBlock,
282			state_root_check: bool,
283			signature_check: bool,
284			select: frame_try_runtime::TryStateSelect
285		) -> Weight {
286			// NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
287			// have a backtrace here.
288			Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed")
289		}
290	}
291
292	impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
293		fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
294			build_state::<RuntimeGenesisConfig>(config)
295		}
296
297		fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
298			get_preset::<RuntimeGenesisConfig>(id, crate::genesis_config_presets::get_preset)
299		}
300
301		fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
302			crate::genesis_config_presets::preset_names()
303		}
304	}
305}