RPC Client

Most of the interactions with Substrate network is made through RPC interface.

Basic RPC interface is declared this way:

interface Rpc {
    suspend fun send(request: RpcRequest): RpcResponse
    suspend fun <P: Any, R: Any> sendRequest(block: RpcRequestBuilder<P, R>.() -> Unit): R?
}

So, basically you can only send requests and receive them. But there are two ways:

Send some request which you can instantiate using next class:

@Serializable
data class RpcRequest constructor(
    @EncodeDefault val jsonrpc: String = rpcVersion,
    val id: Long,
    val method: String,
    val params: JsonElement = JsonArray(listOf())
)

Simply tell the method of RPC, and provide already predecoded params in JSON.

To send a request you need to run it like that:

val rpc: Rpc
val response: RpcResponse = rpc.sendRequest(RpcRequest(
    method = "rpc_method",
    params = JsonArray(
        listOf(UUID.randomUUID().toString().hex.encode(includePrefix = true))
    )
))

val error: RpcResponseError? = response.error
val result: JsonElement? = response.result

You will receive both error and result as nullable. But at least one of them should exist unless you get a real nullable response, like if you want to get data about non-existing account. Error is combination of error code and message. And result is encoded json element. Feel free to try decoding this to your desired object.

Send the request using builder:

val rpc: Rpc
val response: String = rpc.sendRequest {
    method = "rpc_method"
    responseType = String::class
    params = listOf(UUID.randomUUID().toString().hex.encode(includePrefix = true))
    paramsType = String::class
}

Last updated