Skip to main content

Batch Requests

The callPayloadSingle, callMultiplePayloads, and buildJsonRpcPayload methods allow you to send single or multiple JSON-RPC payloads to an OP_NET node. Batch requests are an efficient way to group multiple operations into a single network call, reducing latency and improving performance.


Available Methods

1. Single Payload Call

callPayloadSingle(payload: JsonRpcPayload): Promise<JsonRpcResult>;
  • Parameters:

    • payload: JsonRpcPayload: The JSON-RPC payload to send.
  • Returns:

    • Promise<JsonRpcResult>: The result of the single JSON-RPC call.

2. Multiple Payloads Call

callMultiplePayloads(payloads: JsonRpcPayload[]): Promise<JsonRpcCallResult>;
  • Parameters:

    • payloads: JsonRpcPayload[]: An array of JSON-RPC payloads to send.
  • Returns:

    • Promise<JsonRpcCallResult>: An array of results for each JSON-RPC call in the batch.

3. Build JSON-RPC Payload

buildJsonRpcPayload<T extends JSONRpcMethods>(
method: T,
params: unknown[]
): JsonRpcPayload;
  • Parameters:

    • method: T: The JSON-RPC method to call.
    • params: unknown[]: An array of parameters for the method.
  • Returns:

    • JsonRpcPayload: The constructed JSON-RPC payload.

Example Usage

Build a Payload

import { JSONRpcMethods } from "opnet";

// Example: Get block data for block number 100
const payload = provider.buildJsonRpcPayload(
JSONRpcMethods.GET_BLOCK_BY_NUMBER,
[100]
);

Single Payload Call

const result = await provider.callPayloadSingle(payload);

if ("error" in result) {
console.error("Error:", result.error.message);
} else {
console.log("Block Data:", result.result);
}

Batch Payload Call

const payloads = [
provider.buildJsonRpcPayload(JSONRpcMethods.GET_BLOCK_BY_NUMBER, [100]),
provider.buildJsonRpcPayload(JSONRpcMethods.GET_BLOCK_BY_NUMBER, [101]),
// ... Add multiple payloads here
];

const batchResults = await provider.callMultiplePayloads(payloads);

batchResults.forEach((result, index) => {
if ("error" in result) {
console.error(`Error for Block ${index + 100}:`, result.error.message);
} else {
console.log(`Block ${index + 100} Data:`, result.result);
}
});

Best Practices

  • Always handle errors for individual payloads in the batch response.
  • Batch requests significantly reduce the overhead of multiple network calls, making them ideal for high-performance applications.
  • Use the buildJsonRpcPayload method to ensure payloads are constructed correctly with the appropriate JSONRpcMethods.

What’s Next?

After mastering batch requests, explore: