Skip to content

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.

Imports

Named
import { RpcResponse } from 'ox'

Examples

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

Raw Mode

If raw is true, the response will be returned as an object with result and error properties instead of returning the result directly and throwing errors.

import { RpcRequest, RpcResponse } from 'ox'
 
const store = RpcRequest.createStore()
 
const request = store.prepare({
  method: 'eth_blockNumber',
})
 
const response = RpcResponse.parse({}, {
  request,
  raw: true, 
})
 
response.
result?: `0x${string}` | undefined
result
response.
error?: RpcResponse.ErrorObject | undefined
error

Definition

function parse<response, returnType, raw>(
  response: response,
  options?: parse.Options<returnType, raw>,
): parse.ReturnType<unknown extends response ? returnType : response extends RpcResponse ? response extends {
    result: infer result;
} ? result : never : returnType, raw>

Source: src/RpcResponse.ts

Parameters

response

  • Type: response

Opaque JSON-RPC response object.

options

  • Type: parse.Options<returnType, raw>
  • Optional

Parsing options.

options.raw

  • Type: boolean | raw
  • Optional

Enables raw mode – responses will return an object with result and error properties instead of returning the result directly and throwing errors.

  • true: a JSON-RPC response object will be returned with result and error properties.
  • false: the JSON-RPC response object's result property will be returned directly, and JSON-RPC Errors will be thrown.

options.request

  • Type: { method: string; params?: unknown; id: number; jsonrpc: "2.0"; _returnType: unknown; } | { _returnType: returnType; }
  • Optional

JSON-RPC Method that was used to make the request. Used for typing the response.

Return Type

Typed JSON-RPC result, or response object (if raw is true).

parse.ReturnType<unknown extends response ? returnType : response extends RpcResponse ? response extends { result: infer result; } ? result : never : returnType, raw>