Skip to content

RpcResponse

Utility types & functions for working with JSON-RPC 2.0 Responses

Examples

Below are some examples demonstrating common usages of the RpcResponse module:

Instantiating an RPC Response

RPC Responses can be instantiated using RpcResponse.from:

import { RpcResponse } from 'ox'
 
const response = RpcResponse.from({
  id: 0,
  jsonrpc: '2.0',
  result: '0x69420',
})

Parsing an RPC Response

RPC Responses can be parsed using RpcResponse.parse:

import { RpcRequest, RpcResponse } from 'ox'
 
// 1. Create a request store.
const store = RpcRequest.createStore()
 
// 2. Get a request object.
const request = store.prepare({
  method: 'eth_getBlockByNumber',
  params: ['0x1', false],
})
 
// 3. Send the JSON-RPC request via HTTP.
const block = await fetch('https://1.rpc.thirdweb.com', {
  body: JSON.stringify(request),
  headers: {
    'Content-Type': 'application/json',
  },
  method: 'POST',
})
 .then((response) => response.json())
 // 4. Parse the JSON-RPC response into a type-safe result.
 .then((response) => RpcResponse.parse(response, { request }))
 
const block: { baseFeePerGas?: `0x${string}` | undefined; blobGasUsed?: `0x${string}` | undefined; difficulty?: `0x${string}` | undefined; excessBlobGas?: `0x${string}` | undefined; extraData?: Hex | undefined; ... 21 more ...; withdrawalsRoot?: Hex | undefined; } | null
block

Functions

NameDescription
RpcResponse.fromA type-safe interface to instantiate a JSON-RPC response object as per the JSON-RPC 2.0 specification.
RpcResponse.parseA type-safe interface to parse a JSON-RPC response object as per the JSON-RPC 2.0 specification, and extract the result.

Errors

NameDescription
RpcResponse.BaseErrorThrown when a JSON-RPC error has occurred.
RpcResponse.InternalErrorThrown when an internal JSON-RPC error has occurred.
RpcResponse.InvalidInputErrorThrown when the input to a JSON-RPC method is invalid.
RpcResponse.InvalidParamsErrorThrown when the parameters to a JSON-RPC method are invalid.
RpcResponse.InvalidRequestErrorThrown when a JSON-RPC request is invalid.
RpcResponse.LimitExceededErrorThrown when a rate-limit is exceeded.
RpcResponse.MethodNotFoundErrorThrown when a JSON-RPC method is not found.
RpcResponse.MethodNotSupportedErrorThrown when a JSON-RPC method is not supported.
RpcResponse.ParseErrorThrown when a JSON-RPC response is invalid.
RpcResponse.ResourceNotFoundErrorThrown when a JSON-RPC resource is not found.
RpcResponse.ResourceUnavailableErrorThrown when a JSON-RPC resource is unavailable.
RpcResponse.TransactionRejectedErrorThrown when a JSON-RPC transaction is rejected.
RpcResponse.VersionNotSupportedErrorThrown when a JSON-RPC version is not supported.

Types

NameDescription
RpcResponse.BaseErrorType
RpcResponse.ErrorObjectJSON-RPC error object as per the JSON-RPC 2.0 specification.
RpcResponse.RpcResponseA JSON-RPC response object as per the JSON-RPC 2.0 specification.