Skip to content

Instantly share code, notes, and snippets.

@grsLammy
Created February 1, 2024 11:38
Show Gist options
  • Save grsLammy/1adb24b04cd5b239876ef4b1d1553eca to your computer and use it in GitHub Desktop.
Save grsLammy/1adb24b04cd5b239876ef4b1d1553eca to your computer and use it in GitHub Desktop.
// Code snippet for eth-JSON RPC method
import axios from "axios";
import { MATIC_RPC_URL } from "../utils/constants";
// Fetch finality data using eth-JSON RPC method
export async function ethJsonRpcMethod(yourBlock: number): Promise<void> {
try {
console.log("Waiting for your block to get finalized...\n");
// Flag for block finality
let finalised: boolean = false;
// Store the last known finalized block value
let lastFinalizedBlock: number | null = null;
while (!finalised) {
const response = (
await axios.post(MATIC_RPC_URL, {
jsonrpc: "2.0",
id: 1,
method: "eth_getBlockByNumber",
params: ["finalized", true],
})).data;
// Convert hex to number
lastFinalizedBlock = parseInt(response.result.number.toString(), 16);
// Check if your block has achieved finality
if (lastFinalizedBlock >= yourBlock) {
finalised = true;
}
} catch (error) {
console.log(`Error at ethJsonRpcMethod: ${error}`);
process.exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment