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