From 51ed56b326ee2ba1a99d103167b9979ef982f7be Mon Sep 17 00:00:00 2001 From: minuszka <101508242+minuszka@users.noreply.github.com> Date: Fri, 13 Nov 2026 23:22:14 +0100 Subject: [PATCH] Show the network's key figures at the top of the home page The top of the home page showed only the DFCN price. - It now shows six figures in one row: the price (with its 24-hour change and a note when the quote is delayed), the circulating supply, the yearly masternode return, the average block time over 7 days, the share of the supply locked as masternode collateral, and the number of transactions in the last 24 hours. - The masternode return is worked out by the same code as on the Rewards page, so both pages show the same number. - A figure the server does not provide shows "N/A" instead of a guess, and the 24-hour transaction count is no longer repeated lower on the page. - Browser tests check the figures, the missing-data cases and the layout on desktop and mobile; deliberately broken versions make them fail. --- client/e2e/dashboard-metrics.spec.ts | 242 ++++++++++++++++++++++++ client/src/pages/DashboardPage.css | 67 +++++-- client/src/pages/DashboardPage.tsx | 135 ++++++++++--- client/src/pages/MiningPage.tsx | 46 +---- client/src/utils/masternodeEconomics.ts | 85 +++++++++ 5 files changed, 488 insertions(+), 87 deletions(-) create mode 100644 client/e2e/dashboard-metrics.spec.ts create mode 100644 client/src/utils/masternodeEconomics.ts diff --git a/client/e2e/dashboard-metrics.spec.ts b/client/e2e/dashboard-metrics.spec.ts new file mode 100644 index 0000000..93c7c97 --- /dev/null +++ b/client/e2e/dashboard-metrics.spec.ts @@ -0,0 +1,242 @@ +import { expect, test, type Page } from '@playwright/test'; +import { stubApi } from './apiStub'; + +// Round numbers so the figures can be checked by hand: +// masternode payment 10,500 - 500 = 10,000 DFCN; 86,400 / 144 s = 600 blocks a day → 6,000,000 DFCN a day +// for 120 online masternodes = 50,000 each → 18,250,000 a year on a 1,000,000 collateral = 1825.00%. +// Locked: 120 × 1,000,000 = 120,000,000 of 12,000,000,000 = 1.0% (one decimal, as on the Rewards page). +const STATS = { + blockHeight: 130_000, + lastBlockTime: 1_788_000_000, + difficulty: 1, + hashrate: 1, + connections: 8, + mempool: { size: 0, bytes: 0 }, + supply: { circulating: 12_000_000_000, max: null }, + blockReward: 10_500, + stakingReward: 500, + avgBlockTime: 144, + txCount24h: 1_234, + totalValueTransferred24h: 5_000_000, + txCount30d: 30_000, + avgTxPerBlock30d: 2, + txTrend30d: [], + flow24h: [], + newAddresses24h: 1, + newAddresses7d: 1, + totalTransactions: 1, + totalAddresses: 1, + masternodes: 100, + stakingWallets: 5, +}; +const COIN = { + NAME: 'DeFCoN', TICKER: 'DFCN', ADDRESS_PREFIX: 'D', DECIMALS: 8, MAX_SUPPLY: null, + BLOCK_TIME_SECONDS: 150, INITIAL_REWARD: 10_000, HALVING_INTERVAL: 0, MASTERNODE_COLLATERAL: 1_000_000, +}; +const SUMMARY = { total: 125, enabled: 120, poseBanned: 5, posePenalty: 0, countries: 2 }; +const MARKET = { + available: true, + source: 'qutrade', + lastUpdatedAt: '2026-09-05T08:00:19.000Z', + freshness: 'fresh', + ageSeconds: 30, + price: { usd: 0.000008052, btc: null, change24h: 1.5, volume24h: null, marketCap: null }, +}; + +function api(stats: Record = STATS) { + return { + '/api/dashboard/overview': { success: true, data: { stats, blocks: [], txs: [] } }, + '/api/stats': { success: true, data: stats }, + '/api/coin': { success: true, data: COIN }, + '/api/masternodes/summary': { success: true, data: SUMMARY }, + '/api/market': { success: true, data: MARKET }, + }; +} + +function without(responses: Record>, ...paths: string[]) { + return Object.fromEntries(Object.entries(responses).filter(([path]) => !paths.includes(path))); +} + +function metric(page: Page, label: string) { + return page.locator('.dashboard-metric').filter({ has: page.locator(`dt:text-is("${label}")`) }); +} + +async function expectMetric(page: Page, label: string, value: string) { + await expect(metric(page, label).locator('.dashboard-metric-value')).toHaveText(value); +} + +/** For every figure: how many lines its text takes and how much of its tile's inner width it leaves free. */ +async function figureFit(page: Page) { + return page.locator('.dashboard-metric').evaluateAll((tiles) => tiles.map((tile) => { + const value = tile.querySelector('.dashboard-metric-value') as HTMLElement; + const range = document.createRange(); + range.selectNodeContents(value); + const lines = new Set(Array.from(range.getClientRects()).map((rect) => Math.round(rect.top))).size; + const style = getComputedStyle(tile); + const inner = tile.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); + const text = range.getBoundingClientRect().width; + return { value: value.textContent, lines, slack: (inner - text) / inner, tileRight: tile.getBoundingClientRect().right }; + })); +} + +async function expectFiguresOnOneLine(page: Page) { + const fit = await figureFit(page); + const hero = await page.locator('.dashboard-hero').boundingBox(); + if (!hero) throw new Error('The dashboard hero was not rendered.'); + for (const figure of fit) { + expect(figure.lines, `${figure.value} stays on one line`).toBe(1); + // Room to spare, because Linux Chromium draws this font a few per cent wider than Windows: + // the price at 360 px leaves about 11% on Windows; a tile that is nearly full (about 1%) fails here. + expect(figure.slack, `${figure.value} leaves room in its tile`).toBeGreaterThan(0.03); + expect(figure.tileRight).toBeLessThanOrEqual(hero.x + hero.width + 0.5); + } + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); +} + +test('the dashboard metrics row shows price, supply, ROI, block time, locked collateral and 24h transactions @smoke', async ({ page }) => { + await stubApi(page, api()); + await page.goto('/'); + + await expect(page.locator('.dashboard-metric')).toHaveCount(6); + await expectMetric(page, 'DFCN / USD', '$0.000008052'); + await expect(metric(page, 'DFCN / USD').locator('.dashboard-market-change')).toHaveText('+1.50%'); + await expectMetric(page, 'Circulating supply', '12B DFCN'); + await expect(metric(page, 'Circulating supply').locator('.dashboard-metric-value')).toHaveAttribute('title', '12,000,000,000 DFCN'); + await expectMetric(page, 'Masternode ROI', '1825.00%'); + await expectMetric(page, 'Avg block time', '2m 24s'); + await expectMetric(page, 'Collateral locked', '1.0%'); + await expectMetric(page, 'Transactions (24h)', '1,234'); + // The 24h transaction count is shown once, in the row, not again in Live Flow. + await expect(page.getByText('Transactions (24h)', { exact: true })).toHaveCount(1); +}); + +test('the Rewards page and the dashboard show the same masternode ROI @smoke', async ({ page }) => { + await stubApi(page, api()); + await page.goto('/mining'); + await expect(page.locator('.rewards-detail-card--roi')).toContainText('1825.00%'); + await page.goto('/'); + await expectMetric(page, 'Masternode ROI', '1825.00%'); +}); + +test('without the masternode list the ROI falls back to the active count from the stats, like the Rewards page @smoke', async ({ page }) => { + // 100 active masternodes: 60,000 DFCN a day each → 21,900,000 a year = 2190.00%; 100,000,000 of 12,000,000,000 = 0.8%. + await stubApi(page, without(api(), '/api/masternodes/summary')); + await page.goto('/'); + await expectMetric(page, 'Masternode ROI', '2190.00%'); + await expectMetric(page, 'Collateral locked', '0.8%'); +}); + +test('while the masternode list loads the ROI waits instead of showing the fallback figure @smoke', async ({ page }) => { + await stubApi(page, api()); + let release: () => void = () => {}; + const listHeld = new Promise((resolve) => { release = resolve; }); + // Registered after stubApi, so it answers the masternode list first, and only when released. + await page.route('**/api/masternodes/summary', async (route) => { + await listHeld; + await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ success: true, data: SUMMARY }) }); + }); + const coinAnswered = page.waitForResponse('**/api/coin'); + await page.goto('/'); + await coinAnswered; + await expectMetric(page, 'Transactions (24h)', '1,234'); + // Stats and coin are in; with the list missing the fallback would read 2190.00%. + await page.waitForTimeout(500); + await expectMetric(page, 'Masternode ROI', '...'); + await expectMetric(page, 'Collateral locked', '...'); + release(); + await expectMetric(page, 'Masternode ROI', '1825.00%'); +}); + +test('a figure the API does not give shows N/A, and zero transactions is still a figure @smoke', async ({ page }) => { + const stats = { ...STATS, supply: { circulating: 0, max: null }, avgBlockTime: 0, txCount24h: 0 }; + await stubApi(page, without(api(stats), '/api/coin', '/api/market')); + await page.goto('/'); + + await expectMetric(page, 'DFCN / USD', 'N/A'); + await expectMetric(page, 'Circulating supply', 'N/A'); + await expectMetric(page, 'Masternode ROI', 'N/A'); + await expectMetric(page, 'Avg block time', 'N/A'); + await expectMetric(page, 'Collateral locked', 'N/A'); + await expectMetric(page, 'Transactions (24h)', '0'); +}); + +test('when the dashboard data fails every figure shows N/A @smoke', async ({ page }) => { + await stubApi(page); + await page.goto('/'); + await expect(page.locator('.dashboard-metric-value')).toHaveCount(6); + for (const value of await page.locator('.dashboard-metric-value').all()) { + await expect(value).toHaveText('N/A'); + } +}); + +/** Waits until every figure shows its final value, so a measurement never sees "..." first. */ +async function expectFinalFigures(page: Page) { + await expectMetric(page, 'DFCN / USD', '$0.000008052'); + await expectMetric(page, 'Circulating supply', '12B DFCN'); + await expectMetric(page, 'Masternode ROI', '1825.00%'); + await expectMetric(page, 'Avg block time', '2m 24s'); + await expectMetric(page, 'Collateral locked', '1.0%'); + await expectMetric(page, 'Transactions (24h)', '1,234'); +} + +test('the six figures fit inside the hero: one row on desktop, two columns on a phone @smoke', async ({ page }, testInfo) => { + await stubApi(page, api()); + await page.goto('/'); + await expectFinalFigures(page); + + const hero = await page.locator('.dashboard-hero').boundingBox(); + if (!hero) throw new Error('The dashboard hero was not rendered.'); + const boxes = []; + for (const card of await page.locator('.dashboard-metric').all()) { + const box = await card.boundingBox(); + if (!box) throw new Error('A metric was not rendered.'); + boxes.push(box); + } + for (const box of boxes) { + expect(box.x).toBeGreaterThanOrEqual(hero.x); + expect(box.x + box.width).toBeLessThanOrEqual(hero.x + hero.width + 0.5); + } + const columns = new Set(boxes.map((box) => Math.round(box.x))).size; + const rows = new Set(boxes.map((box) => Math.round(box.y))).size; + if (testInfo.project.name === 'mobile-chromium') { + expect(columns).toBe(2); + expect(rows).toBe(3); + } else { + expect(columns).toBe(6); + expect(rows).toBe(1); + } + await expectFiguresOnOneLine(page); +}); + +// The narrowest tile of each layout: 2 columns on a 360 px phone, 3 columns just above 520 px, +// 6 columns just above 1080 px; 1100 px is the width the design review uses, 1080 px the widest 3-column one. +const NARROW_WIDTHS: Record = { + 'mobile-chromium': [360, 521], + 'desktop-chromium': [1081, 1100, 1080], +}; + +test('at the narrowest width of each layout every figure, the long price too, stays on one line @smoke', async ({ page }, testInfo) => { + await stubApi(page, api()); + for (const width of NARROW_WIDTHS[testInfo.project.name] ?? []) { + await test.step(`${width} px`, async () => { + await page.setViewportSize({ width, height: 800 }); + await page.goto('/'); + await expectFinalFigures(page); + await expectFiguresOnOneLine(page); + }); + } +}); + +test('the masternode list behind the ROI refreshes on its own, like on the Rewards page @smoke', async ({ page }) => { + await page.clock.install(); + await stubApi(page, api()); + let listRequests = 0; + page.on('request', (request) => { + if (new URL(request.url()).pathname === '/api/masternodes/summary') listRequests += 1; + }); + await page.goto('/'); + await expectMetric(page, 'Masternode ROI', '1825.00%'); + const before = listRequests; + await page.clock.runFor(91_000); + await expect.poll(() => listRequests).toBeGreaterThan(before); +}); diff --git a/client/src/pages/DashboardPage.css b/client/src/pages/DashboardPage.css index ce2cc53..e4b32e8 100644 --- a/client/src/pages/DashboardPage.css +++ b/client/src/pages/DashboardPage.css @@ -27,33 +27,58 @@ background: linear-gradient(90deg, var(--accent), transparent 48%); } -.dashboard-market-summary { +.dashboard-metrics { display: grid; grid-column: 1 / -1; - justify-self: start; - align-content: center; + grid-template-columns: repeat(6, minmax(0, 1fr)); + gap: var(--space-3); + margin: 0; +} + +.dashboard-metric { + display: grid; + align-content: start; gap: 0.2rem; + min-width: 0; + border: 1px solid var(--border-soft); + border-radius: 10px; + background: var(--surface-muted); + padding: 10px 12px; color: var(--text); } -.dashboard-market-label { +.dashboard-metric dd { + margin: 0; +} + +.dashboard-metric-label { color: var(--text-subtle); - font-size: 0.805rem; + font-size: 0.72rem; font-weight: 700; - letter-spacing: 0.06em; + letter-spacing: 0.05em; text-transform: uppercase; } +/* One size at every width: the long price ($0.000008052) has to fit the narrowest tile of each + layout (6 columns just above 1080 px, 3 columns just above 520 px, 2 columns on a 360 px phone). */ +.dashboard-metric-value { + color: var(--text); + font-size: 0.9rem; + font-weight: 700; + font-variant-numeric: tabular-nums; + overflow-wrap: anywhere; +} + +.dashboard-metric-note { + color: var(--text-subtle); + font-size: 0.75rem; +} + .dashboard-market-main { display: flex; + flex-wrap: wrap; align-items: baseline; - gap: var(--space-2); -} - -.dashboard-market-value { - color: var(--text); - font-size: 1.2075rem; - font-variant-numeric: tabular-nums; + gap: 0 var(--space-2); } .dashboard-market-change { @@ -131,7 +156,7 @@ .flow-kpis { display: grid; - grid-template-columns: repeat(4, minmax(0, 1fr)); + grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; } @@ -511,9 +536,9 @@ background: var(--success-soft); } -@media (max-width: 1180px) { - .flow-kpis { - grid-template-columns: repeat(2, minmax(0, 1fr)); +@media (max-width: 1080px) { + .dashboard-metrics { + grid-template-columns: repeat(3, minmax(0, 1fr)); } } @@ -563,4 +588,12 @@ padding: var(--space-5); } + .dashboard-metrics { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + + /* Two tiles side by side on a 360 px phone. */ + .dashboard-metric { + padding: 8px 10px; + } } diff --git a/client/src/pages/DashboardPage.tsx b/client/src/pages/DashboardPage.tsx index 6fa98e0..85e4c11 100644 --- a/client/src/pages/DashboardPage.tsx +++ b/client/src/pages/DashboardPage.tsx @@ -9,7 +9,7 @@ import { HiOutlineChevronUp, HiOutlineCube, } from 'react-icons/hi2'; -import { fetchBlockTxs, fetchDashboardOverview } from '../services/api'; +import { fetchBlockTxs, fetchCoin, fetchDashboardOverview, fetchMasternodeSummary } from '../services/api'; import { formatAge, formatBytes, @@ -19,9 +19,11 @@ import { truncateHash, } from '../utils/formatters'; import { useMarketSnapshot } from '../hooks/useMarketSnapshot'; +import { usePageVisibility } from '../hooks/usePageVisibility'; import type { DashboardBlockView, DashboardTxView, TxListItemView } from '../types/api'; import './DashboardPage.css'; import { txPath } from '../utils/routes'; +import { computeMasternodeEconomics } from '../utils/masternodeEconomics'; const TX_PREVIEW_MAX = 12; const REWARD_TOLERANCE = 0.0000001; const PROTOCOL_TX_TOLERANCE = 0.0000001; @@ -80,6 +82,40 @@ function formatMarketAge(ageSeconds: number | null | undefined): string | null { return `${Math.floor(hours / 24)}d ${hours % 24}h`; } +const COMPACT_NUMBER = new Intl.NumberFormat('en-US', { notation: 'compact', maximumFractionDigits: 1 }); + +function formatCompactCoin(value: number): string { + return COMPACT_NUMBER.format(value); +} + +function formatBlockTime(seconds: number): string { + const rounded = Math.round(seconds); + if (rounded < 60) return `${rounded}s`; + return `${Math.floor(rounded / 60)}m ${rounded % 60}s`; +} + +/** Same precision as the Rewards page: the ROI with two decimals, the locked share with one. */ +function formatPercent(value: number, digits: number): string { + return `${value.toFixed(digits)}%`; +} + +interface HeroMetricProps { + label: string; + value: string; + note?: string; + title?: string; +} + +function HeroMetric({ label, value, note, title }: HeroMetricProps) { + return ( +
+
{label}
+
{value}
+ {note &&
{note}
} +
+ ); +} + interface LatestBlockRowProps { block: DashboardBlockView; stakeRewardPerBlock: number | null; @@ -239,6 +275,16 @@ export default function DashboardPage() { queryKey: ['dashboard-overview'], queryFn: fetchDashboardOverview, }); + // The same inputs as the Rewards page, under the same query keys and refresh, so both pages show one ROI. + // The overview refreshes with new blocks; the masternode list does not, so it polls like on the Rewards page. + const isPageVisible = usePageVisibility(); + const coinQuery = useQuery({ queryKey: ['coin'], queryFn: fetchCoin }); + const masternodeSummaryQuery = useQuery({ + queryKey: ['masternodes', 'summary', 'rewards-fallback'], + queryFn: fetchMasternodeSummary, + staleTime: 45_000, + refetchInterval: isPageVisible ? 90_000 : false, + }); const { data: market, isLoading: marketLoading } = useMarketSnapshot({ staleTime: 45_000, refetchInterval: 60_000, @@ -272,35 +318,70 @@ export default function DashboardPage() { const stakeRewardPerBlock = typeof stats?.stakingReward === 'number' && stats.stakingReward > 0 ? stats.stakingReward : null; - const formatCompactCoin = (value: number) => - new Intl.NumberFormat('en-US', { - notation: 'compact', - maximumFractionDigits: 1, - }).format(value); + const masternodeSummary = masternodeSummaryQuery.isError ? undefined : masternodeSummaryQuery.data; + const economics = useMemo( + () => computeMasternodeEconomics({ stats, coin: coinQuery.data, summary: masternodeSummary }), + [stats, coinQuery.data, masternodeSummary] + ); + // A figure is "..." while its inputs load and "N/A" when they did not arrive or cannot give one. + const statsValue = (render: () => string | null) => { + if (overviewLoading) return '...'; + if (!stats) return 'N/A'; + return render() ?? 'N/A'; + }; + const circulating = typeof stats?.supply?.circulating === 'number' && stats.supply.circulating > 0 + ? stats.supply.circulating + : null; + // Wait for the masternode list too, so the figure does not first show the fallback count and then jump. + const economicsLoading = coinQuery.isLoading || masternodeSummaryQuery.isLoading; + const roiValue = economicsLoading + ? '...' + : statsValue(() => (coinQuery.data && economics.roi > 0 ? formatPercent(economics.roi, 2) : null)); + const lockedValue = economicsLoading + ? '...' + : statsValue(() => (coinQuery.data && economics.coinsLockedOnlinePct > 0 ? formatPercent(economics.coinsLockedOnlinePct, 1) : null)); return (
-
- DFCN / USD - - - {marketLoading ? '...' : priceUsd != null ? `$${formatSmallPrice(priceUsd, 4)}` : 'N/A'} - - {priceChange24h != null && !marketLoading && ( - = 0 ? 'positive' : 'negative'}`}> - {priceChange24h >= 0 ? '+' : ''} - {priceChange24h.toFixed(2)}% - +
+
+
DFCN / USD
+
+ + {marketLoading ? '...' : priceUsd != null ? `$${formatSmallPrice(priceUsd, 4)}` : 'N/A'} + + {priceChange24h != null && !marketLoading && ( + = 0 ? 'positive' : 'negative'}`}> + {priceChange24h >= 0 ? '+' : ''} + {priceChange24h.toFixed(2)}% + + )} +
+ {market?.freshness === 'stale' && ( +
+ Market data delayed{marketAge ? ` · ${marketAge} ago` : ''} +
)} - - {market?.freshness === 'stale' && ( - - Market data delayed{marketAge ? ` · ${marketAge} ago` : ''} - - )} -
- +
+ (circulating != null ? `${formatCompactCoin(circulating)} DFCN` : null))} + title={circulating != null ? `${formatNumber(circulating)} DFCN` : undefined} + /> + + (typeof stats?.avgBlockTime === 'number' && stats.avgBlockTime > 0 ? formatBlockTime(stats.avgBlockTime) : null))} + note="7-day average" + title={typeof stats?.avgBlockTime === 'number' && stats.avgBlockTime > 0 ? `${stats.avgBlockTime} seconds` : undefined} + /> + + (txCount24h != null ? formatNumber(txCount24h) : null))} + /> +
@@ -409,10 +490,6 @@ export default function DashboardPage() { Blocks (24h) {overviewLoading ? '...' : formatNumber(flow24hBlocks)}
-
- Transactions (24h) - {overviewLoading ? '...' : txCount24h != null ? formatNumber(txCount24h) : 'n/a'} -
Avg tx/block (24h) diff --git a/client/src/pages/MiningPage.tsx b/client/src/pages/MiningPage.tsx index 8123589..8f6f2b4 100644 --- a/client/src/pages/MiningPage.tsx +++ b/client/src/pages/MiningPage.tsx @@ -24,6 +24,7 @@ import { useChartAnimation } from '../utils/chartAnimation'; import { formatNumber, formatDifficulty, formatSmallPrice, formatUtcDateTime } from '../utils/formatters'; import { usePageVisibility } from '../hooks/usePageVisibility'; import { useMarketSnapshot } from '../hooks/useMarketSnapshot'; +import { computeMasternodeEconomics } from '../utils/masternodeEconomics'; import './PageStyles.css'; import './MiningPage.css'; @@ -100,47 +101,10 @@ export default function MiningPage() { collateral, onlineMn, totalMn, poseBannedMn, hasOnlineMn, avgBlockTime, roi, paybackDays, avgRewardFreqSec, coinsLockedOnline, coinsLockedOnlinePct, - } = useMemo(() => { - const rawBlockReward = stats?.blockReward ?? 0; - const configuredBaseReward = coin?.INITIAL_REWARD ?? 0; - const reportedStakingReward = stats?.stakingReward ?? 0; - const effectiveStakingReward = - reportedStakingReward > 0 - ? reportedStakingReward - : configuredBaseReward > 0 && rawBlockReward > configuredBaseReward - ? rawBlockReward - configuredBaseReward - : 0; - const blockRewardBase = - rawBlockReward > 0 ? Math.max(rawBlockReward - effectiveStakingReward, 0) : configuredBaseReward; - const collateral = coin?.MASTERNODE_COLLATERAL ?? 0; - const totalMn = masternodesData?.total ?? 0; - const onlineMn = masternodesData?.enabled ?? stats?.masternodes ?? 0; - const poseBannedMn = masternodesData?.poseBanned ?? 0; - const avgBlockTime = Math.max(1, stats?.avgBlockTime || coin?.BLOCK_TIME_SECONDS || 150); - const blocksPerDay = 86400 / avgBlockTime; - const mnRewardPerBlock = blockRewardBase; - const totalBlockReward = rawBlockReward > 0 ? rawBlockReward : blockRewardBase + effectiveStakingReward; - - const dailyMnPool = mnRewardPerBlock * blocksPerDay; - const hasOnlineMn = onlineMn > 0; - const dailyIncome = hasOnlineMn ? dailyMnPool / onlineMn : 0; - const yearlyIncome = dailyIncome * 365; - - const roi = collateral > 0 && yearlyIncome > 0 ? (yearlyIncome / collateral) * 100 : 0; - const paybackDays = dailyIncome > 0 && collateral > 0 ? Math.round(collateral / dailyIncome) : 0; - const avgRewardFreqSec = onlineMn > 0 ? onlineMn * avgBlockTime : 0; - - const coinsLockedOnline = onlineMn * collateral; - const supply = stats?.supply?.circulating ?? 0; - const coinsLockedOnlinePct = supply > 0 && coinsLockedOnline > 0 ? (coinsLockedOnline / supply) * 100 : 0; - - return { - totalBlockReward, effectiveStakingReward, mnRewardPerBlock, supply, - collateral, onlineMn, totalMn, poseBannedMn, - hasOnlineMn, avgBlockTime, - roi, paybackDays, avgRewardFreqSec, coinsLockedOnline, coinsLockedOnlinePct, - }; - }, [stats, coin, masternodesData]); + } = useMemo( + () => computeMasternodeEconomics({ stats, coin, summary: masternodesData }), + [stats, coin, masternodesData] + ); const priceUsd = market?.available ? market?.price?.usd ?? null : null; const masternodeValueUsd = diff --git a/client/src/utils/masternodeEconomics.ts b/client/src/utils/masternodeEconomics.ts new file mode 100644 index 0000000..c37c2a0 --- /dev/null +++ b/client/src/utils/masternodeEconomics.ts @@ -0,0 +1,85 @@ +import type { CoinConfigView, MasternodeSummaryView, StatsView } from '../types/api'; + +export interface MasternodeEconomicsInput { + stats: Partial> | undefined; + coin: Pick | undefined; + summary: Partial> | undefined; +} + +export interface MasternodeEconomics { + totalBlockReward: number; + effectiveStakingReward: number; + mnRewardPerBlock: number; + supply: number; + collateral: number; + onlineMn: number; + totalMn: number; + poseBannedMn: number; + hasOnlineMn: boolean; + avgBlockTime: number; + /** Yearly masternode income as a percentage of the collateral; 0 when it cannot be computed. */ + roi: number; + paybackDays: number; + avgRewardFreqSec: number; + coinsLockedOnline: number; + /** Collateral of the online masternodes as a percentage of the circulating supply; 0 when unknown. */ + coinsLockedOnlinePct: number; +} + +/** + * Masternode income figures shared by the Rewards page and the dashboard. The block reward is split + * into the stake reward and the masternode payment; every online masternode gets an equal share of + * the daily masternode pool. A missing input makes the dependent figures 0, never a guess. + */ +export function computeMasternodeEconomics({ stats, coin, summary }: MasternodeEconomicsInput): MasternodeEconomics { + const rawBlockReward = stats?.blockReward ?? 0; + const configuredBaseReward = coin?.INITIAL_REWARD ?? 0; + const reportedStakingReward = stats?.stakingReward ?? 0; + const effectiveStakingReward = + reportedStakingReward > 0 + ? reportedStakingReward + : configuredBaseReward > 0 && rawBlockReward > configuredBaseReward + ? rawBlockReward - configuredBaseReward + : 0; + const blockRewardBase = + rawBlockReward > 0 ? Math.max(rawBlockReward - effectiveStakingReward, 0) : configuredBaseReward; + const collateral = coin?.MASTERNODE_COLLATERAL ?? 0; + const totalMn = summary?.total ?? 0; + const onlineMn = summary?.enabled ?? stats?.masternodes ?? 0; + const poseBannedMn = summary?.poseBanned ?? 0; + const avgBlockTime = Math.max(1, stats?.avgBlockTime || coin?.BLOCK_TIME_SECONDS || 150); + const blocksPerDay = 86400 / avgBlockTime; + const mnRewardPerBlock = blockRewardBase; + const totalBlockReward = rawBlockReward > 0 ? rawBlockReward : blockRewardBase + effectiveStakingReward; + + const dailyMnPool = mnRewardPerBlock * blocksPerDay; + const hasOnlineMn = onlineMn > 0; + const dailyIncome = hasOnlineMn ? dailyMnPool / onlineMn : 0; + const yearlyIncome = dailyIncome * 365; + + const roi = collateral > 0 && yearlyIncome > 0 ? (yearlyIncome / collateral) * 100 : 0; + const paybackDays = dailyIncome > 0 && collateral > 0 ? Math.round(collateral / dailyIncome) : 0; + const avgRewardFreqSec = onlineMn > 0 ? onlineMn * avgBlockTime : 0; + + const coinsLockedOnline = onlineMn * collateral; + const supply = stats?.supply?.circulating ?? 0; + const coinsLockedOnlinePct = supply > 0 && coinsLockedOnline > 0 ? (coinsLockedOnline / supply) * 100 : 0; + + return { + totalBlockReward, + effectiveStakingReward, + mnRewardPerBlock, + supply, + collateral, + onlineMn, + totalMn, + poseBannedMn, + hasOnlineMn, + avgBlockTime, + roi, + paybackDays, + avgRewardFreqSec, + coinsLockedOnline, + coinsLockedOnlinePct, + }; +}