blockchain-api
Version:
API utilities for interacting with the Exatechl2 blockchain
40 lines (35 loc) • 1.09 kB
text/typescript
import fetch from 'node-fetch';
import { getRpcUrl } from '../config';
/**
* Make an RPC call to the blockchain
* @template T - The expected return type
* @param {string} method - The RPC method to call
* @param {unknown[]} params - The parameters for the RPC method
* @returns {Promise<T>} - A promise that resolves with the result of the RPC call
*/
export async function callRpc<T = unknown>(method: string, params: unknown[] = []): Promise<T> {
try {
const rpcUrl = getRpcUrl();
const response = await fetch(rpcUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method,
params,
}),
});
const data = await response.json();
if (data.error) {
console.error('RPC Error:', data.error);
throw new Error(data.error.message || 'RPC call failed');
}
return data.result as T;
} catch (error) {
console.error('Error calling RPC:', error);
throw error;
}
}