otterscan/src/useLatestBlock.ts

65 lines
1.6 KiB
TypeScript
Raw Normal View History

import { useState, useEffect } from "react";
import { ethers } from "ethers";
2021-07-08 19:02:42 +00:00
export const useLatestBlock = (provider?: ethers.providers.JsonRpcProvider) => {
const [latestBlock, setLatestBlock] = useState<ethers.providers.Block>();
useEffect(() => {
2021-07-08 19:02:42 +00:00
if (!provider) {
return;
}
const readLatestBlock = async () => {
const blockNum = await provider.getBlockNumber();
const _raw = await provider.send("erigon_getHeaderByNumber", [blockNum]);
const _block = provider.formatter.block(_raw);
setLatestBlock(_block);
};
readLatestBlock();
const listener = async (blockNumber: number) => {
const _raw = await provider.send("erigon_getHeaderByNumber", [
blockNumber,
]);
const _block = provider.formatter.block(_raw);
setLatestBlock(_block);
};
provider.on("block", listener);
return () => {
provider.removeListener("block", listener);
};
2021-07-08 19:02:42 +00:00
}, [provider]);
return latestBlock;
};
2021-07-08 19:02:42 +00:00
export const useLatestBlockNumber = (
provider?: ethers.providers.JsonRpcProvider
) => {
const [latestBlock, setLatestBlock] = useState<number>();
useEffect(() => {
2021-07-08 19:02:42 +00:00
if (!provider) {
return;
}
const readLatestBlock = async () => {
const blockNum = await provider.getBlockNumber();
setLatestBlock(blockNum);
};
readLatestBlock();
const listener = async (blockNumber: number) => {
setLatestBlock(blockNumber);
};
provider.on("block", listener);
return () => {
provider.removeListener("block", listener);
};
2021-07-08 19:02:42 +00:00
}, [provider]);
return latestBlock;
};