This deep dive explains how to use underlying primitives in the rpc-core library to construct RPC requests for any methods that aren’t provided by SolanaRpcClient.
The rpc-core library defines a JsonRpc20Request constructor to conveniently construct a Solana JSON RPC request.Populate the JSON object with the method name and JSON serialized parameters of a Solana RPC method. The
constructor also includes a requestId parameter, as per JSON-RPC spec.
After creating the request, create Kotlin serializable classes that define the expected response payload for that request.In the following example, we are defining the expected response of the getLatestBlockhash request using the kotlinx.serialization library.
import kotlinx.serialization.Serializableimport kotlinx.serialization.json.*@Serializableclass BlockhashResponse(val value: BlockhashInfo)@Serializableclass BlockhashInfo( val blockhash: String, val lastValidBlockHeight: Long)// Additionally, define an exception in case of failure during requestclass BlockhashException(message: String? = null, cause: Throwable? = null) : RuntimeException(message, cause)
The rpc-core library defines a HttpNetworkDriver interface that is used to make network requests.
interface HttpRequest { val url: String val method: String val properties: Map<String, String> val body: String?}interface HttpNetworkDriver { suspend fun makeHttpRequest(request: HttpRequest): String}
You can use a common networking package like the Ktor library to implement the makeHttpRequest method. The following
is an example from the Kotlin Jetpack Compose Scaffold sample app.
After putting these parts together, use the Rpc20Driver class to point to an RPC uri, send
the request, and receive a response.
// import com.example.solanakotlincomposescaffold.networking.KtorHttpDriverimport com.solana.networking.Rpc20Driverimport com.solana.rpccore.JsonRpc20Requestimport com.solana.transaction.Blockhashimport java.util.UUIDfun getLatestBlockhash(): Blockhash { // Create the Rpc20Driver and specify the RPC uri and network driver val rpc = Rpc20Driver("https://api.devnet.solana.com", KtorHttpDriver()) // Construct the RPC request val requestId = UUID.randomUUID().toString() val request = createBlockhashRequest(commitment, requestId) // Send the request and provide the serializer for the expected response val response = rpc.makeRequest(request, BlockhashResponse.serializer()) response.error?.let { error -> throw BlockhashException("Could not fetch latest blockhash: ${error.code}, ${error.message}") } // Unwrap the response to receive the base58 blockhash string val base58Blockhash = response.result?.value?.blockhash // Return a `Blockhash` object from the web3-solana library Blockhash.from(base58Blockhash ?: throw BlockhashException("Could not fetch latest blockhash: UnknownError"))}