impl_runtime_apis!() { /* proc-macro */ }
Expand description

Tags given trait implementations as runtime apis.

All traits given to this macro, need to be declared with the decl_runtime_apis! macro. The implementation of the trait should follow the declaration given to the decl_runtime_apis! macro, besides the Block type that is required as first generic parameter for each runtime api trait. When implementing a runtime api trait, it is required that the trait is referenced by a path, e.g. impl my_trait::MyTrait for Runtime. The macro will use this path to access the declaration of the trait for the runtime side.

The macro also generates the api implementations for the client side and provides it through the RuntimeApi type. The RuntimeApi is hidden behind a feature called std.

To expose version information about all implemented api traits, the constant RUNTIME_API_VERSIONS is generated. This constant should be used to instantiate the apis field of RuntimeVersion.

Example

use sp_version::create_runtime_str;

/// All runtime api implementations need to be done in one call of the macro!
sp_api::impl_runtime_apis! {

    impl self::Balance<Block> for Runtime {
        fn get_balance() -> u64 {
            1
        }
        fn set_balance(_bal: u64) {
            // Store the balance
        }
    }

    impl self::BlockBuilder<Block> for Runtime {
        fn build_block() -> Block {
             unimplemented!("Please implement me!")
        }
    }
}

/// Runtime version. This needs to be declared for each runtime.
pub const VERSION: sp_version::RuntimeVersion = sp_version::RuntimeVersion {
    spec_name: create_runtime_str!("node"),
    impl_name: create_runtime_str!("test-node"),
    authoring_version: 1,
    spec_version: 1,
    impl_version: 0,
    // Here we are exposing the runtime api versions.
    apis: RUNTIME_API_VERSIONS,
    transaction_version: 1,
    state_version: 1,
};

Implementing specific api version

If decl_runtime_apis! declares multiple versions for an api impl_runtime_apis! should specify which version it implements by adding api_version attribute to the impl block. If omitted - the base/default version is implemented. Here is an example:

sp_api::impl_runtime_apis! {
    #[api_version(3)]
    impl self::Balance<Block> for Runtime {
         // implementation
    }
}

In this case Balance api version 3 is being implemented for Runtime. The impl block must contain all methods declared in version 3 and below.