diff --git a/explorer-nextjs/src/components/staking/StakeTableWithAction.tsx b/explorer-nextjs/src/components/staking/StakeTableWithAction.tsx index 6c642fdba9..5f128513e5 100644 --- a/explorer-nextjs/src/components/staking/StakeTableWithAction.tsx +++ b/explorer-nextjs/src/components/staking/StakeTableWithAction.tsx @@ -4,33 +4,51 @@ import type { IObservatoryNode } from "@/app/api/types"; import { CURRENT_EPOCH_REWARDS } from "@/app/api/urls"; import StakeTable from "./StakeTable"; -const epochRewards = await fetch(CURRENT_EPOCH_REWARDS, { - headers: { - Accept: "application/json", - "Content-Type": "application/json; charset=utf-8", - }, -}); -const epochRewardsData: ExplorerData["currentEpochRewardsData"] = - await epochRewards.json(); +// Function to fetch epoch rewards +async function fetchEpochRewards() { + try { + const response = await fetch(CURRENT_EPOCH_REWARDS, { + headers: { + Accept: "application/json", + "Content-Type": "application/json; charset=utf-8", + }, + }); + + if (!response.ok) { + throw new Error(`Failed to fetch epoch rewards: ${response.statusText}`); + } + + return await response.json(); + } catch (error) { + console.error("Error fetching epoch rewards:", error); + throw new Error("Failed to fetch epoch rewards data"); + } +} function getNodeSaturationPoint( totalStake: number, stakeSaturationPoint: string, ): number { const saturation = Number.parseFloat(stakeSaturationPoint); + if (Number.isNaN(saturation) || saturation <= 0) { throw new Error("Invalid stake saturation point provided"); } + const ratio = (totalStake / saturation) * 100; return Number(ratio.toFixed()); } -const mappedNymNodes = (nodes: IObservatoryNode[]) => +const mappedNymNodes = ( + nodes: IObservatoryNode[], + epochRewardsData: ExplorerData["currentEpochRewardsData"], +) => nodes.map((node) => { const nodeSaturationPoint = getNodeSaturationPoint( node.total_stake, epochRewardsData.interval.stake_saturation_point, ); + return { name: node.self_description.moniker, nodeId: node.node_id, @@ -49,12 +67,20 @@ export type MappedNymNode = MappedNymNodes[0]; const StakeTableWithAction = async () => { try { + // Fetch the epoch rewards data + const epochRewardsData: ExplorerData["currentEpochRewardsData"] = + await fetchEpochRewards(); + + // Fetch the Nym nodes const nodes = await getNymNodes(); - const data = mappedNymNodes(nodes); + + // Map the nodes with the rewards data + const data = mappedNymNodes(nodes, epochRewardsData); + return ; } catch (error) { - console.error(error); - return null; + console.error("Error in StakeTableWithAction:", error); + return
Error loading stake table data.
; // Fallback UI } };