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;
} | nullblock
Functions
Name | Description |
---|---|
RpcResponse.from | A type-safe interface to instantiate a JSON-RPC response object as per the JSON-RPC 2.0 specification. |
RpcResponse.parse | A type-safe interface to parse a JSON-RPC response object as per the JSON-RPC 2.0 specification, and extract the result. |
Errors
Name | Description |
---|---|
RpcResponse.BaseError | Thrown when a JSON-RPC error has occurred. |
RpcResponse.InternalError | Thrown when an internal JSON-RPC error has occurred. |
RpcResponse.InvalidInputError | Thrown when the input to a JSON-RPC method is invalid. |
RpcResponse.InvalidParamsError | Thrown when the parameters to a JSON-RPC method are invalid. |
RpcResponse.InvalidRequestError | Thrown when a JSON-RPC request is invalid. |
RpcResponse.LimitExceededError | Thrown when a rate-limit is exceeded. |
RpcResponse.MethodNotFoundError | Thrown when a JSON-RPC method is not found. |
RpcResponse.MethodNotSupportedError | Thrown when a JSON-RPC method is not supported. |
RpcResponse.ParseError | Thrown when a JSON-RPC response is invalid. |
RpcResponse.ResourceNotFoundError | Thrown when a JSON-RPC resource is not found. |
RpcResponse.ResourceUnavailableError | Thrown when a JSON-RPC resource is unavailable. |
RpcResponse.TransactionRejectedError | Thrown when a JSON-RPC transaction is rejected. |
RpcResponse.VersionNotSupportedError | Thrown when a JSON-RPC version is not supported. |
Types
Name | Description |
---|---|
RpcResponse.BaseErrorType | |
RpcResponse.ErrorObject | JSON-RPC error object as per the JSON-RPC 2.0 specification. |
RpcResponse.RpcResponse | A JSON-RPC response object as per the JSON-RPC 2.0 specification. |