tp_api/
lib.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2019-2021 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//! Tetcore runtime api
19//!
20//! The Tetcore runtime api is the crucial interface between the node and the runtime.
21//! Every call that goes into the runtime is done with a runtime api. The runtime apis are not fixed.
22//! Every Tetcore user can define its own apis with
23//! [`decl_runtime_apis`](macro.decl_runtime_apis.html) and implement them in
24//! the runtime with [`impl_runtime_apis`](macro.impl_runtime_apis.html).
25//!
26//! Every Tetcore runtime needs to implement the [`Core`] runtime api. This api provides the basic
27//! functionality that every runtime needs to export.
28//!
29//! Besides the macros and the [`Core`] runtime api, this crates provides the [`Metadata`] runtime
30//! api, the [`ApiExt`] trait, the [`CallApiAt`] trait and the [`ConstructRuntimeApi`] trait.
31//!
32//! On a meta level this implies, the client calls the generated API from the client perspective.
33
34#![cfg_attr(not(feature = "std"), no_std)]
35
36// Make doc tests happy
37extern crate self as tp_api;
38
39#[doc(hidden)]
40#[cfg(feature = "std")]
41pub use tp_state_machine::{
42	OverlayedChanges, StorageProof, Backend as StateBackend, ChangesTrieState, InMemoryBackend,
43};
44#[doc(hidden)]
45#[cfg(feature = "std")]
46pub use tet_core::NativeOrEncoded;
47#[doc(hidden)]
48#[cfg(feature = "std")]
49pub use tetsy_hash_db::Hasher;
50#[doc(hidden)]
51#[cfg(not(feature = "std"))]
52pub use tet_core::to_tetcore_wasm_fn_return_value;
53#[doc(hidden)]
54pub use tp_runtime::{
55	traits::{
56		Block as BlockT, GetNodeBlockType, GetRuntimeBlockType, HashFor, NumberFor,
57		Header as HeaderT, Hash as HashT,
58	},
59	generic::BlockId, transaction_validity::TransactionValidity, RuntimeString, TransactionOutcome,
60};
61#[doc(hidden)]
62pub use tet_core::{offchain, ExecutionContext};
63#[doc(hidden)]
64pub use tp_version::{ApiId, RuntimeVersion, ApisVec, create_apis_vec};
65#[doc(hidden)]
66pub use tetcore_std::{slice, mem};
67#[cfg(feature = "std")]
68use tetcore_std::result;
69#[doc(hidden)]
70pub use codec::{Encode, Decode, DecodeLimit};
71use tet_core::OpaqueMetadata;
72#[cfg(feature = "std")]
73use std::{panic::UnwindSafe, cell::RefCell};
74
75
76/// Maximum nesting level for extrinsics.
77pub const MAX_EXTRINSIC_DEPTH: u32 = 256;
78
79/// Declares given traits as runtime apis.
80///
81/// The macro will create two declarations, one for using on the client side and one for using
82/// on the runtime side. The declaration for the runtime side is hidden in its own module.
83/// The client side declaration gets two extra parameters per function,
84/// `&self` and `at: &BlockId<Block>`. The runtime side declaration will match the given trait
85/// declaration. Besides one exception, the macro adds an extra generic parameter `Block: BlockT`
86/// to the client side and the runtime side. This generic parameter is usable by the user.
87///
88/// For implementing these macros you should use the
89/// [`impl_runtime_apis!`](macro.impl_runtime_apis.html) macro.
90///
91/// # Example
92///
93/// ```rust
94/// tp_api::decl_runtime_apis! {
95///     /// Declare the api trait.
96///     pub trait Balance {
97///         /// Get the balance.
98///         fn get_balance() -> u64;
99///         /// Set the balance.
100///         fn set_balance(val: u64);
101///     }
102///
103///     /// You can declare multiple api traits in one macro call.
104///     /// In one module you can call the macro at maximum one time.
105///     pub trait BlockBuilder {
106///         /// The macro adds an explicit `Block: BlockT` generic parameter for you.
107///         /// You can use this generic parameter as you would defined it manually.
108///         fn build_block() -> Block;
109///     }
110/// }
111///
112/// # fn main() {}
113/// ```
114///
115/// # Runtime api trait versioning
116///
117/// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`.
118/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if no
119/// version is provided. We also support changing the signature of a method. This signature
120/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that is
121/// tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
122/// method will only support calling into wasm, trying to call into native will fail (change the
123/// spec version!). Such a method also does not need to be implemented in the runtime. It is
124/// required that there exist the "default" of the method without the `#[changed_in(_)]` attribute,
125/// this method will be used to call the current default implementation.
126///
127/// ```rust
128/// tp_api::decl_runtime_apis! {
129///     /// Declare the api trait.
130///     #[api_version(2)]
131///     pub trait Balance {
132///         /// Get the balance.
133///         fn get_balance() -> u64;
134///         /// Set balance.
135///         fn set_balance(val: u64);
136///         /// Set balance, old version.
137///         ///
138///         /// Is callable by `set_balance_before_version_2`.
139///         #[changed_in(2)]
140///         fn set_balance(val: u16);
141///         /// In version 2, we added this new function.
142///         fn increase_balance(val: u64);
143///     }
144/// }
145///
146/// # fn main() {}
147/// ```
148///
149/// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the
150/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: &BlockId)` to
151/// check if the runtime at the given block id implements the requested runtime api trait.
152pub use tp_api_proc_macro::decl_runtime_apis;
153
154/// Tags given trait implementations as runtime apis.
155///
156/// All traits given to this macro, need to be declared with the
157/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait
158/// should follow the declaration given to the [`decl_runtime_apis!`](macro.decl_runtime_apis.html)
159/// macro, besides the `Block` type that is required as first generic parameter for each runtime
160/// api trait. When implementing a runtime api trait, it is required that the trait is referenced
161/// by a path, e.g. `impl my_trait::MyTrait for Runtime`. The macro will use this path to access
162/// the declaration of the trait for the runtime side.
163///
164/// The macro also generates the api implementations for the client side and provides it through
165/// the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
166///
167/// To expose version information about all implemented api traits, the constant
168/// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis`
169/// field of `RuntimeVersion`.
170///
171/// # Example
172///
173/// ```rust
174/// use tp_version::create_runtime_str;
175/// #
176/// # use tp_runtime::traits::{GetNodeBlockType, Block as BlockT};
177/// # use tp_test_primitives::Block;
178/// #
179/// # /// The declaration of the `Runtime` type and the implementation of the `GetNodeBlockType`
180/// # /// trait are done by the `construct_runtime!` macro in a real runtime.
181/// # pub struct Runtime {}
182/// # impl GetNodeBlockType for Runtime {
183/// #     type NodeBlock = Block;
184/// # }
185/// #
186/// # tp_api::decl_runtime_apis! {
187/// #     /// Declare the api trait.
188/// #     pub trait Balance {
189/// #         /// Get the balance.
190/// #         fn get_balance() -> u64;
191/// #         /// Set the balance.
192/// #         fn set_balance(val: u64);
193/// #     }
194/// #     pub trait BlockBuilder {
195/// #        fn build_block() -> Block;
196/// #     }
197/// # }
198///
199/// /// All runtime api implementations need to be done in one call of the macro!
200/// tp_api::impl_runtime_apis! {
201/// #   impl tp_api::Core<Block> for Runtime {
202/// #       fn version() -> tp_version::RuntimeVersion {
203/// #           unimplemented!()
204/// #       }
205/// #       fn execute_block(_block: Block) {}
206/// #       fn initialize_block(_header: &<Block as BlockT>::Header) {}
207/// #   }
208///
209///     impl self::Balance<Block> for Runtime {
210///         fn get_balance() -> u64 {
211///             1
212///         }
213///         fn set_balance(_bal: u64) {
214///             // Store the balance
215///         }
216///     }
217///
218///     impl self::BlockBuilder<Block> for Runtime {
219///         fn build_block() -> Block {
220///              unimplemented!("Please implement me!")
221///         }
222///     }
223/// }
224///
225/// /// Runtime version. This needs to be declared for each runtime.
226/// pub const VERSION: tp_version::RuntimeVersion = tp_version::RuntimeVersion {
227///     spec_name: create_runtime_str!("node"),
228///     impl_name: create_runtime_str!("test-node"),
229///     authoring_version: 1,
230///     spec_version: 1,
231///     impl_version: 0,
232///     // Here we are exposing the runtime api versions.
233///     apis: RUNTIME_API_VERSIONS,
234///     transaction_version: 1,
235/// };
236///
237/// # fn main() {}
238/// ```
239pub use tp_api_proc_macro::impl_runtime_apis;
240
241/// Mocks given trait implementations as runtime apis.
242///
243/// Accepts similar syntax as [`impl_runtime_apis!`] and generates
244/// simplified mock implementations of the given runtime apis. The difference in syntax is that the
245/// trait does not need to be referenced by a qualified path, methods accept the `&self` parameter
246/// and the error type can be specified as associated type. If no error type is specified [`String`]
247/// is used as error type.
248///
249/// Besides implementing the given traits, the [`Core`](tp_api::Core), [`ApiExt`](tp_api::ApiExt)
250/// and [`ApiErrorExt`](tp_api::ApiErrorExt) are implemented automatically.
251///
252/// # Example
253///
254/// ```rust
255/// # use tp_runtime::traits::Block as BlockT;
256/// # use tp_test_primitives::Block;
257/// #
258/// # tp_api::decl_runtime_apis! {
259/// #     /// Declare the api trait.
260/// #     pub trait Balance {
261/// #         /// Get the balance.
262/// #         fn get_balance() -> u64;
263/// #         /// Set the balance.
264/// #         fn set_balance(val: u64);
265/// #     }
266/// #     pub trait BlockBuilder {
267/// #        fn build_block() -> Block;
268/// #     }
269/// # }
270/// struct MockApi {
271///     balance: u64,
272/// }
273///
274/// /// All runtime api mock implementations need to be done in one call of the macro!
275/// tp_api::mock_impl_runtime_apis! {
276///     impl Balance<Block> for MockApi {
277///         /// Here we take the `&self` to access the instance.
278///         fn get_balance(&self) -> u64 {
279///             self.balance
280///         }
281///         fn set_balance(_bal: u64) {
282///             // Store the balance
283///         }
284///     }
285///
286///     impl BlockBuilder<Block> for MockApi {
287///         /// Sets the error type that is being used by the mock implementation.
288///         /// The error type is used by all runtime apis. It is only required to
289///         /// be specified in one trait implementation.
290///         type Error = tp_api::ApiError;
291///
292///         fn build_block() -> Block {
293///              unimplemented!("Not Required in tests")
294///         }
295///     }
296/// }
297///
298/// # fn main() {}
299/// ```
300///
301/// # `advanced` attribute
302///
303/// This attribute can be placed above individual function in the mock implementation to request
304/// more control over the function declaration. From the client side each runtime api function is
305/// called with the `at` parameter that is a [`BlockId`](tp_api::BlockId). When using the `advanced`
306/// attribute, the macro expects that the first parameter of the function is this `at` parameter.
307/// Besides that the macro also doesn't do the automatic return value rewrite, which means that full
308/// return value must be specified. The full return value is constructed like
309/// [`Result`]`<`[`NativeOrEncoded`](tp_api::NativeOrEncoded)`<ReturnValue>, Error>` while
310/// `ReturnValue` being the return value that is specified in the trait declaration.
311///
312/// ## Example
313/// ```rust
314/// # use tp_runtime::{traits::Block as BlockT, generic::BlockId};
315/// # use tp_test_primitives::Block;
316/// # use tet_core::NativeOrEncoded;
317/// # use codec;
318/// #
319/// # tp_api::decl_runtime_apis! {
320/// #     /// Declare the api trait.
321/// #     pub trait Balance {
322/// #         /// Get the balance.
323/// #         fn get_balance() -> u64;
324/// #         /// Set the balance.
325/// #         fn set_balance(val: u64);
326/// #     }
327/// # }
328/// struct MockApi {
329///     balance: u64,
330/// }
331///
332/// tp_api::mock_impl_runtime_apis! {
333///     impl Balance<Block> for MockApi {
334///         type Error = tp_api::ApiError;
335///         #[advanced]
336///         fn get_balance(&self, at: &BlockId<Block>) -> Result<NativeOrEncoded<u64>, Self::Error> {
337///             println!("Being called at: {}", at);
338///
339///             Ok(self.balance.into())
340///         }
341///         #[advanced]
342///         fn set_balance(at: &BlockId<Block>, val: u64) -> Result<NativeOrEncoded<()>, Self::Error> {
343///             if let BlockId::Number(1) = at {
344///                 println!("Being called to set balance to: {}", val);
345///             }
346///
347///             Ok(().into())
348///         }
349///     }
350/// }
351///
352/// # fn main() {}
353/// ```
354pub use tp_api_proc_macro::mock_impl_runtime_apis;
355
356/// A type that records all accessed trie nodes and generates a proof out of it.
357#[cfg(feature = "std")]
358pub type ProofRecorder<B> = tp_state_machine::ProofRecorder<HashFor<B>>;
359
360/// A type that is used as cache for the storage transactions.
361#[cfg(feature = "std")]
362pub type StorageTransactionCache<Block, Backend> =
363	tp_state_machine::StorageTransactionCache<
364		<Backend as StateBackend<HashFor<Block>>>::Transaction, HashFor<Block>, NumberFor<Block>
365	>;
366
367#[cfg(feature = "std")]
368pub type StorageChanges<SBackend, Block> =
369	tp_state_machine::StorageChanges<
370		<SBackend as StateBackend<HashFor<Block>>>::Transaction,
371		HashFor<Block>,
372		NumberFor<Block>
373	>;
374
375/// Extract the state backend type for a type that implements `ProvideRuntimeApi`.
376#[cfg(feature = "std")]
377pub type StateBackendFor<P, Block> =
378	<<P as ProvideRuntimeApi<Block>>::Api as ApiExt<Block>>::StateBackend;
379
380/// Extract the state backend transaction type for a type that implements `ProvideRuntimeApi`.
381#[cfg(feature = "std")]
382pub type TransactionFor<P, Block> =
383	<StateBackendFor<P, Block> as StateBackend<HashFor<Block>>>::Transaction;
384
385/// Something that can be constructed to a runtime api.
386#[cfg(feature = "std")]
387pub trait ConstructRuntimeApi<Block: BlockT, C: CallApiAt<Block>> {
388	/// The actual runtime api that will be constructed.
389	type RuntimeApi: ApiExt<Block>;
390
391	/// Construct an instance of the runtime api.
392	fn construct_runtime_api<'a>(call: &'a C) -> ApiRef<'a, Self::RuntimeApi>;
393}
394
395/// An error describing which API call failed.
396#[cfg_attr(feature = "std", derive(Debug, thiserror::Error, Eq, PartialEq))]
397#[cfg_attr(feature = "std", error("Failed to execute API call {tag}"))]
398#[cfg(feature = "std")]
399pub struct ApiError {
400    tag: &'static str,
401    #[source]
402    error: codec::Error,
403}
404
405#[cfg(feature = "std")]
406impl From<(&'static str, codec::Error)> for ApiError {
407    fn from((tag, error): (&'static str, codec::Error)) -> Self {
408        Self {
409            tag,
410            error,
411        }
412    }
413}
414
415#[cfg(feature = "std")]
416impl ApiError {
417	pub fn new(tag: &'static str, error: codec::Error) -> Self {
418		Self {
419			tag,
420			error,
421		}
422	}
423}
424
425/// Extends the runtime api traits with an associated error type. This trait is given as super
426/// trait to every runtime api trait.
427#[cfg(feature = "std")]
428pub trait ApiErrorExt {
429	/// Error type used by the runtime apis.
430	type Error: std::fmt::Debug + From<ApiError>;
431}
432
433/// Extends the runtime api implementation with some common functionality.
434#[cfg(feature = "std")]
435pub trait ApiExt<Block: BlockT>: ApiErrorExt {
436	/// The state backend that is used to store the block states.
437	type StateBackend: StateBackend<HashFor<Block>>;
438
439	/// Execute the given closure inside a new transaction.
440	///
441	/// Depending on the outcome of the closure, the transaction is committed or rolled-back.
442	///
443	/// The internal result of the closure is returned afterwards.
444	fn execute_in_transaction<F: FnOnce(&Self) -> TransactionOutcome<R>, R>(
445		&self,
446		call: F,
447	) -> R where Self: Sized;
448
449	/// Checks if the given api is implemented and versions match.
450	fn has_api<A: RuntimeApiInfo + ?Sized>(
451		&self,
452		at: &BlockId<Block>,
453	) -> Result<bool, Self::Error> where Self: Sized;
454
455	/// Check if the given api is implemented and the version passes a predicate.
456	fn has_api_with<A: RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
457		&self,
458		at: &BlockId<Block>,
459		pred: P,
460	) -> Result<bool, Self::Error> where Self: Sized;
461
462	/// Start recording all accessed trie nodes for generating proofs.
463	fn record_proof(&mut self);
464
465	/// Extract the recorded proof.
466	///
467	/// This stops the proof recording.
468	///
469	/// If `record_proof` was not called before, this will return `None`.
470	fn extract_proof(&mut self) -> Option<StorageProof>;
471
472	/// Convert the api object into the storage changes that were done while executing runtime
473	/// api functions.
474	///
475	/// After executing this function, all collected changes are reset.
476	fn into_storage_changes(
477		&self,
478		backend: &Self::StateBackend,
479		changes_trie_state: Option<&ChangesTrieState<HashFor<Block>, NumberFor<Block>>>,
480		parent_hash: Block::Hash,
481	) -> Result<StorageChanges<Self::StateBackend, Block>, String> where Self: Sized;
482}
483
484/// Before calling any runtime api function, the runtime need to be initialized
485/// at the requested block. However, some functions like `execute_block` or
486/// `initialize_block` itself don't require to have the runtime initialized
487/// at the requested block.
488///
489/// `call_api_at` is instructed by this enum to do the initialization or to skip
490/// it.
491#[cfg(feature = "std")]
492#[derive(Clone, Copy)]
493pub enum InitializeBlock<'a, Block: BlockT> {
494	/// Skip initializing the runtime for a given block.
495	///
496	/// This is used by functions who do the initialization by themselves or don't require it.
497	Skip,
498	/// Initialize the runtime for a given block.
499	///
500	/// If the stored `BlockId` is `Some(_)`, the runtime is currently initialized at this block.
501	Do(&'a RefCell<Option<BlockId<Block>>>),
502}
503
504/// Parameters for [`CallApiAt::call_api_at`].
505#[cfg(feature = "std")]
506pub struct CallApiAtParams<'a, Block: BlockT, C, NC, Backend: StateBackend<HashFor<Block>>> {
507	/// A reference to something that implements the [`Core`] api.
508	pub core_api: &'a C,
509	/// The block id that determines the state that should be setup when calling the function.
510	pub at: &'a BlockId<Block>,
511	/// The name of the function that should be called.
512	pub function: &'static str,
513	/// An optional native call that calls the `function`. This is an optimization to call into a
514	/// native runtime without requiring to encode/decode the parameters. The native runtime can
515	/// still be called when this value is `None`, we then just fallback to encoding/decoding the
516	/// parameters.
517	pub native_call: Option<NC>,
518	/// The encoded arguments of the function.
519	pub arguments: Vec<u8>,
520	/// The overlayed changes that are on top of the state.
521	pub overlayed_changes: &'a RefCell<OverlayedChanges>,
522	/// The cache for storage transactions.
523	pub storage_transaction_cache: &'a RefCell<StorageTransactionCache<Block, Backend>>,
524	/// Determines if the function requires that `initialize_block` should be called before calling
525	/// the actual function.
526	pub initialize_block: InitializeBlock<'a, Block>,
527	/// The context this function is executed in.
528	pub context: ExecutionContext,
529	/// The optional proof recorder for recording storage accesses.
530	pub recorder: &'a Option<ProofRecorder<Block>>,
531}
532
533/// Something that can call into the an api at a given block.
534#[cfg(feature = "std")]
535pub trait CallApiAt<Block: BlockT> {
536	/// Error type used by the implementation.
537	type Error: std::fmt::Debug + From<ApiError>;
538
539	/// The state backend that is used to store the block states.
540	type StateBackend: StateBackend<HashFor<Block>>;
541
542	/// Calls the given api function with the given encoded arguments at the given block and returns
543	/// the encoded result.
544	fn call_api_at<
545		'a,
546		R: Encode + Decode + PartialEq,
547		NC: FnOnce() -> result::Result<R, String> + UnwindSafe,
548		C: Core<Block, Error = Self::Error>,
549	>(
550		&self,
551		params: CallApiAtParams<'a, Block, C, NC, Self::StateBackend>,
552	) -> Result<NativeOrEncoded<R>, Self::Error>;
553
554	/// Returns the runtime version at the given block.
555	fn runtime_version_at(&self, at: &BlockId<Block>) -> Result<RuntimeVersion, Self::Error>;
556}
557
558/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
559#[cfg(feature = "std")]
560pub struct ApiRef<'a, T>(T, std::marker::PhantomData<&'a ()>);
561
562#[cfg(feature = "std")]
563impl<'a, T> From<T> for ApiRef<'a, T> {
564	fn from(api: T) -> Self {
565		ApiRef(api, Default::default())
566	}
567}
568
569#[cfg(feature = "std")]
570impl<'a, T> std::ops::Deref for ApiRef<'a, T> {
571	type Target = T;
572
573	fn deref(&self) -> &Self::Target {
574		&self.0
575	}
576}
577
578#[cfg(feature = "std")]
579impl<'a, T> std::ops::DerefMut for ApiRef<'a, T> {
580	fn deref_mut(&mut self) -> &mut T {
581		&mut self.0
582	}
583}
584
585/// Something that provides a runtime api.
586#[cfg(feature = "std")]
587pub trait ProvideRuntimeApi<Block: BlockT> {
588	/// The concrete type that provides the api.
589	type Api: ApiExt<Block>;
590
591	/// Returns the runtime api.
592	/// The returned instance will keep track of modifications to the storage. Any successful
593	/// call to an api function, will `commit` its changes to an internal buffer. Otherwise,
594	/// the modifications will be `discarded`. The modifications will not be applied to the
595	/// storage, even on a `commit`.
596	fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api>;
597}
598
599/// Something that provides information about a runtime api.
600#[cfg(feature = "std")]
601pub trait RuntimeApiInfo {
602	/// The identifier of the runtime api.
603	const ID: [u8; 8];
604	/// The version of the runtime api.
605	const VERSION: u32;
606}
607
608/// Extracts the `Api::Error` for a type that provides a runtime api.
609#[cfg(feature = "std")]
610pub type ApiErrorFor<T, Block> = <<T as ProvideRuntimeApi<Block>>::Api as ApiErrorExt>::Error;
611
612#[derive(codec::Encode, codec::Decode)]
613pub struct OldRuntimeVersion {
614	pub spec_name: RuntimeString,
615	pub impl_name: RuntimeString,
616	pub authoring_version: u32,
617	pub spec_version: u32,
618	pub impl_version: u32,
619	pub apis: ApisVec,
620}
621
622impl From<OldRuntimeVersion> for RuntimeVersion {
623	fn from(x: OldRuntimeVersion) -> Self {
624		Self {
625			spec_name: x.spec_name,
626			impl_name: x.impl_name,
627			authoring_version: x.authoring_version,
628			spec_version: x.spec_version,
629			impl_version: x.impl_version,
630			apis: x.apis,
631			transaction_version: 1,
632		}
633	}
634}
635
636impl From<RuntimeVersion> for OldRuntimeVersion {
637	fn from(x: RuntimeVersion) -> Self {
638		Self {
639			spec_name: x.spec_name,
640			impl_name: x.impl_name,
641			authoring_version: x.authoring_version,
642			spec_version: x.spec_version,
643			impl_version: x.impl_version,
644			apis: x.apis,
645		}
646	}
647}
648
649decl_runtime_apis! {
650	/// The `Core` runtime api that every Tetcore runtime needs to implement.
651	#[core_trait]
652	#[api_version(3)]
653	pub trait Core {
654		/// Returns the version of the runtime.
655		fn version() -> RuntimeVersion;
656		/// Returns the version of the runtime.
657		#[changed_in(3)]
658		fn version() -> OldRuntimeVersion;
659		/// Execute the given block.
660		#[skip_initialize_block]
661		fn execute_block(block: Block);
662		/// Initialize a block with the given header.
663		#[renamed("initialise_block", 2)]
664		#[skip_initialize_block]
665		#[initialize_block]
666		fn initialize_block(header: &<Block as BlockT>::Header);
667	}
668
669	/// The `Metadata` api trait that returns metadata for the runtime.
670	pub trait Metadata {
671		/// Returns the metadata of a runtime.
672		fn metadata() -> OpaqueMetadata;
673	}
674}