From 1ca06ee8d442ad287c7777b065612f7531cd7c7a Mon Sep 17 00:00:00 2001 From: Iuri Date: Thu, 11 Jan 2024 20:31:32 +0100 Subject: [PATCH] Fix block page --- .../components/layouts/EpochAnimation.tsx | 7 +- packages/client/pages/block/[id].tsx | 149 +++--------------- packages/server/controllers/blocks.ts | 54 +++++-- packages/server/routes/blocks.ts | 13 +- 4 files changed, 79 insertions(+), 144 deletions(-) diff --git a/packages/client/components/layouts/EpochAnimation.tsx b/packages/client/components/layouts/EpochAnimation.tsx index 59247346..8b1773b8 100644 --- a/packages/client/components/layouts/EpochAnimation.tsx +++ b/packages/client/components/layouts/EpochAnimation.tsx @@ -6,9 +6,10 @@ import ThemeModeContext from '../../contexts/theme-mode/ThemeModeContext'; type Props = { notEpoch?: boolean; notSlot?: boolean; + notBlock?: boolean; }; -const EpochAnimation = ({ notEpoch, notSlot }: Props) => { +const EpochAnimation = ({ notEpoch, notSlot, notBlock }: Props) => { // Theme Mode Context const { themeMode } = useContext(ThemeModeContext) ?? {}; @@ -17,6 +18,8 @@ const EpochAnimation = ({ notEpoch, notSlot }: Props) => { return 'Epoch not saved yet'; } else if (notSlot) { return 'Slot not saved yet'; + } else if (notBlock) { + return 'Block not saved yet'; } else { return "We're not there yet"; } @@ -24,7 +27,7 @@ const EpochAnimation = ({ notEpoch, notSlot }: Props) => { return (
{ const { network, id } = router.query; // Refs - const slotRef = useRef(0); - const existsBlockRef = useRef(true); + const blockRef = useRef(0); // States const [block, setBlock] = useState(null); const [transactions, setTransactions] = useState>([]); - const [existsBlock, setExistsBlock] = useState(true); - const [countdownText, setCountdownText] = useState(''); - const [tabPageIndex, setTabPageIndex] = useState(0); - const [loadingBlock, setLoadingBlock] = useState(true); - const [loadingTransactions, setLoadingTransactions] = useState(true); - const [blockGenesis, setBlockGenesis] = useState(0); + const [tabPageIndex, setTabPageIndex] = useState(0); + const [loadingBlock, setLoadingBlock] = useState(true); + const [loadingTransactions, setLoadingTransactions] = useState(true); + const [notBlock, setNotBlock] = useState(false); // UseEffect useEffect(() => { if (id) { - slotRef.current = Number(id); + blockRef.current = Number(id); } - if (network && ((id && !block) || (block && block.f_slot !== Number(id)))) { + if (network && ((id && !block) || (block && block.f_el_block_number !== Number(id)))) { getBlock(); getTransactions(); } @@ -94,73 +92,26 @@ const BlockPage = () => { // eslint-disable-next-line react-hooks/exhaustive-deps }, [network, id]); - const shuffle = useCallback(() => { - const text: string = getCountdownText(); - setCountdownText(text); - - // eslint-disable-next-line react-hooks/exhaustive-deps - }, []); - - useEffect(() => { - const intervalID = setInterval(shuffle, 1000); - return () => clearInterval(intervalID); - - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [shuffle, slotRef.current]); - // Get blocks const getBlock = async () => { try { setLoadingBlock(true); - const [response, genesisBlock] = await Promise.all([ + const [blockResponse, latestBlockResponse] = await Promise.all([ axiosClient.get(`/api/blocks/${id}`, { params: { network, }, }), - axiosClient.get(`/api/networks/block/genesis`, { + axiosClient.get('/api/blocks/latest', { params: { network, }, }), ]); - const blockResponse: BlockEL = response.data.block; - setBlock(blockResponse); - setBlockGenesis(genesisBlock.data.block_genesis); - - if (!blockResponse) { - const expectedTimestamp = (genesisBlock.data.block_genesis + Number(id) * 12000) / 1000; - - setBlock({ - f_epoch: Math.floor(Number(id) / 32), - f_slot: Number(id), - f_timestamp: expectedTimestamp, - }); - - setExistsBlock(false); - existsBlockRef.current = false; - - const timeDifference = new Date(expectedTimestamp * 1000).getTime() - new Date().getTime(); - - if (timeDifference > 0) { - setTimeout(() => { - if (Number(id) === slotRef.current) { - getBlock(); - } - }, timeDifference + 2000); - } else if (timeDifference > -10000) { - setTimeout(() => { - if (Number(id) === slotRef.current) { - getBlock(); - } - }, 1000); - } - } else { - setExistsBlock(true); - existsBlockRef.current = true; - } + setBlock(blockResponse.data.block); + setNotBlock(Number(id) < latestBlockResponse.data.block.f_el_block_number); } catch (error) { console.log(error); } finally { @@ -196,59 +147,6 @@ const BlockPage = () => { } }; - // Get Time Block - const getTimeBlock = () => { - let text; - - if (block) { - if (block.f_timestamp) { - text = new Date(block.f_timestamp * 1000).toLocaleString('ja-JP'); - } else { - text = new Date(blockGenesis + Number(id) * 12000).toLocaleString('ja-JP'); - } - } - - return text + countdownText; - }; - - // Get Countdown Text - const getCountdownText = () => { - let text = ''; - - if (!existsBlockRef.current) { - const expectedTimestamp = (blockGenesis + slotRef.current * 12000) / 1000; - const timeDifference = new Date(expectedTimestamp * 1000).getTime() - new Date().getTime(); - - const minutesMiliseconds = 1000 * 60; - const hoursMiliseconds = minutesMiliseconds * 60; - const daysMiliseconds = hoursMiliseconds * 24; - const yearsMiliseconds = daysMiliseconds * 365; - - if (timeDifference > yearsMiliseconds) { - const years = Math.floor(timeDifference / yearsMiliseconds); - text = ` (in ${years} ${years > 1 ? 'years' : 'year'})`; - } else if (timeDifference > daysMiliseconds) { - const days = Math.floor(timeDifference / daysMiliseconds); - text = ` (in ${days} ${days > 1 ? 'days' : 'day'})`; - } else if (timeDifference > hoursMiliseconds) { - const hours = Math.floor(timeDifference / hoursMiliseconds); - text = ` (in ${hours} ${hours > 1 ? 'hours' : 'hour'})`; - } else if (timeDifference > minutesMiliseconds) { - const minutes = Math.floor(timeDifference / minutesMiliseconds); - text = ` (in ${minutes} ${minutes > 1 ? 'minutes' : 'minute'})`; - } else if (timeDifference > 1000) { - const seconds = Math.floor(timeDifference / 1000); - text = ` (in ${seconds} ${seconds > 1 ? 'seconds' : 'second'})`; - } else if (timeDifference < -10000) { - text = ' (data not saved)'; - } else { - text = ' (updating...)'; - } - } - - return text; - }; - //TABLE //TABS const getSelectedTab = () => { @@ -266,14 +164,13 @@ const BlockPage = () => {
setTabPageIndex(0)} /> - {existsBlock && ( - setTabPageIndex(1)} - /> - )} + setTabPageIndex(1)} + />
+ {getSelectedTab()}
); @@ -299,7 +196,10 @@ const BlockPage = () => {
} /> - + @@ -349,7 +249,8 @@ const BlockPage = () => {
)} - {block?.f_slot && !loadingBlock && getInformationView()} + {block && !loadingBlock && getInformationView()} + {!block && !loadingBlock && } ); }; diff --git a/packages/server/controllers/blocks.ts b/packages/server/controllers/blocks.ts index 3e3e9cb8..51bbc04f 100644 --- a/packages/server/controllers/blocks.ts +++ b/packages/server/controllers/blocks.ts @@ -51,23 +51,45 @@ export const getBlockById = async (req: Request, res: Response) => { const pgPool = pgPools[network as string]; - const [ block ] = - await Promise.all([ - pgPool.query(` - SELECT f_timestamp, f_slot, f_epoch, - f_el_fee_recp, f_el_gas_limit, f_el_gas_used, - f_el_transactions, f_el_block_hash, f_payload_size_bytes - FROM t_block_metrics - WHERE f_el_block_number = '${id}' - `) - ]); - // 18022299 - - + const block = await pgPool.query(` + SELECT f_el_block_number, f_timestamp, f_slot, f_epoch, + f_el_fee_recp, f_el_gas_limit, f_el_gas_used, + f_el_transactions, f_el_block_hash, f_payload_size_bytes + FROM t_block_metrics + WHERE f_el_block_number = '${id}' + `); + + res.json({ + block: block.rows[0], + }); + + } catch (error) { + console.log(error); + return res.status(500).json({ + msg: 'An error occurred on the server' + }); + } +}; + +export const getLatestBlock = async (req: Request, res: Response) => { + + try { + + const { network } = req.query; + + const pgPool = pgPools[network as string]; + + const block = await pgPool.query(` + SELECT f_el_block_number, f_timestamp, f_slot, f_epoch, + f_el_fee_recp, f_el_gas_limit, f_el_gas_used, + f_el_transactions, f_el_block_hash, f_payload_size_bytes + FROM t_block_metrics + ORDER BY f_el_block_number DESC + LIMIT 1 + `); + res.json({ - block: { - ...block.rows[0], - }, + block: block.rows[0], }); } catch (error) { diff --git a/packages/server/routes/blocks.ts b/packages/server/routes/blocks.ts index e6c5c3e0..4904791e 100644 --- a/packages/server/routes/blocks.ts +++ b/packages/server/routes/blocks.ts @@ -2,15 +2,22 @@ import { Router } from 'express'; import { check, query } from 'express-validator'; import { - getBlockById, getTransactionsByBlock, getBlocks + getLatestBlock, + getBlockById, + getTransactionsByBlock, + getBlocks, } from '../controllers/blocks'; import { checkFields } from '../middlewares/check-fields'; import { existsNetwork } from '../helpers/network-validator'; - const router = Router(); +router.get('/latest', [ + query('network').not().isEmpty(), + query('network').custom(existsNetwork), + checkFields, +], getLatestBlock); router.get('/:id', [ check('id').isInt({ min: 0, max: 2147483647 }), @@ -18,12 +25,14 @@ router.get('/:id', [ query('network').custom(existsNetwork), checkFields, ], getBlockById); + router.get('/:id/transactions', [ check('id').isInt({ min: 0, max: 2147483647 }), query('network').not().isEmpty(), query('network').custom(existsNetwork), checkFields, ], getTransactionsByBlock); + router.get('/', [ query('network').not().isEmpty(), query('network').custom(existsNetwork),