Skip to content

How to add a JSON RPC method

JinGyeong Jeong edited this page Jun 25, 2018 · 7 revisions

1. Choose a module your method will be placed in.

  • chain module is for reading or writing blockchain, including parcel queue.
  • devel module is for utility functions to debug CodeChain

2. Modify rpc/src/v1/traits/<module name>.rs

chain_getBlockHash example:

/// Gets the hash of the block with given number.
# [rpc(name = "chain_getBlockHash")]
fn get_block_hash(&self, u64) -> Result<Option<H256>>;

The above declaration is part of pub trait Chain. It creates the RPC endpoint to "chain_getBlockHash" which receives u64 parameter. All of the parameters must be the serde-Serializable. See files in src/rpc/v1/types/ directory.

3. Modify rpc/src/v1/impls/<module name>.rs

chain_getBlockHash example:

fn get_block_hash(&self, block_number: u64) -> Result<Option<H256>> {
    Ok(self.client.block_hash(BlockId::Number(block_number)))
}

The above implementation is part of impl Chain for ChainClient. ChainClient holds Client and Miner which are the structs for the blockchain and the parcel queue each.