sp_api/
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//! Substrate runtime api
19//!
20//! The Substrate runtime api is the interface between the node and the runtime. There isn't a fixed
21//! set of runtime apis, instead it is up to the user to declare and implement these runtime apis.
22//! The declaration of a runtime api is normally done outside of a runtime, while the implementation
23//! of it has to be done in the runtime. We provide the [`decl_runtime_apis!`] macro for declaring
24//! a runtime api and the [`impl_runtime_apis!`] for implementing them. The macro docs provide more
25//! information on how to use them and what kind of attributes we support.
26//!
27//! It is required that each runtime implements at least the [`Core`] runtime api. This runtime api
28//! provides all the core functions that Substrate expects from a runtime.
29//!
30//! # Versioning
31//!
32//! Runtime apis support versioning. Each runtime api itself has a version attached. It is also
33//! supported to change function signatures or names in a non-breaking way. For more information on
34//! versioning check the [`decl_runtime_apis!`] macro.
35//!
36//! All runtime apis and their versions are returned as part of the [`RuntimeVersion`]. This can be
37//! used to check which runtime api version is currently provided by the on-chain runtime.
38//!
39//! # Testing
40//!
41//! For testing we provide the [`mock_impl_runtime_apis!`] macro that lets you implement a runtime
42//! api for a mocked object to use it in tests.
43//!
44//! # Logging
45//!
46//! Substrate supports logging from the runtime in native and in wasm. For that purpose it provides
47//! the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger). This runtime logger is
48//! automatically enabled for each call into the runtime through the runtime api. As logging
49//! introduces extra code that isn't actually required for the logic of your runtime and also
50//! increases the final wasm blob size, it is recommended to disable the logging for on-chain
51//! wasm blobs. This can be done by enabling the `disable-logging` feature of this crate. Be aware
52//! that this feature instructs `log` and `tracing` to disable logging at compile time by setting
53//! the `max_level_off` feature for these crates. So, you should not enable this feature for a
54//! native build as otherwise the node will not output any log messages.
55//!
56//! # How does it work?
57//!
58//! Each runtime api is declared as a trait with functions. When compiled to WASM, each implemented
59//! runtime api function is exported as a function with the following naming scheme
60//! `${TRAIT_NAME}_${FUNCTION_NAME}`. Such a function has the following signature
61//! `(ptr: *u8, length: u32) -> u64`. It takes a pointer to an `u8` array and its length as an
62//! argument. This `u8` array is expected to be the SCALE encoded parameters of the function as
63//! defined in the trait. The return value is an `u64` that represents `length << 32 | pointer` of
64//! an `u8` array. This return value `u8` array contains the SCALE encoded return value as defined
65//! by the trait function. The macros take care to encode the parameters and to decode the return
66//! value.
67
68#![cfg_attr(not(feature = "std"), no_std)]
69
70// Make doc tests happy
71extern crate self as sp_api;
72
73extern crate alloc;
74
75/// Private exports used by the macros.
76///
77/// This is seen as internal API and can change at any point.
78#[doc(hidden)]
79pub mod __private {
80	#[cfg(feature = "std")]
81	mod std_imports {
82		pub use hash_db::Hasher;
83		pub use sp_core::traits::CallContext;
84		pub use sp_externalities::{Extension, Extensions};
85		pub use sp_runtime::StateVersion;
86		pub use sp_state_machine::{
87			Backend as StateBackend, InMemoryBackend, OverlayedChanges, StorageProof, TrieBackend,
88			TrieBackendBuilder,
89		};
90	}
91	#[cfg(feature = "std")]
92	pub use std_imports::*;
93
94	pub use crate::*;
95	pub use alloc::vec;
96	pub use codec::{self, Decode, DecodeLimit, Encode};
97	pub use core::{mem, slice};
98	pub use scale_info;
99	pub use sp_core::offchain;
100	#[cfg(not(feature = "std"))]
101	pub use sp_core::to_substrate_wasm_fn_return_value;
102	#[cfg(feature = "frame-metadata")]
103	pub use sp_metadata_ir::{self as metadata_ir, frame_metadata as metadata};
104	pub use sp_runtime::{
105		generic::BlockId,
106		traits::{Block as BlockT, Hash as HashT, HashingFor, Header as HeaderT, NumberFor},
107		transaction_validity::TransactionValidity,
108		ExtrinsicInclusionMode, TransactionOutcome,
109	};
110	pub use sp_version::{create_apis_vec, ApiId, ApisVec, RuntimeVersion};
111
112	#[cfg(all(any(target_arch = "riscv32", target_arch = "riscv64"), substrate_runtime))]
113	pub use sp_runtime_interface::polkavm::{polkavm_abi, polkavm_export};
114}
115
116#[cfg(feature = "std")]
117pub use sp_core::traits::CallContext;
118use sp_core::OpaqueMetadata;
119#[cfg(feature = "std")]
120use sp_externalities::{Extension, Extensions};
121#[cfg(feature = "std")]
122use sp_runtime::traits::HashingFor;
123#[cfg(feature = "std")]
124pub use sp_runtime::TransactionOutcome;
125use sp_runtime::{traits::Block as BlockT, ExtrinsicInclusionMode};
126#[cfg(feature = "std")]
127pub use sp_state_machine::StorageProof;
128#[cfg(feature = "std")]
129use sp_state_machine::{backend::AsTrieBackend, Backend as StateBackend, OverlayedChanges};
130use sp_version::RuntimeVersion;
131#[cfg(feature = "std")]
132use std::cell::RefCell;
133
134/// Declares given traits as runtime apis.
135///
136/// The macro will create two declarations, one for using on the client side and one for using
137/// on the runtime side. The declaration for the runtime side is hidden in its own module.
138/// The client side declaration gets two extra parameters per function,
139/// `&self` and `at: Block::Hash`. The runtime side declaration will match the given trait
140/// declaration. Besides one exception, the macro adds an extra generic parameter `Block:
141/// BlockT` to the client side and the runtime side. This generic parameter is usable by the
142/// user.
143///
144/// For implementing these macros you should use the
145/// [`impl_runtime_apis!`] macro.
146///
147/// # Example
148///
149/// ```rust
150/// sp_api::decl_runtime_apis! {
151///     /// Declare the api trait.
152///     pub trait Balance {
153///         /// Get the balance.
154///         fn get_balance() -> u64;
155///         /// Set the balance.
156///         fn set_balance(val: u64);
157///     }
158///
159///     /// You can declare multiple api traits in one macro call.
160///     /// In one module you can call the macro at maximum one time.
161///     pub trait BlockBuilder {
162///         /// The macro adds an explicit `Block: BlockT` generic parameter for you.
163///         /// You can use this generic parameter as you would defined it manually.
164///         fn build_block() -> Block;
165///     }
166/// }
167///
168/// # fn main() {}
169/// ```
170///
171/// # Runtime api trait versioning
172///
173/// To support versioning of the traits, the macro supports the attribute `#[api_version(1)]`.
174/// The attribute supports any `u32` as version. By default, each trait is at version `1`, if
175/// no version is provided. We also support changing the signature of a method. This signature
176/// change is highlighted with the `#[changed_in(2)]` attribute above a method. A method that
177/// is tagged with this attribute is callable by the name `METHOD_before_version_VERSION`. This
178/// method will only support calling into wasm, trying to call into native will fail (change
179/// the spec version!). Such a method also does not need to be implemented in the runtime. It
180/// is required that there exist the "default" of the method without the `#[changed_in(_)]`
181/// attribute, this method will be used to call the current default implementation.
182///
183/// ```rust
184/// sp_api::decl_runtime_apis! {
185///     /// Declare the api trait.
186///     #[api_version(2)]
187///     pub trait Balance {
188///         /// Get the balance.
189///         fn get_balance() -> u64;
190///         /// Set balance.
191///         fn set_balance(val: u64);
192///         /// Set balance, old version.
193///         ///
194///         /// Is callable by `set_balance_before_version_2`.
195///         #[changed_in(2)]
196///         fn set_balance(val: u16);
197///         /// In version 2, we added this new function.
198///         fn increase_balance(val: u64);
199///     }
200/// }
201///
202/// # fn main() {}
203/// ```
204///
205/// To check if a given runtime implements a runtime api trait, the `RuntimeVersion` has the
206/// function `has_api<A>()`. Also the `ApiExt` provides a function `has_api<A>(at: Hash)`
207/// to check if the runtime at the given block id implements the requested runtime api trait.
208///
209/// # Declaring multiple api versions
210///
211/// Optionally multiple versions of the same api can be declared. This is useful for
212/// development purposes. For example you want to have a testing version of the api which is
213/// available only on a testnet. You can define one stable and one development version. This
214/// can be done like this:
215/// ```rust
216/// sp_api::decl_runtime_apis! {
217///     /// Declare the api trait.
218/// 	#[api_version(2)]
219///     pub trait Balance {
220///         /// Get the balance.
221///         fn get_balance() -> u64;
222///         /// Set the balance.
223///         fn set_balance(val: u64);
224///         /// Transfer the balance to another user id
225///         #[api_version(3)]
226///         fn transfer_balance(uid: u64);
227///     }
228/// }
229///
230/// # fn main() {}
231/// ```
232/// The example above defines two api versions - 2 and 3. Version 2 contains `get_balance` and
233/// `set_balance`. Version 3 additionally contains `transfer_balance`, which is not available
234/// in version 2. Version 2 in this case is considered the default/base version of the api.
235/// More than two versions can be defined this way. For example:
236/// ```rust
237/// sp_api::decl_runtime_apis! {
238///     /// Declare the api trait.
239///     #[api_version(2)]
240///     pub trait Balance {
241///         /// Get the balance.
242///         fn get_balance() -> u64;
243///         /// Set the balance.
244///         fn set_balance(val: u64);
245///         /// Transfer the balance to another user id
246///         #[api_version(3)]
247///         fn transfer_balance(uid: u64);
248///         /// Clears the balance
249///         #[api_version(4)]
250///         fn clear_balance();
251///     }
252/// }
253///
254/// # fn main() {}
255/// ```
256/// Note that the latest version (4 in our example above) always contains all methods from all
257/// the versions before.
258///
259/// ## Note on deprecation.
260///
261/// - Usage of `deprecated` attribute will propagate deprecation information to the metadata.
262/// - For general usage examples of `deprecated` attribute please refer to <https://doc.rust-lang.org/nightly/reference/attributes/diagnostics.html#the-deprecated-attribute>
263pub use sp_api_proc_macro::decl_runtime_apis;
264
265/// Tags given trait implementations as runtime apis.
266///
267/// All traits given to this macro, need to be declared with the
268/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro. The implementation of the trait
269/// should follow the declaration given to the
270/// [`decl_runtime_apis!`](macro.decl_runtime_apis.html) macro, besides the `Block` type that
271/// is required as first generic parameter for each runtime api trait. When implementing a
272/// runtime api trait, it is required that the trait is referenced by a path, e.g. `impl
273/// my_trait::MyTrait for Runtime`. The macro will use this path to access the declaration of
274/// the trait for the runtime side.
275///
276/// The macro also generates the api implementations for the client side and provides it
277/// through the `RuntimeApi` type. The `RuntimeApi` is hidden behind a `feature` called `std`.
278///
279/// To expose version information about all implemented api traits, the constant
280/// `RUNTIME_API_VERSIONS` is generated. This constant should be used to instantiate the `apis`
281/// field of `RuntimeVersion`.
282///
283/// # Example
284///
285/// ```rust
286/// extern crate alloc;
287/// #
288/// # use sp_runtime::{ExtrinsicInclusionMode, traits::Block as BlockT};
289/// # use sp_test_primitives::Block;
290/// #
291/// # /// The declaration of the `Runtime` type is done by the `construct_runtime!` macro
292/// # /// in a real runtime.
293/// # pub enum Runtime {}
294/// #
295/// # sp_api::decl_runtime_apis! {
296/// #     /// Declare the api trait.
297/// #     pub trait Balance {
298/// #         /// Get the balance.
299/// #         fn get_balance() -> u64;
300/// #         /// Set the balance.
301/// #         fn set_balance(val: u64);
302/// #     }
303/// #     pub trait BlockBuilder {
304/// #        fn build_block() -> Block;
305/// #     }
306/// # }
307///
308/// /// All runtime api implementations need to be done in one call of the macro!
309/// sp_api::impl_runtime_apis! {
310/// #   impl sp_api::Core<Block> for Runtime {
311/// #       fn version() -> sp_version::RuntimeVersion {
312/// #           unimplemented!()
313/// #       }
314/// #       fn execute_block(_block: Block) {}
315/// #       fn initialize_block(_header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode {
316/// #           unimplemented!()
317/// #       }
318/// #   }
319///
320///     impl self::Balance<Block> for Runtime {
321///         fn get_balance() -> u64 {
322///             1
323///         }
324///         fn set_balance(_bal: u64) {
325///             // Store the balance
326///         }
327///     }
328///
329///     impl self::BlockBuilder<Block> for Runtime {
330///         fn build_block() -> Block {
331///              unimplemented!("Please implement me!")
332///         }
333///     }
334/// }
335///
336/// /// Runtime version. This needs to be declared for each runtime.
337/// pub const VERSION: sp_version::RuntimeVersion = sp_version::RuntimeVersion {
338///     spec_name: alloc::borrow::Cow::Borrowed("node"),
339///     impl_name: alloc::borrow::Cow::Borrowed("test-node"),
340///     authoring_version: 1,
341///     spec_version: 1,
342///     impl_version: 0,
343///     // Here we are exposing the runtime api versions.
344///     apis: RUNTIME_API_VERSIONS,
345///     transaction_version: 1,
346///     system_version: 1,
347/// };
348///
349/// # fn main() {}
350/// ```
351///
352/// # Implementing specific api version
353///
354/// If `decl_runtime_apis!` declares multiple versions for an api `impl_runtime_apis!`
355/// should specify which version it implements by adding `api_version` attribute to the
356/// `impl` block. If omitted - the base/default version is implemented. Here is an example:
357/// ```ignore
358/// sp_api::impl_runtime_apis! {
359///     #[api_version(3)]
360///     impl self::Balance<Block> for Runtime {
361///          // implementation
362///     }
363/// }
364/// ```
365/// In this case `Balance` api version 3 is being implemented for `Runtime`. The `impl` block
366/// must contain all methods declared in version 3 and below.
367///
368/// # Conditional version implementation
369///
370/// `impl_runtime_apis!` supports `cfg_attr` attribute for conditional compilation. For example
371/// let's say you want to implement a staging version of the runtime api and put it behind a
372/// feature flag. You can do it this way:
373/// ```ignore
374/// pub enum Runtime {}
375/// sp_api::decl_runtime_apis! {
376///     pub trait ApiWithStagingMethod {
377///         fn stable_one(data: u64);
378///
379///         #[api_version(99)]
380///         fn staging_one();
381///     }
382/// }
383///
384/// sp_api::impl_runtime_apis! {
385///     #[cfg_attr(feature = "enable-staging-api", api_version(99))]
386///     impl self::ApiWithStagingMethod<Block> for Runtime {
387///         fn stable_one(_: u64) {}
388///
389///         #[cfg(feature = "enable-staging-api")]
390///         fn staging_one() {}
391///     }
392/// }
393/// ```
394///
395/// [`decl_runtime_apis!`] declares two version of the api - 1 (the default one, which is
396/// considered stable in our example) and 99 (which is considered staging). In
397/// `impl_runtime_apis!` a `cfg_attr` attribute is attached to the `ApiWithStagingMethod`
398/// implementation. If the code is compiled with  `enable-staging-api` feature a version 99 of
399/// the runtime api will be built which will include `staging_one`. Note that `staging_one`
400/// implementation is feature gated by `#[cfg(feature = ... )]` attribute.
401///
402/// If the code is compiled without `enable-staging-api` version 1 (the default one) will be
403/// built which doesn't include `staging_one`.
404///
405/// `cfg_attr` can also be used together with `api_version`. For the next snippet will build
406/// version 99 if `enable-staging-api` is enabled and version 2 otherwise because both
407/// `cfg_attr` and `api_version` are attached to the impl block:
408/// ```ignore
409/// #[cfg_attr(feature = "enable-staging-api", api_version(99))]
410/// #[api_version(2)]
411/// impl self::ApiWithStagingAndVersionedMethods<Block> for Runtime {
412///  // impl skipped
413/// }
414/// ```
415pub use sp_api_proc_macro::impl_runtime_apis;
416
417/// Mocks given trait implementations as runtime apis.
418///
419/// Accepts similar syntax as [`impl_runtime_apis!`] and generates simplified mock
420/// implementations of the given runtime apis. The difference in syntax is that the trait does
421/// not need to be referenced by a qualified path, methods accept the `&self` parameter and the
422/// error type can be specified as associated type. If no error type is specified [`String`] is
423/// used as error type.
424///
425/// Besides implementing the given traits, the [`Core`] and [`ApiExt`] are implemented
426/// automatically.
427///
428/// # Example
429///
430/// ```rust
431/// # use sp_runtime::traits::Block as BlockT;
432/// # use sp_test_primitives::Block;
433/// #
434/// # sp_api::decl_runtime_apis! {
435/// #     /// Declare the api trait.
436/// #     pub trait Balance {
437/// #         /// Get the balance.
438/// #         fn get_balance() -> u64;
439/// #         /// Set the balance.
440/// #         fn set_balance(val: u64);
441/// #     }
442/// #     pub trait BlockBuilder {
443/// #        fn build_block() -> Block;
444/// #     }
445/// # }
446/// struct MockApi {
447///     balance: u64,
448/// }
449///
450/// /// All runtime api mock implementations need to be done in one call of the macro!
451/// sp_api::mock_impl_runtime_apis! {
452///     impl Balance<Block> for MockApi {
453///         /// Here we take the `&self` to access the instance.
454///         fn get_balance(&self) -> u64 {
455///             self.balance
456///         }
457///         fn set_balance(_bal: u64) {
458///             // Store the balance
459///         }
460///     }
461///
462///     impl BlockBuilder<Block> for MockApi {
463///         fn build_block() -> Block {
464///              unimplemented!("Not Required in tests")
465///         }
466///     }
467/// }
468///
469/// # fn main() {}
470/// ```
471///
472/// # `advanced` attribute
473///
474/// This attribute can be placed above individual function in the mock implementation to
475/// request more control over the function declaration. From the client side each runtime api
476/// function is called with the `at` parameter that is a [`Hash`](sp_runtime::traits::Hash).
477/// When using the `advanced` attribute, the macro expects that the first parameter of the
478/// function is this `at` parameter. Besides that the macro also doesn't do the automatic
479/// return value rewrite, which means that full return value must be specified. The full return
480/// value is constructed like [`Result`]`<<ReturnValue>, Error>` while `ReturnValue` being the
481/// return value that is specified in the trait declaration.
482///
483/// ## Example
484/// ```rust
485/// # use sp_runtime::traits::Block as BlockT;
486/// # use sp_test_primitives::Block;
487/// # use codec;
488/// #
489/// # sp_api::decl_runtime_apis! {
490/// #     /// Declare the api trait.
491/// #     pub trait Balance {
492/// #         /// Get the balance.
493/// #         fn get_balance() -> u64;
494/// #         /// Set the balance.
495/// #         fn set_balance(val: u64);
496/// #     }
497/// # }
498/// struct MockApi {
499///     balance: u64,
500/// }
501///
502/// sp_api::mock_impl_runtime_apis! {
503///     impl Balance<Block> for MockApi {
504///         #[advanced]
505///         fn get_balance(&self, at: <Block as BlockT>::Hash) -> Result<u64, sp_api::ApiError> {
506///             println!("Being called at: {}", at);
507///
508///             Ok(self.balance.into())
509///         }
510///         #[advanced]
511///         fn set_balance(at: <Block as BlockT>::Hash, val: u64) -> Result<(), sp_api::ApiError> {
512///             println!("Being called at: {}", at);
513///
514///             Ok(().into())
515///         }
516///     }
517/// }
518///
519/// # fn main() {}
520/// ```
521pub use sp_api_proc_macro::mock_impl_runtime_apis;
522
523/// A type that records all accessed trie nodes and generates a proof out of it.
524#[cfg(feature = "std")]
525pub type ProofRecorder<B> = sp_trie::recorder::Recorder<HashingFor<B>>;
526
527#[cfg(feature = "std")]
528pub type StorageChanges<Block> = sp_state_machine::StorageChanges<HashingFor<Block>>;
529
530/// Something that can be constructed to a runtime api.
531#[cfg(feature = "std")]
532pub trait ConstructRuntimeApi<Block: BlockT, C: CallApiAt<Block>> {
533	/// The actual runtime api that will be constructed.
534	type RuntimeApi: ApiExt<Block>;
535
536	/// Construct an instance of the runtime api.
537	fn construct_runtime_api(call: &C) -> ApiRef<Self::RuntimeApi>;
538}
539
540#[docify::export]
541/// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger).
542pub fn init_runtime_logger() {
543	#[cfg(not(feature = "disable-logging"))]
544	sp_runtime::runtime_logger::RuntimeLogger::init();
545}
546
547/// An error describing which API call failed.
548#[cfg(feature = "std")]
549#[derive(Debug, thiserror::Error)]
550pub enum ApiError {
551	#[error("Failed to decode return value of {function}: {error} raw data: {raw:?}")]
552	FailedToDecodeReturnValue {
553		function: &'static str,
554		#[source]
555		error: codec::Error,
556		raw: Vec<u8>,
557	},
558	#[error("Failed to convert return value from runtime to node of {function}")]
559	FailedToConvertReturnValue {
560		function: &'static str,
561		#[source]
562		error: codec::Error,
563	},
564	#[error("Failed to convert parameter `{parameter}` from node to runtime of {function}")]
565	FailedToConvertParameter {
566		function: &'static str,
567		parameter: &'static str,
568		#[source]
569		error: codec::Error,
570	},
571	#[error("The given `StateBackend` isn't a `TrieBackend`.")]
572	StateBackendIsNotTrie,
573	#[error(transparent)]
574	Application(#[from] Box<dyn std::error::Error + Send + Sync>),
575	#[error("Api called for an unknown Block: {0}")]
576	UnknownBlock(String),
577	#[error("Using the same api instance to call into multiple independent blocks.")]
578	UsingSameInstanceForDifferentBlocks,
579}
580
581/// Extends the runtime api implementation with some common functionality.
582#[cfg(feature = "std")]
583pub trait ApiExt<Block: BlockT> {
584	/// Execute the given closure inside a new transaction.
585	///
586	/// Depending on the outcome of the closure, the transaction is committed or rolled-back.
587	///
588	/// The internal result of the closure is returned afterwards.
589	fn execute_in_transaction<F: FnOnce(&Self) -> TransactionOutcome<R>, R>(&self, call: F) -> R
590	where
591		Self: Sized;
592
593	/// Checks if the given api is implemented and versions match.
594	fn has_api<A: RuntimeApiInfo + ?Sized>(&self, at_hash: Block::Hash) -> Result<bool, ApiError>
595	where
596		Self: Sized;
597
598	/// Check if the given api is implemented and the version passes a predicate.
599	fn has_api_with<A: RuntimeApiInfo + ?Sized, P: Fn(u32) -> bool>(
600		&self,
601		at_hash: Block::Hash,
602		pred: P,
603	) -> Result<bool, ApiError>
604	where
605		Self: Sized;
606
607	/// Returns the version of the given api.
608	fn api_version<A: RuntimeApiInfo + ?Sized>(
609		&self,
610		at_hash: Block::Hash,
611	) -> Result<Option<u32>, ApiError>
612	where
613		Self: Sized;
614
615	/// Start recording all accessed trie nodes for generating proofs.
616	fn record_proof(&mut self);
617
618	/// Extract the recorded proof.
619	///
620	/// This stops the proof recording.
621	///
622	/// If `record_proof` was not called before, this will return `None`.
623	fn extract_proof(&mut self) -> Option<StorageProof>;
624
625	/// Returns the current active proof recorder.
626	fn proof_recorder(&self) -> Option<ProofRecorder<Block>>;
627
628	/// Convert the api object into the storage changes that were done while executing runtime
629	/// api functions.
630	///
631	/// After executing this function, all collected changes are reset.
632	fn into_storage_changes<B: StateBackend<HashingFor<Block>>>(
633		&self,
634		backend: &B,
635		parent_hash: Block::Hash,
636	) -> Result<StorageChanges<Block>, String>
637	where
638		Self: Sized;
639
640	/// Set the [`CallContext`] to be used by the runtime api calls done by this instance.
641	fn set_call_context(&mut self, call_context: CallContext);
642
643	/// Register an [`Extension`] that will be accessible while executing a runtime api call.
644	fn register_extension<E: Extension>(&mut self, extension: E);
645}
646
647/// Parameters for [`CallApiAt::call_api_at`].
648#[cfg(feature = "std")]
649pub struct CallApiAtParams<'a, Block: BlockT> {
650	/// The block id that determines the state that should be setup when calling the function.
651	pub at: Block::Hash,
652	/// The name of the function that should be called.
653	pub function: &'static str,
654	/// The encoded arguments of the function.
655	pub arguments: Vec<u8>,
656	/// The overlayed changes that are on top of the state.
657	pub overlayed_changes: &'a RefCell<OverlayedChanges<HashingFor<Block>>>,
658	/// The call context of this call.
659	pub call_context: CallContext,
660	/// The optional proof recorder for recording storage accesses.
661	pub recorder: &'a Option<ProofRecorder<Block>>,
662	/// The extensions that should be used for this call.
663	pub extensions: &'a RefCell<Extensions>,
664}
665
666/// Something that can call into an api at a given block.
667#[cfg(feature = "std")]
668pub trait CallApiAt<Block: BlockT> {
669	/// The state backend that is used to store the block states.
670	type StateBackend: StateBackend<HashingFor<Block>> + AsTrieBackend<HashingFor<Block>>;
671
672	/// Calls the given api function with the given encoded arguments at the given block and returns
673	/// the encoded result.
674	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError>;
675
676	/// Returns the runtime version at the given block.
677	fn runtime_version_at(&self, at_hash: Block::Hash) -> Result<RuntimeVersion, ApiError>;
678
679	/// Get the state `at` the given block.
680	fn state_at(&self, at: Block::Hash) -> Result<Self::StateBackend, ApiError>;
681
682	/// Initialize the `extensions` for the given block `at` by using the global extensions factory.
683	fn initialize_extensions(
684		&self,
685		at: Block::Hash,
686		extensions: &mut Extensions,
687	) -> Result<(), ApiError>;
688}
689
690#[cfg(feature = "std")]
691impl<Block: BlockT, T: CallApiAt<Block>> CallApiAt<Block> for std::sync::Arc<T> {
692	type StateBackend = T::StateBackend;
693
694	fn call_api_at(&self, params: CallApiAtParams<Block>) -> Result<Vec<u8>, ApiError> {
695		(**self).call_api_at(params)
696	}
697
698	fn runtime_version_at(
699		&self,
700		at_hash: <Block as BlockT>::Hash,
701	) -> Result<RuntimeVersion, ApiError> {
702		(**self).runtime_version_at(at_hash)
703	}
704
705	fn state_at(&self, at: <Block as BlockT>::Hash) -> Result<Self::StateBackend, ApiError> {
706		(**self).state_at(at)
707	}
708
709	fn initialize_extensions(
710		&self,
711		at: <Block as BlockT>::Hash,
712		extensions: &mut Extensions,
713	) -> Result<(), ApiError> {
714		(**self).initialize_extensions(at, extensions)
715	}
716}
717
718/// Auxiliary wrapper that holds an api instance and binds it to the given lifetime.
719#[cfg(feature = "std")]
720pub struct ApiRef<'a, T>(T, std::marker::PhantomData<&'a ()>);
721
722#[cfg(feature = "std")]
723impl<'a, T> From<T> for ApiRef<'a, T> {
724	fn from(api: T) -> Self {
725		ApiRef(api, Default::default())
726	}
727}
728
729#[cfg(feature = "std")]
730impl<'a, T> std::ops::Deref for ApiRef<'a, T> {
731	type Target = T;
732
733	fn deref(&self) -> &Self::Target {
734		&self.0
735	}
736}
737
738#[cfg(feature = "std")]
739impl<'a, T> std::ops::DerefMut for ApiRef<'a, T> {
740	fn deref_mut(&mut self) -> &mut T {
741		&mut self.0
742	}
743}
744
745/// Something that provides a runtime api.
746#[cfg(feature = "std")]
747pub trait ProvideRuntimeApi<Block: BlockT> {
748	/// The concrete type that provides the api.
749	type Api: ApiExt<Block>;
750
751	/// Returns the runtime api.
752	/// The returned instance will keep track of modifications to the storage. Any successful
753	/// call to an api function, will `commit` its changes to an internal buffer. Otherwise,
754	/// the modifications will be `discarded`. The modifications will not be applied to the
755	/// storage, even on a `commit`.
756	fn runtime_api(&self) -> ApiRef<Self::Api>;
757}
758
759/// Something that provides information about a runtime api.
760#[cfg(feature = "std")]
761pub trait RuntimeApiInfo {
762	/// The identifier of the runtime api.
763	const ID: [u8; 8];
764	/// The version of the runtime api.
765	const VERSION: u32;
766}
767
768/// The number of bytes required to encode a [`RuntimeApiInfo`].
769///
770/// 8 bytes for `ID` and 4 bytes for a version.
771pub const RUNTIME_API_INFO_SIZE: usize = 12;
772
773/// Crude and simple way to serialize the `RuntimeApiInfo` into a bunch of bytes.
774pub const fn serialize_runtime_api_info(id: [u8; 8], version: u32) -> [u8; RUNTIME_API_INFO_SIZE] {
775	let version = version.to_le_bytes();
776
777	let mut r = [0; RUNTIME_API_INFO_SIZE];
778	r[0] = id[0];
779	r[1] = id[1];
780	r[2] = id[2];
781	r[3] = id[3];
782	r[4] = id[4];
783	r[5] = id[5];
784	r[6] = id[6];
785	r[7] = id[7];
786
787	r[8] = version[0];
788	r[9] = version[1];
789	r[10] = version[2];
790	r[11] = version[3];
791	r
792}
793
794/// Deserialize the runtime API info serialized by [`serialize_runtime_api_info`].
795pub fn deserialize_runtime_api_info(bytes: [u8; RUNTIME_API_INFO_SIZE]) -> ([u8; 8], u32) {
796	let id: [u8; 8] = bytes[0..8]
797		.try_into()
798		.expect("the source slice size is equal to the dest array length; qed");
799
800	let version = u32::from_le_bytes(
801		bytes[8..12]
802			.try_into()
803			.expect("the source slice size is equal to the array length; qed"),
804	);
805
806	(id, version)
807}
808
809decl_runtime_apis! {
810	/// The `Core` runtime api that every Substrate runtime needs to implement.
811	#[core_trait]
812	#[api_version(5)]
813	pub trait Core {
814		/// Returns the version of the runtime.
815		fn version() -> RuntimeVersion;
816		/// Execute the given block.
817		fn execute_block(block: Block);
818		/// Initialize a block with the given header.
819		#[changed_in(5)]
820		#[renamed("initialise_block", 2)]
821		fn initialize_block(header: &<Block as BlockT>::Header);
822		/// Initialize a block with the given header and return the runtime executive mode.
823		fn initialize_block(header: &<Block as BlockT>::Header) -> ExtrinsicInclusionMode;
824	}
825
826	/// The `Metadata` api trait that returns metadata for the runtime.
827	#[api_version(2)]
828	pub trait Metadata {
829		/// Returns the metadata of a runtime.
830		fn metadata() -> OpaqueMetadata;
831
832		/// Returns the metadata at a given version.
833		///
834		/// If the given `version` isn't supported, this will return `None`.
835		/// Use [`Self::metadata_versions`] to find out about supported metadata version of the runtime.
836		fn metadata_at_version(version: u32) -> Option<OpaqueMetadata>;
837
838		/// Returns the supported metadata versions.
839		///
840		/// This can be used to call `metadata_at_version`.
841		fn metadata_versions() -> alloc::vec::Vec<u32>;
842	}
843}
844
845sp_core::generate_feature_enabled_macro!(std_enabled, feature = "std", $);
846sp_core::generate_feature_enabled_macro!(std_disabled, not(feature = "std"), $);
847sp_core::generate_feature_enabled_macro!(frame_metadata_enabled, feature = "frame-metadata", $);