alexd10s
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    4
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # Add custom RPC to the node Remote Procedure Calls, or RPCs, are a way for an external program—for example, a browser or front-end application—to communicate with a Substrate node. Substrate comes with several default [RPCs](https://polkadot.js.org/docs/substrate/rpc/). ### Learning Objectives By the end of this document, you should be able to: * Implement a custom RPC call in your pallet. * Add your custom RPC methods in your node. * Query them using Postman or Curl. We use the Substrate node template and we will add a method in the template pallet. ### Set up Clone the substrate node template repository and compile it. ``` git clone https://github.com/substrate-developer-hub/substrate-node-template cd substrate-node-template cargo build --release ``` ### Add custom RPC in our pallet Modify the pallet to add the custom RPC calls. The pallet template has a function `do_something` that store a value in the storage. For this tutorial we are going to create an RPC call that reads that value in the storage. 1. Inside the pallet template folder create a new folder called rpc: `pallets/template/src/rpc` 2. The RPC call interacts with the pallet-tempate runtime API to call the function that gets the value. For that we will create a pallet-template-runtime-api. Create a new folder inside the rpc folder: `pallets/template/src/rpc/runtime-api` *This folder can live anywhere you like, but because it defines an API that is closely related to a particular pallet, it makes sense to include the API definition in the pallet's directory.* 3. Create the `Cargo.toml` file for the runtime-api package. In `pallets/template/src/rpc/runtime-api/Cargo.toml` ``` [package] name = "pallet-template-runtime-api" authors = ["Alex Bean <https://github.com/AlexD10S>"] version = "1.0.0" edition = "2021" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] sp-api = { git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28", default-features = false } [features] default = ["std"] std = [ "sp-api/std", ] ``` 4. And define the runtime API interface: `pallets/template/src/rpc/runtime-api/src/lib.rs` The code to define the API is quite simple, and looks almost like any old Rust trait. The one addition is that it must be placed in the decl_runtime_apis! macro. This macro allows the outer node to query the runtime API at specific blocks. Although this runtime API only provides a single function, you may write as many as you like. ``` #![cfg_attr(not(feature = "std"), no_std)] // Here we declare the runtime API. It is implemented it the `impl` block in // runtime file (the `runtime-api/src/lib.rs`) sp_api::decl_runtime_apis! { pub trait TemplateApi { fn get_value() -> u32; } } ``` 5. Now define the RPC. Create a folder Cargo.toml in the rpc folder: `pallets/template/src/rpc/Cargo.toml` Here import the runtime-api defined before: `pallet-template-runtime-api = { path = "./runtime-api", default-features = false }` And the [JSON-RPC library] for Rust (https://github.com/paritytech/jsonrpsee) `jsonrpsee = { version = "0.15.1", features = ["server", "macros"] }` *Full file:* ``` [package] name = "pallet-template-rpc" version = "1.0.0" edition = "2021" authors = ["Alex Bean <https://github.com/AlexD10S>"] description = 'RPC methods for the template pallet' [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive", ] } jsonrpsee = { version = "0.15.1", features = ["server", "macros"] } # Substrate packages sp-api = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } sp-blockchain = { default-features = false, version = "4.0.0-dev", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } sp-runtime = { default-features = false, version = "6.0.0", git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.28" } # local packages pallet-template-runtime-api = { path = "./runtime-api", default-features = false } [features] default = ["std"] std = [ "sp-api/std", "sp-runtime/std", "pallet-template-runtime-api/std" ] ``` 6. Inside the rpc folder create a src folder with a lib.rs where we will define the Pallet Template RPC. * 6.1. First define the RPC interface. Notice that the struct that implements the RPC needs a reference to the client. This is necessary so we can actually call into the runtime. And the struct is generic over the BlockHash type. This is because it will call a runtime API, and runtime APIs must always be called at a specific block. ``` #[rpc(client, server)] pub trait TemplateApi<BlockHash> { #[method(name = "template_getValue")] fn get_value(&self, at: Option<BlockHash>) -> RpcResult<u32>; } /// A struct that implements the `TemplateApi`. pub struct TemplatePallet<C, Block> { // If you have more generics, no need to TemplatePallet<C, M, N, P, ...> // just use a tuple like TemplatePallet<C, (M, N, P, ...)> client: Arc<C>, _marker: std::marker::PhantomData<Block>, } impl<C, Block> TemplatePallet<C, Block> { /// Create new `TemplatePallet` instance with the given reference to the client. pub fn new(client: Arc<C>) -> Self { Self { client, _marker: Default::default() } } } ``` * 6.2. Now the RPC's implementation. The additional syntax here is related to calling the runtime at a specific block, as well as ensuring that the runtime we're calling actually has the correct runtime API available. ``` impl<C, Block> TemplateApiServer<<Block as BlockT>::Hash> for TemplatePallet<C, Block> where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>, C::Api: TemplateRuntimeApi<Block>, { fn get_value(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<u32> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(||self.client.info().best_hash)); api.get_value(&at).map_err(runtime_error_into_rpc_err) } } const RUNTIME_ERROR: i32 = 1; /// Converts a runtime trap into an RPC error. fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError { CallError::Custom(ErrorObject::owned( RUNTIME_ERROR, "Runtime error", Some(format!("{:?}", err)), )) .into() } ``` * 6.3. The full file in `pallets/template/src/rpc/src/lib.rs`: ``` pub use pallet_template_runtime_api::TemplateApi as TemplateRuntimeApi; use jsonrpsee::{ core::{Error as JsonRpseeError, RpcResult}, proc_macros::rpc, types::error::{CallError, ErrorObject}, }; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; use sp_runtime::{generic::BlockId, traits::Block as BlockT}; use std::sync::Arc; #[rpc(client, server)] pub trait TemplateApi<BlockHash> { #[method(name = "template_getValue")] fn get_value(&self, at: Option<BlockHash>) -> RpcResult<u32>; } /// A struct that implements the `TemplateApi`. pub struct TemplatePallet<C, Block> { // If you have more generics, no need to TemplatePallet<C, M, N, P, ...> // just use a tuple like TemplatePallet<C, (M, N, P, ...)> client: Arc<C>, _marker: std::marker::PhantomData<Block>, } impl<C, Block> TemplatePallet<C, Block> { /// Create new `TemplatePallet` instance with the given reference to the client. pub fn new(client: Arc<C>) -> Self { Self { client, _marker: Default::default() } } } impl<C, Block> TemplateApiServer<<Block as BlockT>::Hash> for TemplatePallet<C, Block> where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi<Block> + HeaderBackend<Block>, C::Api: TemplateRuntimeApi<Block>, { fn get_value(&self, at: Option<<Block as BlockT>::Hash>) -> RpcResult<u32> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(||self.client.info().best_hash)); api.get_value(&at).map_err(runtime_error_into_rpc_err) } } const RUNTIME_ERROR: i32 = 1; /// Converts a runtime trap into an RPC error. fn runtime_error_into_rpc_err(err: impl std::fmt::Debug) -> JsonRpseeError { CallError::Custom(ErrorObject::owned( RUNTIME_ERROR, "Runtime error", Some(format!("{:?}", err)), )) .into() } ``` 7. Modify the pallet implementation to have a function called get_value(), in `pallets/template/src/lib.rs` Change: `#[pallet::getter(fn something)]` with `#[pallet::getter(fn get_value)]` ### Set up the node for the pallet-template Custom RPC 1. Implement now in the runtime of the node the function get_value() declared in the pallet-template-runtime-api Add the runtime-api pallet in the configuration file of the pallet, in: `runtime/Cargo.toml` ``` # local packages pallet-template-runtime-api = { path = "../pallets/template/rpc/runtime-api", default-features = false }} ``` And add in the std: ``` std = [ ..., "pallet-template-runtime-api/std", ] ``` Add the implementation of the runtime function in the pallet: `runtime/src/lib.rs` ``` impl pallet_template_runtime_api::TemplateApi<Block> for Runtime { fn get_value() -> u32 { TemplateModule::get_value().unwrap_or(0) } } ``` 2. Install the RPC in our node To add the node-specific RPC methods modify the files in the node to include our pallet RPC code manually. * First adding the new pallet in the configuration file in the node/Config.toml: `pallet-template-rpc = { version = "1.0.0", path = "../pallets/template/rpc" }` * Then adding the node-specific RPC methods. Modify the file node/rpc.rs and there include the pallet template RPC code. ``` /// Instantiate all full RPC extensions. pub fn create_full<C, P>( deps: FullDeps<C, P>, ) -> Result<RpcModule<()>, Box<dyn std::error::Error + Send + Sync>> where C: ProvideRuntimeApi<Block>, C: HeaderBackend<Block> + HeaderMetadata<Block, Error = BlockChainError> + 'static, C: Send + Sync + 'static, C::Api: substrate_frame_rpc_system::AccountNonceApi<Block, AccountId, Index>, C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi<Block, Balance>, C::Api: pallet_template_rpc::TemplateRuntimeApi<Block>, C::Api: BlockBuilder<Block>, P: TransactionPool + 'static, { use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; use substrate_frame_rpc_system::{System, SystemApiServer}; use pallet_template_rpc::{TemplatePallet, TemplateApiServer}; let mut module = RpcModule::new(()); let FullDeps { client, pool, deny_unsafe } = deps; module.merge(System::new(client.clone(), pool.clone(), deny_unsafe).into_rpc())?; module.merge(TransactionPayment::new(client.clone()).into_rpc())?; module.merge(TemplatePallet::new(client).into_rpc())?; // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed // to call into the runtime. // `module.merge(YourRpcTrait::into_rpc(YourRpcStruct::new(ReferenceToClient, ...)))?;` Ok(module) } ``` **Well done!** 👏 👏 ### Query the RPC calls Now let's see how to query this call. Compile the node and run it: ``` cargo build --release ./target/release/node-template --dev ``` To check the pallet RPC methods has been include open PokadotJS and go under the tab Development > RPC calls. In the dropdown "Call the selected endpoint", pick rpc and the function methods() and you will see all the RPC methods available, included the one that we have just included. ![](https://i.imgur.com/zR9mVtj.png) To test it, we are going to first store a value using the methods of the pallet. Going under Development > Extrinsics, in the Dropdown pick the templateModule and the function doSomething(something) and fill the value something, like in the picture below. ![](https://i.imgur.com/eOS2VW7.png) We have stored a value there, and we can test our RPC method now to get that value. Is possible to test the RPC request with Postman or CURL. * An example with Postman, a POST method to query the template_getValue method: ![](https://i.imgur.com/vpqpVl1.png) * And an example using CURL, in the command line: `curl -H "Content-Type: application/json" -d '{"id":1, "jsonrpc":"2.0", "method": "template_getValue", "params": []}' http://localhost:9933/` Will return the same as Postman in the console: `{"jsonrpc":"2.0","result":100,"id":1}` A full example of the code of this tutorial can be found here: https://github.com/AlexD10S/susbtrate-node-template/tree/rpc-custom-methods

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully