diff --git a/e2e/tests/shared/mocked/zcash-blocks.spec.ts b/e2e/tests/shared/mocked/zcash-blocks.spec.ts new file mode 100644 index 00000000..7b9012ce --- /dev/null +++ b/e2e/tests/shared/mocked/zcash-blocks.spec.ts @@ -0,0 +1,149 @@ +import type { Page } from "@playwright/test"; +import { + BLOCK_3483400, + COINBASE_TX, +} from "../../../../src/services/adapters/ZcashAdapter/fixtures"; +import { expect, test } from "../../../fixtures/test"; +import { mockZcashRpc, ZCASH, ZCASH_RPC_PATTERN } from "../../../fixtures/zcash"; + +// Before NU5 (mainnet height 1,687,104) blocks have no Orchard root, tree or block commitments +const PRE_NU5_HEIGHT = 1_000_000; +const PRE_NU5_BLOCK = { + ...BLOCK_3483400, + height: PRE_NU5_HEIGHT, + hash: PRE_NU5_HEIGHT.toString(16).padStart(64, "0"), + finalorchardroot: undefined, + blockcommitments: undefined, + trees: { sapling: { size: 123_456 } }, + tx: [COINBASE_TX], +}; + +/** + * Answer one getblock request from the test instead of the shared mock + */ +async function overrideGetBlock( + page: Page, + respond: (params: unknown[]) => { result: unknown } | { error: string } | null, +) { + await page.route(ZCASH_RPC_PATTERN, async (route) => { + const body = JSON.parse(route.request().postData() ?? "{}"); + const response = body.method === "getblock" ? respond(body.params ?? []) : null; + if (!response) { + await route.fallback(); + return; + } + await route.fulfill({ + contentType: "application/json", + body: JSON.stringify( + "error" in response + ? { jsonrpc: "2.0", id: body.id, error: { code: -8, message: response.error } } + : { jsonrpc: "2.0", id: body.id, result: response.result }, + ), + }); + }); +} + +/** + * Hermetic Zcash blocks list and block detail pages, served from mainnet block 3,483,400. + */ +test.describe("Zcash blocks", () => { + test("lists the latest blocks one call per block and pages to older blocks", async ({ + page, + }) => { + const calls = await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}/blocks`); + + const table = page.locator("table.blocks-table"); + await expect(table).toContainText("3,483,400"); + await expect(table).toContainText("3,483,391"); + await expect(table.locator("tbody tr")).toHaveCount(10); + + const summaryHeights = calls + .filter((call) => call.method === "getblock" && call.params[1] === 1) + .map((call) => call.params[0]); + expect(summaryHeights).toContain("3483391"); + expect(calls.map((call) => call.method)).not.toContain("getblockhash"); + + await page.getByRole("button", { name: "Older →" }).click(); + await expect(page).toHaveURL(/fromBlock=3483390/); + await expect(table).toContainText("3,483,381"); + }); + + test("shows Zcash-specific block details", async ({ page }) => { + const calls = await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}/block/${ZCASH.tipHeight}`); + + await expect(page.locator(".block-number")).toHaveText("#3,483,400"); + await expect(page.getByText(BLOCK_3483400.hash)).toBeVisible(); + await expect(page.getByText("t1SqwRAAdSig6dE4EBPLonAait219VmkUjP")).toBeVisible(); + await expect(page.getByText("2 Sapling")).toBeVisible(); + await expect(page.getByText("2 Ironwood")).toBeVisible(); + await expect(page.getByTestId("zcash-value-pools")).toContainText("Value Pools After This Block"); + + await page.getByRole("button", { name: "+ Show More Details" }).click(); + await expect(page.getByText(BLOCK_3483400.nonce)).toBeVisible(); + await expect(page.getByText("Equihash Solution:")).toBeVisible(); + await expect(page.getByText("Ironwood 318,976")).toBeVisible(); + + // Only the requested block is fetched with full transactions, by height string. The dev + // server runs React StrictMode, which can issue the same request twice. + const verboseBlockCalls = calls.filter( + (call) => call.method === "getblock" && call.params[1] === 2, + ); + expect(new Set(verboseBlockCalls.map((call) => call.params[0]))).toEqual(new Set(["3483400"])); + }); + + test("renders a pre-NU5 block without Orchard fields", async ({ page }) => { + await mockZcashRpc(page); + await overrideGetBlock(page, ([height]) => + height === String(PRE_NU5_HEIGHT) ? { result: PRE_NU5_BLOCK } : null, + ); + + await page.goto(`/#/${ZCASH.networkSlug}/block/${PRE_NU5_HEIGHT}`); + await expect(page.locator(".block-number")).toHaveText("#1,000,000"); + + await page.getByRole("button", { name: "+ Show More Details" }).click(); + await expect(page.getByText("Final Sapling Root:")).toBeVisible(); + await expect(page.getByText("Sapling 123,456")).toBeVisible(); + await expect(page.getByText("Final Orchard Root:")).toHaveCount(0); + await expect(page.getByText("Block Commitments:")).toHaveCount(0); + await expect(page.getByText(/Orchard \d/)).toHaveCount(0); + }); + + test("pages down to the genesis block", async ({ page }) => { + await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}/blocks?fromBlock=3`); + + const table = page.locator("table.blocks-table"); + await expect(table.locator("tbody tr")).toHaveCount(4); + await expect(table.locator("tbody tr").last()).toContainText("0"); + await expect(page.getByRole("button", { name: "Older →" })).toBeDisabled(); + await expect(page.getByRole("button", { name: "← Newer" })).toBeEnabled(); + }); + + test("lists a block that failed to load and retries it", async ({ page }) => { + await mockZcashRpc(page); + const failingHeight = String(ZCASH.tipHeight - 5); + // Fails until the retry (React StrictMode may fetch the page twice in development) + let recovered = false; + await overrideGetBlock(page, ([height]) => + height === failingHeight && !recovered ? { error: "Block not found" } : null, + ); + + await page.goto(`/#/${ZCASH.networkSlug}/blocks`); + + const table = page.locator("table.blocks-table"); + const unavailable = table.getByTestId("zcash-block-unavailable"); + // Rows arrive one block at a time, so allow for a slow dev server + await expect(unavailable).toContainText("3,483,395", { timeout: 15_000 }); + await expect(table.locator("tbody tr")).toHaveCount(10); + + recovered = true; + await unavailable.getByRole("button", { name: "Retry" }).click(); + await expect(unavailable).toHaveCount(0); + await expect(table).toContainText("3,483,395"); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index b6294f31..018d08e9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -56,6 +56,8 @@ import { LazyTokenDetails, LazyTx, LazyTxs, + LazyZcashBlock, + LazyZcashBlocks, LazyZcashNetwork, preloadAllRoutes, } from "./components/LazyComponents"; @@ -162,8 +164,12 @@ function AppContent() { } /> {/* Zcash Mainnet routes (must come before :networkId catch-all) */} } /> + } /> + } /> {/* Zcash Testnet routes */} } /> + } /> + } /> {/* Solana Mainnet routes (must come before :networkId catch-all) */} } /> } /> diff --git a/src/components/LazyComponents.tsx b/src/components/LazyComponents.tsx index 80b70255..0a5bf25a 100644 --- a/src/components/LazyComponents.tsx +++ b/src/components/LazyComponents.tsx @@ -22,6 +22,8 @@ const BitcoinMempoolPage = lazy(() => import("./pages/bitcoin/BitcoinMempoolPage // Lazy load page components - Zcash const ZcashNetwork = lazy(() => import("./pages/zcash")); +const ZcashBlocksPage = lazy(() => import("./pages/zcash/ZcashBlocksPage")); +const ZcashBlockPage = lazy(() => import("./pages/zcash/ZcashBlockPage")); // Lazy load page components - Solana const SolanaNetwork = lazy(() => import("./pages/solana")); @@ -68,6 +70,8 @@ export const LazyBitcoinTxs = withSuspense(BitcoinTransactionsPage); export const LazyBitcoinAddress = withSuspense(BitcoinAddressPage); export const LazyBitcoinMempool = withSuspense(BitcoinMempoolPage); export const LazyZcashNetwork = withSuspense(ZcashNetwork); +export const LazyZcashBlocks = withSuspense(ZcashBlocksPage); +export const LazyZcashBlock = withSuspense(ZcashBlockPage); export const LazySolanaNetwork = withSuspense(SolanaNetwork); export const LazySolanaSlots = withSuspense(SolanaSlotsPage); export const LazySolanaSlot = withSuspense(SolanaSlotPage); @@ -115,6 +119,8 @@ export function preloadAllRoutes() { import("./pages/bitcoin/BitcoinMempoolPage"); // Zcash pages import("./pages/zcash"); + import("./pages/zcash/ZcashBlocksPage"); + import("./pages/zcash/ZcashBlockPage"); // Solana pages import("./pages/solana"); import("./pages/solana/SolanaSlotsPage"); diff --git a/src/components/common/LoaderWithTimeout.tsx b/src/components/common/LoaderWithTimeout.tsx index 4e455ce3..fd987367 100644 --- a/src/components/common/LoaderWithTimeout.tsx +++ b/src/components/common/LoaderWithTimeout.tsx @@ -1,5 +1,6 @@ import type React from "react"; import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import OpenScanCubeLoader from "../LoadingLogo"; @@ -16,8 +17,9 @@ const LoaderWithTimeout: React.FC = ({ size = 60, timeoutMs = 15000, onRetry, - timeoutText = "Data is taking longer than expected.", + timeoutText, }) => { + const { t } = useTranslation("common"); const [timedOut, setTimedOut] = useState(false); useEffect(() => { @@ -40,15 +42,15 @@ const LoaderWithTimeout: React.FC = ({ - {timeoutText} + {timeoutText ?? t("loaderTimeout.message")} {onRetry && ( - Retry + {t("loaderTimeout.retry")} )} - Go Home + {t("errors.goHome")} diff --git a/src/components/pages/zcash/ZcashBlockDisplay.tsx b/src/components/pages/zcash/ZcashBlockDisplay.tsx new file mode 100644 index 00000000..f6f8d1b4 --- /dev/null +++ b/src/components/pages/zcash/ZcashBlockDisplay.tsx @@ -0,0 +1,392 @@ +import React, { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { ZCASH_SHIELDED_POOLS, ZCASH_TREE_POOLS } from "../../../config/zcashConstants"; +import { useSettings } from "../../../context/SettingsContext"; +import { useTimeAgo } from "../../../hooks/useTimeAgo"; +import type { KnowledgeLevel, ZcashBlock } from "../../../types"; +import { + formatDifficulty, + formatNumber, + formatSize, + formatTimestamp, + formatZEC, + truncateBlockHash, +} from "../../../utils/zcashFormatters"; +import CopyButton from "../../common/CopyButton"; +import FieldLabel from "../../common/FieldLabel"; +import HelperTooltip from "../../common/HelperTooltip"; +import LongString from "../../common/LongString"; +import { VALUE_POOL_LABEL_KEYS } from "./labels"; +import { ZcashPoolChip } from "./ZcashCells"; +import ZcashValuePools from "./ZcashValuePools"; + +// Header internals are self-explanatory to advanced users +const DETAIL_TOOLTIP_LEVELS: KnowledgeLevel[] = ["beginner", "intermediate"]; + +interface DetailRowProps { + label: string; + tooltipKey: string; + mono?: boolean; + children: React.ReactNode; +} + +/** A row of the "more details" section; FieldLabel decides whether the tooltip shows */ +const DetailRow: React.FC = ({ label, tooltipKey, mono, children }) => ( + + + {children} + +); + +interface ZcashBlockDisplayProps { + block: ZcashBlock; + networkId: string; + currency: string; + /** The block came from the cache: its confirmation count is a lower bound */ + confirmationsAtLeast?: boolean; +} + +const ZcashBlockDisplay: React.FC = React.memo( + ({ block, networkId, currency, confirmationsAtLeast = false }) => { + const { t } = useTranslation("zcash"); + const { t: tTooltips } = useTranslation("tooltips"); + const { settings } = useSettings(); + const timeAgo = useTimeAgo(); + const [showMoreDetails, setShowMoreDetails] = useState(false); + const [showTransactions, setShowTransactions] = useState(false); + const showTooltips = settings.showHelperTooltips !== false; + + const coinbaseOutputs = block.coinbaseOutputs ?? []; + const coinbaseShieldedZat = block.coinbaseShieldedZat ?? 0; + // A shielded coinbase pays (part of) the reward into Sapling or Orchard + const rewardZat = + coinbaseOutputs.reduce((sum, output) => sum + output.valueZat, 0) + coinbaseShieldedZat; + const txids = block.txids ?? []; + const poolCounts = ZCASH_SHIELDED_POOLS.flatMap((pool) => { + const count = block.shieldedTxCounts?.[pool]; + return count ? [{ pool, count }] : []; + }); + const treeSizes = ZCASH_TREE_POOLS.flatMap((pool) => { + const size = block.trees?.[pool]; + return size === undefined + ? [] + : [ + t("block.treeSize", { + pool: t(VALUE_POOL_LABEL_KEYS[pool]), + size: formatNumber(size), + }), + ]; + }); + + return ( + + + + {block.height > 0 && ( + + ← + + )} + + {t("block.title")} + #{block.height.toLocaleString()} + + {block.nextBlockHash && ( + + → + + )} + • + + {timeAgo(block.time)} + ({formatTimestamp(block.time)}) + + + {block.confirmations !== undefined && ( + + {confirmationsAtLeast + ? t("block.confirmationsAtLeast", { count: block.confirmations }) + : t("block.confirmations", { count: block.confirmations })} + {showTooltips && ( + + )} + + )} + + + + + + + {block.hash} + + + + + + + {rewardZat > 0 && ( + + + + {formatZEC(rewardZat, currency)} + {coinbaseShieldedZat > 0 && ( + + {" "} + {t("block.shieldedReward", { + amount: formatZEC(coinbaseShieldedZat, currency), + })} + + )} + + + )} + + + + + {t("block.txCount", { count: block.nTx })} + {poolCounts.length > 0 && ( + + {poolCounts.map(({ pool, count }) => ( + + {t("block.poolTxCount", { count, pool: t(VALUE_POOL_LABEL_KEYS[pool]) })} + + ))} + + )} + + + + {block.transparentOutputZat !== undefined && ( + + + + {formatZEC(block.transparentOutputZat, currency)} + + + )} + + + + + + {formatDifficulty(block.difficulty)} + + + + + {formatSize(block.size)} + + + {block.previousBlockHash && ( + + + + + {truncateBlockHash(block.previousBlockHash)} + + + + )} + + {block.nextBlockHash && ( + + + + + {truncateBlockHash(block.nextBlockHash)} + + + + )} + + + + {coinbaseOutputs.length > 0 && ( + + + + {coinbaseOutputs.map((output, index) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: outputs keep their on-chain order + + {output.address ? ( + + {output.address} + + ) : ( + {t("block.noAddress")} + )} + + {formatZEC(output.valueZat, currency)} + + + ))} + + + )} + + + setShowMoreDetails(!showMoreDetails)} + > + {showMoreDetails ? t("block.hideDetails") : t("block.showDetails")} + + + {showMoreDetails && ( + + + {block.merkleRoot} + + {block.blockCommitments && ( + + {block.blockCommitments} + + )} + {block.finalSaplingRoot && ( + + {block.finalSaplingRoot} + + )} + {block.finalOrchardRoot && ( + + {block.finalOrchardRoot} + + )} + + {block.version} + + + {block.bits} + + + {block.nonce} + + {block.solution && ( + + + + )} + {treeSizes.length > 0 && ( + + {treeSizes.join(" · ")} + + )} + + )} + + + {txids.length > 0 && ( + + setShowTransactions(!showTransactions)} + > + {showTransactions + ? t("block.hideTransactions", { count: txids.length }) + : t("block.showTransactions", { count: txids.length })} + + + {showTransactions && ( + + + {txids.map((txid, index) => ( + + {index} + + + {txid} + + + + ))} + + + )} + + )} + + + {block.valuePools && block.valuePools.length > 0 && ( + + )} + + ); + }, +); + +ZcashBlockDisplay.displayName = "ZcashBlockDisplay"; +export default ZcashBlockDisplay; diff --git a/src/components/pages/zcash/ZcashBlockPage.tsx b/src/components/pages/zcash/ZcashBlockPage.tsx new file mode 100644 index 00000000..963f109a --- /dev/null +++ b/src/components/pages/zcash/ZcashBlockPage.tsx @@ -0,0 +1,139 @@ +import { useEffect, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useParams } from "react-router-dom"; +import { LOADER_TIMEOUT_MS } from "../../../config/zcashConstants"; +import { useDataService } from "../../../hooks/useDataService"; +import { usePersistentCache } from "../../../hooks/usePersistentCache"; +import { useZcashNetworkFromPath } from "../../../hooks/useZcashNetworkFromPath"; +import type { ZcashBlock } from "../../../types"; +import Breadcrumb from "../../common/Breadcrumb"; +import LoaderWithTimeout from "../../common/LoaderWithTimeout"; +import ZcashBlockDisplay from "./ZcashBlockDisplay"; + +export default function ZcashBlockPage() { + const { t } = useTranslation("zcash"); + const { filter } = useParams<{ filter?: string }>(); + const { + slug: networkSlug, + label: networkLabel, + currency, + cacheNetworkId, + } = useZcashNetworkFromPath(); + const dataService = useDataService(networkSlug); + const { getCached, setCached } = usePersistentCache(); + + const [block, setBlock] = useState(null); + const [fromCache, setFromCache] = useState(false); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const [attempt, setAttempt] = useState(0); + + // biome-ignore lint/correctness/useExhaustiveDependencies: attempt re-runs the fetch on retry + useEffect(() => { + if (!dataService || !dataService.isZcash() || !filter) return; + + const controller = new AbortController(); + const { signal } = controller; + const adapter = dataService.getZcashAdapter(); + + const fetchBlock = async () => { + setLoading(true); + setError(null); + setFromCache(false); + + try { + let blockId: string | number = filter; + if (filter === "latest") { + blockId = await adapter.getLatestBlockNumber({ signal }); + } else if (/^\d+$/.test(filter)) { + const cached = getCached(cacheNetworkId, "block", filter); + if (cached) { + setBlock(cached); + setFromCache(true); + return; + } + } + + // A single getblock call returns the header, transactions and value pools + const { data } = await adapter.getBlock(blockId, { signal }); + if (signal.aborted) return; + setBlock(data.block); + // The tip still changes (next block link, confirmations), so only cache blocks that + // already have a successor + if (data.block.nextBlockHash) { + setCached(cacheNetworkId, "block", String(data.block.height), data.block); + } + } catch (err) { + if (!signal.aborted) setError(err instanceof Error ? err.message : String(err)); + } finally { + if (!signal.aborted) setLoading(false); + } + }; + + fetchBlock(); + return () => controller.abort(); + }, [dataService, filter, getCached, setCached, cacheNetworkId, attempt]); + + if (loading) { + return ( + + + + {t("block.title")} + {filter} + + + setAttempt((count) => count + 1)} + /> + + + + ); + } + + if (error) { + return ( + + + + {t("block.title")} + + + {t("block.loadError", { message: error })} + + + + ); + } + + return ( + + + {block ? ( + + ) : ( + + + {t("block.notFound")} + + + )} + + ); +} diff --git a/src/components/pages/zcash/ZcashBlocksPage.tsx b/src/components/pages/zcash/ZcashBlocksPage.tsx new file mode 100644 index 00000000..d04eade3 --- /dev/null +++ b/src/components/pages/zcash/ZcashBlocksPage.tsx @@ -0,0 +1,297 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link, useNavigate, useSearchParams } from "react-router-dom"; +import { BLOCKS_PER_PAGE } from "../../../config/zcashConstants"; +import { useDataService } from "../../../hooks/useDataService"; +import { useTimeAgo } from "../../../hooks/useTimeAgo"; +import { useZcashNetworkFromPath } from "../../../hooks/useZcashNetworkFromPath"; +import type { ZcashBlock } from "../../../types"; +import { logger } from "../../../utils/logger"; +import { + formatNumber, + formatSize, + formatTimestamp, + truncateBlockHash, +} from "../../../utils/zcashFormatters"; +import Breadcrumb from "../../common/Breadcrumb"; +import { ZcashSkeleton } from "./ZcashCells"; + +export default function ZcashBlocksPage() { + const { t } = useTranslation("zcash"); + const timeAgo = useTimeAgo(); + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const { slug: networkSlug, name: networkName, label: networkLabel } = useZcashNetworkFromPath(); + const dataService = useDataService(networkSlug); + + const fromBlockParam = searchParams.get("fromBlock"); + const fromBlock = + fromBlockParam !== null && /^\d+$/.test(fromBlockParam) ? Number(fromBlockParam) : null; + + const [blocks, setBlocks] = useState>(new Map()); + const [failedHeights, setFailedHeights] = useState([]); + const [latestHeight, setLatestHeight] = useState(null); + const [fetching, setFetching] = useState(true); + const [error, setError] = useState(null); + // Aborted when the page or network changes, so retries of an old page can't land here + const pageSignalRef = useRef(null); + + const addBlock = useCallback((block: ZcashBlock) => { + setBlocks((prev) => new Map(prev).set(block.height, block)); + }, []); + + useEffect(() => { + if (!dataService || !dataService.isZcash()) return; + + const controller = new AbortController(); + const { signal } = controller; + pageSignalRef.current = signal; + const adapter = dataService.getZcashAdapter(); + + const fetchBlocks = async () => { + setFetching(true); + setError(null); + setBlocks(new Map()); + setFailedHeights([]); + + try { + const tipHeight = await adapter.getLatestBlockNumber({ signal }); + if (signal.aborted) return; + setLatestHeight(tipHeight); + + const start = Math.min(fromBlock ?? tipHeight, tipHeight); + const heights = Array.from({ length: BLOCKS_PER_PAGE }, (_, i) => start - i).filter( + (height) => height >= 0, + ); + // One block per call; rows appear as they arrive on rate-limited endpoints + const result = await adapter.getBlockSummaries(heights, { + signal, + onBlock: (block) => { + if (!signal.aborted) addBlock(block); + }, + }); + if (signal.aborted) return; + setFailedHeights(result.failedHeights); + } catch (err) { + if (signal.aborted) return; + logger.error("Error fetching Zcash blocks:", err); + setError(err instanceof Error ? err.message : String(err)); + } finally { + if (!signal.aborted) setFetching(false); + } + }; + + fetchBlocks(); + return () => controller.abort(); + }, [dataService, fromBlock, addBlock]); + + const retryBlock = async (height: number) => { + const signal = pageSignalRef.current; + if (!dataService?.isZcash() || !signal) return; + setFailedHeights((prev) => prev.filter((failed) => failed !== height)); + try { + const result = await dataService.getZcashAdapter().getBlockSummaries([height], { + signal, + onBlock: (block) => { + if (!signal.aborted) addBlock(block); + }, + }); + if (signal.aborted) return; + setFailedHeights((prev) => [...prev, ...result.failedHeights]); + } catch { + // Aborted: the page moved on + } + }; + + const startHeight = + latestHeight === null ? null : Math.min(fromBlock ?? latestHeight, latestHeight); + const oldestHeight = startHeight === null ? null : Math.max(startHeight - BLOCKS_PER_PAGE + 1, 0); + const isAtLatest = fromBlock === null || (latestHeight !== null && fromBlock >= latestHeight); + const canGoNewer = !isAtLatest && startHeight !== null; + const canGoOlder = startHeight !== null && startHeight - BLOCKS_PER_PAGE >= 0; + + const pageHeights = + startHeight === null || oldestHeight === null + ? [] + : Array.from({ length: startHeight - oldestHeight + 1 }, (_, i) => startHeight - i); + const skeletonRows = startHeight === null && fetching ? BLOCKS_PER_PAGE : 0; + + const goToLatest = () => navigate(`/${networkSlug}/blocks`); + + const goToNewer = () => { + if (startHeight === null || latestHeight === null) return; + const next = startHeight + BLOCKS_PER_PAGE; + navigate( + next >= latestHeight ? `/${networkSlug}/blocks` : `/${networkSlug}/blocks?fromBlock=${next}`, + ); + }; + + const goToOlder = () => { + if (startHeight === null) return; + navigate(`/${networkSlug}/blocks?fromBlock=${startHeight - BLOCKS_PER_PAGE}`); + }; + + return ( + + + + + + {t("blocksPage.title", { network: networkName })} + {startHeight !== null && oldestHeight !== null && ( + <> + • + + {isAtLatest + ? t("blocksPage.showingLatest", { count: BLOCKS_PER_PAGE }) + : t("blocksPage.showingRange", { + from: formatNumber(oldestHeight), + to: formatNumber(startHeight), + })} + + > + )} + + + + {error ? ( + + {t("blocksPage.loadError", { message: error })} + + ) : ( + + + + + {t("blocksPage.height")} + {t("blocksPage.hash")} + {t("blocksPage.time")} + {t("blocksPage.txns")} + {t("blocksPage.size")} + + + + {pageHeights.map((height) => { + const block = blocks.get(height); + if (block) { + return ( + + + + {block.height.toLocaleString()} + + + + + {truncateBlockHash(block.hash)} + + + + {timeAgo(block.time)} + + {block.nTx.toLocaleString()} + {formatSize(block.size)} + + ); + } + if (failedHeights.includes(height)) { + return ( + + + + {height.toLocaleString()} + + + + {t("blocksPage.unavailable")} + retryBlock(height)} + > + {t("blocksPage.retryBlock")} + + + + ); + } + return ; + })} + {Array.from({ length: skeletonRows }).map((_, i) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholder + + ))} + + + + )} + + + + {t("blocksPage.latest")} + + + {t("blocksPage.newer")} + + + {t("blocksPage.older")} + + + + + ); +} + +const SkeletonRow = () => ( + + + + + + + + + + + + + + + + + +); diff --git a/src/components/pages/zcash/ZcashCells.tsx b/src/components/pages/zcash/ZcashCells.tsx index 546a2789..9f1b9c55 100644 --- a/src/components/pages/zcash/ZcashCells.tsx +++ b/src/components/pages/zcash/ZcashCells.tsx @@ -1,16 +1,16 @@ import type React from "react"; import { useTranslation } from "react-i18next"; -import type { ZcashTransaction, ZcashTxKind } from "../../../types"; +import type { ZcashShieldedPool, ZcashTransaction, ZcashTxKind } from "../../../types"; import { formatZEC } from "../../../utils/zcashFormatters"; import { getTransparentOutputZat } from "../../../utils/zcashUtils"; -import { TX_KIND_LABEL_KEYS } from "./labels"; +import { TX_KIND_LABEL_KEYS, VALUE_POOL_LABEL_KEYS } from "./labels"; -type SkeletonWidth = 50 | 60 | 70 | 80 | 90 | 100 | 120 | 140; +type SkeletonWidth = 40 | 50 | 60 | 70 | 80 | 90 | 100 | 120 | 140; interface ZcashSkeletonProps { width: SkeletonWidth; /** Line height of the text the placeholder stands in for */ - size?: "small" | "text" | "stat"; + size?: "small" | "text" | "row" | "stat"; } /** @@ -46,3 +46,21 @@ export const ZcashOutputValue: React.FC = ({ transaction, {t("transactions.shieldedValue")} ); }; + +interface ZcashPoolChipProps { + pool: ZcashShieldedPool; + /** Chip text; the pool name by default */ + children?: React.ReactNode; +} + +/** + * A shielded pool tag, colored per pool + */ +export const ZcashPoolChip: React.FC = ({ pool, children }) => { + const { t } = useTranslation("zcash"); + return ( + + {children ?? t(VALUE_POOL_LABEL_KEYS[pool])} + + ); +}; diff --git a/src/components/pages/zcash/ZcashValuePools.tsx b/src/components/pages/zcash/ZcashValuePools.tsx index 65f6bd92..62abdc3a 100644 --- a/src/components/pages/zcash/ZcashValuePools.tsx +++ b/src/components/pages/zcash/ZcashValuePools.tsx @@ -1,7 +1,7 @@ import type React from "react"; import { useTranslation } from "react-i18next"; import { useSettings } from "../../../context/SettingsContext"; -import type { ZcashNetworkStats, ZcashValuePoolId } from "../../../types"; +import type { ZcashValuePool, ZcashValuePoolId } from "../../../types"; import { formatPercent, formatZECCompact } from "../../../utils/zcashFormatters"; import HelperTooltip from "../../common/HelperTooltip"; import { VALUE_POOL_LABEL_KEYS } from "./labels"; @@ -16,32 +16,37 @@ const POOL_TOOLTIP_KEYS = { } as const satisfies Record; interface ZcashValuePoolsProps { - stats: ZcashNetworkStats | null; + valuePools: ZcashValuePool[]; + chainSupplyZat?: number; currency: string; + title?: string; } -const ZcashValuePools: React.FC = ({ stats, currency }) => { +const ZcashValuePools: React.FC = ({ + valuePools, + chainSupplyZat, + currency, + title, +}) => { const { t } = useTranslation("zcash"); const { t: tTooltips } = useTranslation("tooltips"); const { settings } = useSettings(); const showTooltips = settings.showHelperTooltips !== false; - const pools = stats?.valuePools ?? []; - const totalZat = - stats?.chainSupplyZat || pools.reduce((sum, pool) => sum + pool.valueZat, 0) || 0; - if (pools.length === 0 || totalZat <= 0) return null; + const totalZat = chainSupplyZat || valuePools.reduce((sum, pool) => sum + pool.valueZat, 0); + if (valuePools.length === 0 || totalZat <= 0) return null; const sharePercent = (valueZat: number) => (valueZat / totalZat) * 100; return ( - {t("valuePools.title")} + {title ?? t("valuePools.title")} {showTooltips && } - {pools.map((pool) => ( + {valuePools.map((pool) => ( = ({ stats, currency }) => - {pools.map((pool) => ( + {valuePools.map((pool) => ( {t(VALUE_POOL_LABEL_KEYS[pool.id])} diff --git a/src/components/pages/zcash/index.tsx b/src/components/pages/zcash/index.tsx index 0ccafabe..5a8156a2 100644 --- a/src/components/pages/zcash/index.tsx +++ b/src/components/pages/zcash/index.tsx @@ -58,7 +58,11 @@ export default function ZcashNetwork() { loading={dashboard.loading} /> - + { .mockResolvedValueOnce(fail("RPC error: Block not found")) .mockResolvedValueOnce(ok(summary(3483400))); - const { blocks, failedHeights } = await adapter.getBlockSummaries([3483399, 3483398, 3483400]); + const onBlock = vi.fn(); + const { blocks, failedHeights } = await adapter.getBlockSummaries([3483399, 3483398, 3483400], { + onBlock, + }); expect(client.getBlock.mock.calls).toEqual([ ["3483399", 1], @@ -172,6 +175,8 @@ describe("ZcashAdapter blocks", () => { expect(blocks.map((block) => block.height)).toEqual([3483400, 3483399]); expect(blocks[0]?.txids).toEqual(["a".repeat(64)]); expect(failedHeights).toEqual([3483398]); + // Rows can render in request order as each block arrives + expect(onBlock.mock.calls.map(([block]) => block.height)).toEqual([3483399, 3483400]); }); it("stops fetching summaries once a block stays rate limited", async () => { diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts index 8921e32c..39fba262 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts @@ -333,7 +333,10 @@ export class ZcashAdapter { */ async getBlockSummaries( heights: number[], - options: ZcashCallOptions = {}, + options: ZcashCallOptions & { + /** Called as each block arrives, so pages can render rows progressively */ + onBlock?: (block: ZcashBlock) => void; + } = {}, ): Promise { const blocks: ZcashBlock[] = []; const failedHeights: number[] = []; @@ -345,7 +348,9 @@ export class ZcashAdapter { () => this.client.getBlock(String(height), 1), options.signal, ); - blocks.push(transformBlockSummary(data)); + const block = transformBlockSummary(data); + blocks.push(block); + options.onBlock?.(block); } catch (error) { if (options.signal?.aborted) throw error; logger.warn(`Failed to fetch Zcash block ${height}:`, error); diff --git a/src/styles/components.css b/src/styles/components.css index 04522cd6..4f2bc696 100644 --- a/src/styles/components.css +++ b/src/styles/components.css @@ -6366,10 +6366,15 @@ button.tx-section-header-toggle { height: 14px; } +.zec-skeleton-row { + height: 18px; +} + .zec-skeleton-stat { height: 20px; } +.zec-skeleton-w40 { width: 40px; } .zec-skeleton-w50 { width: 50px; } .zec-skeleton-w60 { width: 60px; } .zec-skeleton-w70 { width: 70px; } @@ -6379,6 +6384,15 @@ button.tx-section-header-toggle { .zec-skeleton-w120 { width: 120px; } .zec-skeleton-w140 { width: 140px; } +.zec-retry-button { + background: none; + border: none; + padding: 0; + margin-left: 8px; + font: inherit; + cursor: pointer; +} + /* Zcash value pools */ .zec-value-pools { background: var(--bg-secondary); @@ -6506,6 +6520,65 @@ button.tx-section-header-toggle { color: var(--color-warning); } +/* Zcash block details */ +.zec-inline-copy { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.zec-solution { + word-break: break-all; +} + +.zec-pool-chips { + display: inline-flex; + flex-wrap: wrap; + gap: 6px; + margin-left: 8px; + vertical-align: middle; +} + +.zec-pool-chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 1px 8px; + border-radius: 10px; + font-size: 0.75rem; + background: var(--overlay-light-5); + color: var(--text-secondary); +} + +.zec-pool-chip::before { + content: ""; + width: 8px; + height: 8px; + border-radius: 2px; + background: var(--pool-color); +} + +.zec-coinbase-outputs { + display: flex; + flex-direction: column; + gap: 4px; + margin: 0; + padding: 0; + list-style: none; +} + +.zec-coinbase-outputs li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; +} + +.zec-coinbase-value { + color: var(--text-secondary); + font-variant-numeric: tabular-nums; +} + /* Clickable stat label */ .dashboard-stat-label-link { display: block;
{timeoutText}
{timeoutText ?? t("loaderTimeout.message")}
{t("block.loadError", { message: error })}
{t("block.notFound")}
{t("blocksPage.loadError", { message: error })}