From bbb9e15e06405a5bc58270048df4e1bac65bab90 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:21:23 -0300 Subject: [PATCH 1/7] feat(i18n): add zcash namespace and value pool tooltips --- src/i18n.ts | 11 ++++++++ src/i18next.d.ts | 2 ++ src/locales/en/tooltips.json | 12 ++++++++ src/locales/en/zcash.json | 50 +++++++++++++++++++++++++++++++++ src/locales/es/tooltips.json | 12 ++++++++ src/locales/es/zcash.json | 50 +++++++++++++++++++++++++++++++++ src/locales/ja/tooltips.json | 12 ++++++++ src/locales/ja/zcash.json | 50 +++++++++++++++++++++++++++++++++ src/locales/pt-BR/tooltips.json | 12 ++++++++ src/locales/pt-BR/zcash.json | 50 +++++++++++++++++++++++++++++++++ src/locales/zh/tooltips.json | 12 ++++++++ src/locales/zh/zcash.json | 50 +++++++++++++++++++++++++++++++++ 12 files changed, 323 insertions(+) create mode 100644 src/locales/en/zcash.json create mode 100644 src/locales/es/zcash.json create mode 100644 src/locales/ja/zcash.json create mode 100644 src/locales/pt-BR/zcash.json create mode 100644 src/locales/zh/zcash.json diff --git a/src/i18n.ts b/src/i18n.ts index c04990cd..0d211b8f 100644 --- a/src/i18n.ts +++ b/src/i18n.ts @@ -14,6 +14,7 @@ import enTransaction from "./locales/en/transaction.json"; import enTokenDetails from "./locales/en/tokenDetails.json"; import enRpcs from "./locales/en/rpcs.json"; import enTooltips from "./locales/en/tooltips.json"; +import enZcash from "./locales/en/zcash.json"; import esAddress from "./locales/es/address.json"; import esBlock from "./locales/es/block.json"; @@ -27,6 +28,7 @@ import esTransaction from "./locales/es/transaction.json"; import esTokenDetails from "./locales/es/tokenDetails.json"; import esRpcs from "./locales/es/rpcs.json"; import esTooltips from "./locales/es/tooltips.json"; +import esZcash from "./locales/es/zcash.json"; import zhAddress from "./locales/zh/address.json"; import zhBlock from "./locales/zh/block.json"; @@ -39,6 +41,7 @@ import zhSolana from "./locales/zh/solana.json"; import zhTransaction from "./locales/zh/transaction.json"; import zhTokenDetails from "./locales/zh/tokenDetails.json"; import zhTooltips from "./locales/zh/tooltips.json"; +import zhZcash from "./locales/zh/zcash.json"; import jaAddress from "./locales/ja/address.json"; import jaBlock from "./locales/ja/block.json"; @@ -51,6 +54,7 @@ import jaSolana from "./locales/ja/solana.json"; import jaTransaction from "./locales/ja/transaction.json"; import jaTokenDetails from "./locales/ja/tokenDetails.json"; import jaTooltips from "./locales/ja/tooltips.json"; +import jaZcash from "./locales/ja/zcash.json"; import ptBRAddress from "./locales/pt-BR/address.json"; import ptBRBlock from "./locales/pt-BR/block.json"; @@ -63,6 +67,7 @@ import ptBRSolana from "./locales/pt-BR/solana.json"; import ptBRTransaction from "./locales/pt-BR/transaction.json"; import ptBRTokenDetails from "./locales/pt-BR/tokenDetails.json"; import ptBRTooltips from "./locales/pt-BR/tooltips.json"; +import ptBRZcash from "./locales/pt-BR/zcash.json"; export const SUPPORTED_LANGUAGES = [ { code: "en", name: "English" }, @@ -90,6 +95,7 @@ i18n rpcs: enRpcs, tooltips: enTooltips, solana: enSolana, + zcash: enZcash, }, es: { common: esCommon, @@ -104,6 +110,7 @@ i18n rpcs: esRpcs, tooltips: esTooltips, solana: esSolana, + zcash: esZcash, }, zh: { common: zhCommon, @@ -117,6 +124,7 @@ i18n tokenDetails: zhTokenDetails, tooltips: zhTooltips, solana: zhSolana, + zcash: zhZcash, }, ja: { common: jaCommon, @@ -130,6 +138,7 @@ i18n tokenDetails: jaTokenDetails, tooltips: jaTooltips, solana: jaSolana, + zcash: jaZcash, }, "pt-BR": { common: ptBRCommon, @@ -143,6 +152,7 @@ i18n tokenDetails: ptBRTokenDetails, tooltips: ptBRTooltips, solana: ptBRSolana, + zcash: ptBRZcash, }, }, fallbackLng: "en", @@ -159,6 +169,7 @@ i18n "rpcs", "tooltips", "solana", + "zcash", ], interpolation: { escapeValue: false, diff --git a/src/i18next.d.ts b/src/i18next.d.ts index 834ba065..a2c3395c 100644 --- a/src/i18next.d.ts +++ b/src/i18next.d.ts @@ -10,6 +10,7 @@ import type transaction from "./locales/en/transaction.json"; import type tokenDetails from "./locales/en/tokenDetails.json"; import type rpcs from "./locales/en/rpcs.json"; import type tooltips from "./locales/en/tooltips.json"; +import type zcash from "./locales/en/zcash.json"; declare module "i18next" { interface CustomTypeOptions { defaultNS: "common"; @@ -26,6 +27,7 @@ declare module "i18next" { rpcs: typeof rpcs; tooltips: typeof tooltips; solana: typeof solana; + zcash: typeof zcash; }; } } diff --git a/src/locales/en/tooltips.json b/src/locales/en/tooltips.json index 4179d7c5..55f6273f 100644 --- a/src/locales/en/tooltips.json +++ b/src/locales/en/tooltips.json @@ -151,6 +151,18 @@ "inputsColumn": "Previous transaction outputs being spent. Each input references a UTXO (Unspent Transaction Output).", "outputsColumn": "New outputs created by this transaction. Each output locks BTC to a recipient address." }, + "zcash": { + "valuePools": "Balances held in each of Zcash's value pools. Transparent funds are public, like Bitcoin; shielded pools (Sprout, Sapling, Orchard, Ironwood) hide amounts and parties.", + "chainSupply": "Total ZEC in circulation across all value pools.", + "pools": { + "transparent": "Public UTXOs with visible addresses and amounts, like Bitcoin.", + "sprout": "The original shielded pool from Zcash's 2016 launch. Deprecated: funds can only move out.", + "sapling": "Shielded pool introduced in 2018 with fast, lightweight proofs.", + "orchard": "Shielded pool introduced with NU5 in 2022, using Halo 2 proofs that need no trusted setup.", + "lockbox": "Deferred development fund: part of every block reward since NU6, held by the protocol until its use is decided.", + "ironwood": "Shielded pool introduced with the NU6.3 (Ironwood) network upgrade." + } + }, "network": { "gasPrice": "Current cost per unit of gas on this network.", "blockNumber": "The most recently mined block number on this network.", diff --git a/src/locales/en/zcash.json b/src/locales/en/zcash.json new file mode 100644 index 00000000..78e67405 --- /dev/null +++ b/src/locales/en/zcash.json @@ -0,0 +1,50 @@ +{ + "dashboard": { + "blockHeight": "Block Height", + "difficulty": "Difficulty: {{value}}", + "mempool": "Mempool", + "mempoolTxs": "{{count}} txs", + "chainSupply": "Chain Supply", + "shieldedShare": "{{percent}}% shielded", + "loadError": "Couldn't load data from the RPC endpoint: {{message}}", + "rateLimited": "The RPC endpoint is rate limiting requests. Data refreshes automatically." + }, + "valuePools": { + "title": "Value Pools", + "barLabel": "Share of the chain supply held in each value pool", + "pools": { + "transparent": "Transparent", + "sprout": "Sprout", + "sapling": "Sapling", + "orchard": "Orchard", + "lockbox": "Lockbox", + "ironwood": "Ironwood" + } + }, + "blocks": { + "title": "Latest Blocks", + "viewAll": "View all", + "txCount": "{{count}} txns", + "noBlocks": "No blocks found" + }, + "transactions": { + "title": "Latest Transactions", + "viewAll": "View all", + "noTransactions": "No transactions found", + "shieldedValue": "Shielded", + "kinds": { + "coinbase": "Coinbase", + "transparent": "Transparent", + "shielding": "Shielding", + "deshielding": "Deshielding", + "shielded": "Fully shielded", + "mixed": "Mixed" + } + }, + "common": { + "secondsAgo": "{{count}}s ago", + "minutesAgo": "{{count}}m ago", + "hoursAgo": "{{count}}h ago", + "daysAgo": "{{count}}d ago" + } +} diff --git a/src/locales/es/tooltips.json b/src/locales/es/tooltips.json index 694761ed..081bfe0b 100644 --- a/src/locales/es/tooltips.json +++ b/src/locales/es/tooltips.json @@ -151,6 +151,18 @@ "inputsColumn": "Salidas de transacciones previas siendo gastadas. Cada entrada referencia un UTXO (Salida de Transacción No Gastada).", "outputsColumn": "Nuevas salidas creadas por esta transacción. Cada salida bloquea BTC a una dirección receptora." }, + "zcash": { + "valuePools": "Saldos en cada pool de valor de Zcash. Los fondos transparentes son públicos, como en Bitcoin; los pools blindados (Sprout, Sapling, Orchard, Ironwood) ocultan montos y participantes.", + "chainSupply": "Total de ZEC en circulación en todos los pools de valor.", + "pools": { + "transparent": "UTXOs públicos con direcciones y montos visibles, como en Bitcoin.", + "sprout": "El pool blindado original del lanzamiento de Zcash en 2016. Obsoleto: los fondos solo pueden salir.", + "sapling": "Pool blindado introducido en 2018 con pruebas rápidas y livianas.", + "orchard": "Pool blindado introducido con NU5 en 2022, con pruebas Halo 2 que no requieren configuración de confianza.", + "lockbox": "Fondo de desarrollo diferido: parte de cada recompensa de bloque desde NU6, retenida por el protocolo hasta que se decida su uso.", + "ironwood": "Pool blindado introducido con la actualización de red NU6.3 (Ironwood)." + } + }, "network": { "gasPrice": "Costo actual por unidad de gas en esta red.", "blockNumber": "El número de bloque más reciente minado en esta red.", diff --git a/src/locales/es/zcash.json b/src/locales/es/zcash.json new file mode 100644 index 00000000..6f1311b1 --- /dev/null +++ b/src/locales/es/zcash.json @@ -0,0 +1,50 @@ +{ + "dashboard": { + "blockHeight": "Altura de bloque", + "difficulty": "Dificultad: {{value}}", + "mempool": "Mempool", + "mempoolTxs": "{{count}} txs", + "chainSupply": "Suministro total", + "shieldedShare": "{{percent}}% blindado", + "loadError": "No se pudieron cargar datos del endpoint RPC: {{message}}", + "rateLimited": "El endpoint RPC está limitando las solicitudes. Los datos se actualizan automáticamente." + }, + "valuePools": { + "title": "Pools de valor", + "barLabel": "Proporción del suministro total en cada pool de valor", + "pools": { + "transparent": "Transparente", + "sprout": "Sprout", + "sapling": "Sapling", + "orchard": "Orchard", + "lockbox": "Lockbox", + "ironwood": "Ironwood" + } + }, + "blocks": { + "title": "Últimos bloques", + "viewAll": "Ver todos", + "txCount": "{{count}} txs", + "noBlocks": "No se encontraron bloques" + }, + "transactions": { + "title": "Últimas transacciones", + "viewAll": "Ver todas", + "noTransactions": "No se encontraron transacciones", + "shieldedValue": "Blindado", + "kinds": { + "coinbase": "Coinbase", + "transparent": "Transparente", + "shielding": "Blindaje", + "deshielding": "Desblindaje", + "shielded": "Totalmente blindada", + "mixed": "Mixta" + } + }, + "common": { + "secondsAgo": "hace {{count}} s", + "minutesAgo": "hace {{count}} min", + "hoursAgo": "hace {{count}} h", + "daysAgo": "hace {{count}} d" + } +} diff --git a/src/locales/ja/tooltips.json b/src/locales/ja/tooltips.json index ee9d41bc..37f51cd2 100644 --- a/src/locales/ja/tooltips.json +++ b/src/locales/ja/tooltips.json @@ -151,6 +151,18 @@ "inputsColumn": "使用される以前のトランザクション出力。各入力はUTXO(未使用トランザクション出力)を参照します。", "outputsColumn": "このトランザクションによって作成された新しい出力。各出力は受取アドレスにBTCをロックします。" }, + "zcash": { + "valuePools": "Zcashの各バリュープールの残高。トランスペアレントな資金はBitcoinと同様に公開されますが、シールドプール(Sprout、Sapling、Orchard、Ironwood)は金額と当事者を秘匿します。", + "chainSupply": "すべてのバリュープールで流通しているZECの総量。", + "pools": { + "transparent": "Bitcoinと同様に、アドレスと金額が公開されるUTXO。", + "sprout": "2016年のZcashローンチ時の最初のシールドプール。非推奨で、資金は引き出しのみ可能です。", + "sapling": "2018年に導入された、高速で軽量な証明を使うシールドプール。", + "orchard": "2022年のNU5で導入されたシールドプール。信頼されたセットアップが不要なHalo 2証明を使用します。", + "lockbox": "繰り延べ開発資金:NU6以降、各ブロック報酬の一部が使途決定までプロトコルによって保管されます。", + "ironwood": "NU6.3(Ironwood)ネットワークアップグレードで導入されたシールドプール。" + } + }, "network": { "gasPrice": "このネットワークのガス1単位あたりの現在のコスト。", "blockNumber": "このネットワークで最も最近マイニングされたブロック番号。", diff --git a/src/locales/ja/zcash.json b/src/locales/ja/zcash.json new file mode 100644 index 00000000..08b2d900 --- /dev/null +++ b/src/locales/ja/zcash.json @@ -0,0 +1,50 @@ +{ + "dashboard": { + "blockHeight": "ブロック高", + "difficulty": "難易度: {{value}}", + "mempool": "メンプール", + "mempoolTxs": "{{count}} 件", + "chainSupply": "総供給量", + "shieldedShare": "{{percent}}% シールド", + "loadError": "RPCエンドポイントからデータを読み込めませんでした: {{message}}", + "rateLimited": "RPCエンドポイントがリクエストを制限しています。データは自動的に更新されます。" + }, + "valuePools": { + "title": "バリュープール", + "barLabel": "各バリュープールが保有する総供給量の割合", + "pools": { + "transparent": "トランスペアレント", + "sprout": "Sprout", + "sapling": "Sapling", + "orchard": "Orchard", + "lockbox": "ロックボックス", + "ironwood": "Ironwood" + } + }, + "blocks": { + "title": "最新ブロック", + "viewAll": "すべて表示", + "txCount": "{{count}} 件", + "noBlocks": "ブロックが見つかりません" + }, + "transactions": { + "title": "最新トランザクション", + "viewAll": "すべて表示", + "noTransactions": "トランザクションが見つかりません", + "shieldedValue": "シールド済み", + "kinds": { + "coinbase": "コインベース", + "transparent": "トランスペアレント", + "shielding": "シールド化", + "deshielding": "アンシールド化", + "shielded": "完全シールド", + "mixed": "混合" + } + }, + "common": { + "secondsAgo": "{{count}}秒前", + "minutesAgo": "{{count}}分前", + "hoursAgo": "{{count}}時間前", + "daysAgo": "{{count}}日前" + } +} diff --git a/src/locales/pt-BR/tooltips.json b/src/locales/pt-BR/tooltips.json index 0fefe9fa..68242f78 100644 --- a/src/locales/pt-BR/tooltips.json +++ b/src/locales/pt-BR/tooltips.json @@ -151,6 +151,18 @@ "inputsColumn": "Saídas de transações anteriores sendo gastas. Cada entrada referencia um UTXO (Saída de Transação Não Gasta).", "outputsColumn": "Novas saídas criadas por esta transação. Cada saída bloqueia BTC para um endereço receptor." }, + "zcash": { + "valuePools": "Saldos em cada pool de valor do Zcash. Fundos transparentes são públicos, como no Bitcoin; os pools blindados (Sprout, Sapling, Orchard, Ironwood) ocultam valores e participantes.", + "chainSupply": "Total de ZEC em circulação em todos os pools de valor.", + "pools": { + "transparent": "UTXOs públicos com endereços e valores visíveis, como no Bitcoin.", + "sprout": "O pool blindado original do lançamento do Zcash em 2016. Obsoleto: os fundos só podem sair.", + "sapling": "Pool blindado introduzido em 2018 com provas rápidas e leves.", + "orchard": "Pool blindado introduzido com o NU5 em 2022, usando provas Halo 2 que dispensam configuração confiável.", + "lockbox": "Fundo de desenvolvimento diferido: parte de cada recompensa de bloco desde o NU6, retida pelo protocolo até que seu uso seja decidido.", + "ironwood": "Pool blindado introduzido com a atualização de rede NU6.3 (Ironwood)." + } + }, "network": { "gasPrice": "Custo atual por unidade de gas nesta rede.", "blockNumber": "O número do bloco mais recentemente minerado nesta rede.", diff --git a/src/locales/pt-BR/zcash.json b/src/locales/pt-BR/zcash.json new file mode 100644 index 00000000..e0505505 --- /dev/null +++ b/src/locales/pt-BR/zcash.json @@ -0,0 +1,50 @@ +{ + "dashboard": { + "blockHeight": "Altura do bloco", + "difficulty": "Dificuldade: {{value}}", + "mempool": "Mempool", + "mempoolTxs": "{{count}} txs", + "chainSupply": "Oferta total", + "shieldedShare": "{{percent}}% blindado", + "loadError": "Não foi possível carregar dados do endpoint RPC: {{message}}", + "rateLimited": "O endpoint RPC está limitando as requisições. Os dados são atualizados automaticamente." + }, + "valuePools": { + "title": "Pools de valor", + "barLabel": "Parcela da oferta total mantida em cada pool de valor", + "pools": { + "transparent": "Transparente", + "sprout": "Sprout", + "sapling": "Sapling", + "orchard": "Orchard", + "lockbox": "Lockbox", + "ironwood": "Ironwood" + } + }, + "blocks": { + "title": "Últimos blocos", + "viewAll": "Ver todos", + "txCount": "{{count}} txs", + "noBlocks": "Nenhum bloco encontrado" + }, + "transactions": { + "title": "Últimas transações", + "viewAll": "Ver todas", + "noTransactions": "Nenhuma transação encontrada", + "shieldedValue": "Blindado", + "kinds": { + "coinbase": "Coinbase", + "transparent": "Transparente", + "shielding": "Blindagem", + "deshielding": "Desblindagem", + "shielded": "Totalmente blindada", + "mixed": "Mista" + } + }, + "common": { + "secondsAgo": "há {{count}} s", + "minutesAgo": "há {{count}} min", + "hoursAgo": "há {{count}} h", + "daysAgo": "há {{count}} d" + } +} diff --git a/src/locales/zh/tooltips.json b/src/locales/zh/tooltips.json index 82f8a71d..239836c8 100644 --- a/src/locales/zh/tooltips.json +++ b/src/locales/zh/tooltips.json @@ -151,6 +151,18 @@ "inputsColumn": "正在花费的先前交易输出。每个输入引用一个UTXO(未花费交易输出)。", "outputsColumn": "此交易创建的新输出。每个输出将BTC锁定到接收地址。" }, + "zcash": { + "valuePools": "Zcash 各价值池中的余额。透明资金与比特币一样公开可见;屏蔽池(Sprout、Sapling、Orchard、Ironwood)会隐藏金额和参与方。", + "chainSupply": "所有价值池中流通的 ZEC 总量。", + "pools": { + "transparent": "地址和金额公开可见的 UTXO,与比特币相同。", + "sprout": "Zcash 2016 年上线时的初代屏蔽池。已弃用,资金只能转出。", + "sapling": "2018 年引入的屏蔽池,证明快速且轻量。", + "orchard": "随 2022 年 NU5 升级引入的屏蔽池,使用无需可信设置的 Halo 2 证明。", + "lockbox": "递延开发基金:自 NU6 起每个区块奖励的一部分,由协议保管,直至决定其用途。", + "ironwood": "随 NU6.3(Ironwood)网络升级引入的屏蔽池。" + } + }, "network": { "gasPrice": "此网络每单位Gas的当前成本。", "blockNumber": "此网络上最近挖出的区块号。", diff --git a/src/locales/zh/zcash.json b/src/locales/zh/zcash.json new file mode 100644 index 00000000..3b64c42c --- /dev/null +++ b/src/locales/zh/zcash.json @@ -0,0 +1,50 @@ +{ + "dashboard": { + "blockHeight": "区块高度", + "difficulty": "难度: {{value}}", + "mempool": "内存池", + "mempoolTxs": "{{count}} 笔交易", + "chainSupply": "总供应量", + "shieldedShare": "{{percent}}% 已屏蔽", + "loadError": "无法从 RPC 端点加载数据: {{message}}", + "rateLimited": "RPC 端点正在限制请求。数据会自动刷新。" + }, + "valuePools": { + "title": "价值池", + "barLabel": "各价值池持有的总供应量比例", + "pools": { + "transparent": "透明", + "sprout": "Sprout", + "sapling": "Sapling", + "orchard": "Orchard", + "lockbox": "锁箱", + "ironwood": "Ironwood" + } + }, + "blocks": { + "title": "最新区块", + "viewAll": "查看全部", + "txCount": "{{count}} 笔交易", + "noBlocks": "未找到区块" + }, + "transactions": { + "title": "最新交易", + "viewAll": "查看全部", + "noTransactions": "未找到交易", + "shieldedValue": "已屏蔽", + "kinds": { + "coinbase": "Coinbase", + "transparent": "透明", + "shielding": "屏蔽", + "deshielding": "解除屏蔽", + "shielded": "完全屏蔽", + "mixed": "混合" + } + }, + "common": { + "secondsAgo": "{{count}}秒前", + "minutesAgo": "{{count}}分钟前", + "hoursAgo": "{{count}}小时前", + "daysAgo": "{{count}}天前" + } +} From 3ebb147543a88b1db1ebb10e0095bfaa2672684f Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:21:25 -0300 Subject: [PATCH 2/7] feat(network): add Zcash network dashboard with value pools The dashboard loads stats and the tip block first, then earlier block summaries one at a time, and caches summaries across refreshes so a 90s refresh stays within hosted gateway rate limits. --- src/App.tsx | 5 + src/components/LazyComponents.tsx | 6 + .../navbar/NetworkBlockIndicator.tsx | 20 ++- .../pages/rpcs/useRpcLatencyTest.ts | 12 +- .../pages/zcash/ZcashBlocksTable.tsx | 94 +++++++++++++ .../pages/zcash/ZcashDashboardStats.tsx | 78 +++++++++++ .../pages/zcash/ZcashTransactionsTable.tsx | 111 +++++++++++++++ .../pages/zcash/ZcashValuePools.tsx | 76 +++++++++++ src/components/pages/zcash/index.tsx | 103 ++++++++++++++ src/config/networks.json | 55 +++++++- src/config/zcashConstants.ts | 7 + src/hooks/useZcashDashboard.ts | 113 ++++++++++++++++ src/hooks/useZcashTimeAgo.ts | 20 +++ src/styles/components.css | 127 ++++++++++++++++++ src/utils/zcashFormatters.ts | 10 ++ src/utils/zcashUtils.test.ts | 23 ++++ src/utils/zcashUtils.ts | 14 ++ 17 files changed, 868 insertions(+), 6 deletions(-) create mode 100644 src/components/pages/zcash/ZcashBlocksTable.tsx create mode 100644 src/components/pages/zcash/ZcashDashboardStats.tsx create mode 100644 src/components/pages/zcash/ZcashTransactionsTable.tsx create mode 100644 src/components/pages/zcash/ZcashValuePools.tsx create mode 100644 src/components/pages/zcash/index.tsx create mode 100644 src/hooks/useZcashDashboard.ts create mode 100644 src/hooks/useZcashTimeAgo.ts diff --git a/src/App.tsx b/src/App.tsx index 0f2843fe..b6294f31 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -56,6 +56,7 @@ import { LazyTokenDetails, LazyTx, LazyTxs, + LazyZcashNetwork, preloadAllRoutes, } from "./components/LazyComponents"; import { SettingsProvider, useSettings, useTheme } from "./context/SettingsContext"; @@ -159,6 +160,10 @@ 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 1777fd01..80b70255 100644 --- a/src/components/LazyComponents.tsx +++ b/src/components/LazyComponents.tsx @@ -20,6 +20,9 @@ const BitcoinTransactionsPage = lazy(() => import("./pages/bitcoin/BitcoinTransa const BitcoinAddressPage = lazy(() => import("./pages/bitcoin/BitcoinAddressPage")); const BitcoinMempoolPage = lazy(() => import("./pages/bitcoin/BitcoinMempoolPage")); +// Lazy load page components - Zcash +const ZcashNetwork = lazy(() => import("./pages/zcash")); + // Lazy load page components - Solana const SolanaNetwork = lazy(() => import("./pages/solana")); const SolanaSlotsPage = lazy(() => import("./pages/solana/SolanaSlotsPage")); @@ -64,6 +67,7 @@ export const LazyBitcoinTx = withSuspense(BitcoinTransactionPage); export const LazyBitcoinTxs = withSuspense(BitcoinTransactionsPage); export const LazyBitcoinAddress = withSuspense(BitcoinAddressPage); export const LazyBitcoinMempool = withSuspense(BitcoinMempoolPage); +export const LazyZcashNetwork = withSuspense(ZcashNetwork); export const LazySolanaNetwork = withSuspense(SolanaNetwork); export const LazySolanaSlots = withSuspense(SolanaSlotsPage); export const LazySolanaSlot = withSuspense(SolanaSlotPage); @@ -109,6 +113,8 @@ export function preloadAllRoutes() { import("./pages/bitcoin/BitcoinTransactionsPage"); import("./pages/bitcoin/BitcoinAddressPage"); import("./pages/bitcoin/BitcoinMempoolPage"); + // Zcash pages + import("./pages/zcash"); // Solana pages import("./pages/solana"); import("./pages/solana/SolanaSlotsPage"); diff --git a/src/components/navbar/NetworkBlockIndicator.tsx b/src/components/navbar/NetworkBlockIndicator.tsx index 2049c45f..d5894a18 100644 --- a/src/components/navbar/NetworkBlockIndicator.tsx +++ b/src/components/navbar/NetworkBlockIndicator.tsx @@ -1,6 +1,7 @@ import { useContext, useEffect, useMemo, useState } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import { getRPCUrls } from "../../config/rpcConfig"; +import { REFRESH_INTERVAL_MS as ZCASH_REFRESH_INTERVAL_MS } from "../../config/zcashConstants"; import { AppContext, useNetworks } from "../../context/AppContext"; import { RpcClient } from "@openscan/network-connectors"; import { useDataService } from "../../hooks/useDataService"; @@ -57,6 +58,15 @@ export function NetworkBlockIndicator({ className }: NetworkBlockIndicatorProps) setGasPrice(null); // Bitcoin doesn't have gas setIsLoading(false); } + } else if (network.type === "zcash" && dataService?.isZcash()) { + // Fetch Zcash block height + const adapter = dataService.getZcashAdapter(); + const height = await adapter.getLatestBlockNumber(); + if (isMounted) { + setBlockNumber(height); + setGasPrice(null); // Zcash doesn't have gas + setIsLoading(false); + } } else if (network.type === "solana" && dataService?.isSolana()) { // Fetch Solana current slot const adapter = dataService.getSolanaAdapter(); @@ -99,8 +109,14 @@ export function NetworkBlockIndicator({ className }: NetworkBlockIndicatorProps) setIsLoading(true); fetchData(); - // Poll every 12 seconds for EVM, 60 seconds for Bitcoin - const pollInterval = network.type === "bitcoin" ? 60000 : 12000; + // Poll every 12 seconds for EVM, 60 seconds for Bitcoin, and 90 seconds for Zcash + // (75 second blocks served by rate-limited gateways) + const pollInterval = + network.type === "zcash" + ? ZCASH_REFRESH_INTERVAL_MS + : network.type === "bitcoin" + ? 60000 + : 12000; intervalId = setInterval(fetchData, pollInterval); return () => { diff --git a/src/components/pages/rpcs/useRpcLatencyTest.ts b/src/components/pages/rpcs/useRpcLatencyTest.ts index 78ccba4f..70d568fa 100644 --- a/src/components/pages/rpcs/useRpcLatencyTest.ts +++ b/src/components/pages/rpcs/useRpcLatencyTest.ts @@ -24,8 +24,13 @@ function isHttpRpcUrl(url: string): boolean { } } +// Zcash (Zebra) serves the same getblockcount method as Bitcoin Core +function usesBitcoinRpc(networkType: NetworkType): boolean { + return networkType === "bitcoin" || networkType === "zcash"; +} + function buildRpcBody(networkType: NetworkType): string { - if (networkType === "bitcoin") { + if (usesBitcoinRpc(networkType)) { return JSON.stringify({ jsonrpc: "2.0", id: 1, method: "getblockcount", params: [] }); } return JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [] }); @@ -78,8 +83,9 @@ export async function testRpcEndpoint( }; } - const blockNumber = - networkType === "bitcoin" ? String(json.result ?? "") : (json.result ?? null); + const blockNumber = usesBitcoinRpc(networkType) + ? String(json.result ?? "") + : (json.result ?? null); return { url, diff --git a/src/components/pages/zcash/ZcashBlocksTable.tsx b/src/components/pages/zcash/ZcashBlocksTable.tsx new file mode 100644 index 00000000..7edc47b2 --- /dev/null +++ b/src/components/pages/zcash/ZcashBlocksTable.tsx @@ -0,0 +1,94 @@ +import type React from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { DASHBOARD_BLOCKS } from "../../../config/zcashConstants"; +import { useZcashTimeAgo } from "../../../hooks/useZcashTimeAgo"; +import type { ZcashBlock } from "../../../types"; +import { truncateBlockHash } from "../../../utils/zcashFormatters"; + +interface ZcashBlocksTableProps { + blocks: ZcashBlock[]; + loading: boolean; + networkId: string; +} + +const ZcashBlocksTable: React.FC = ({ blocks, loading, networkId }) => { + const { t } = useTranslation("zcash"); + const timeAgo = useZcashTimeAgo(); + + return ( +
+
+ +

{t("blocks.title")}

+ ↗ + + + {t("blocks.viewAll")} → + +
+ + {loading && blocks.length === 0 ? ( +
+ {Array.from({ length: DASHBOARD_BLOCKS }).map((_, i) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholder +
+
+ +
+
+ +
+
+ +
+
+ ))} +
+ ) : blocks.length === 0 ? ( +
{t("blocks.noBlocks")}
+ ) : ( +
+ {blocks.map((block) => ( +
+
+ + #{block.height.toLocaleString()} + + {timeAgo(block.time)} +
+
+ + {t("blocks.txCount", { count: block.nTx })} + +
+
+ + {truncateBlockHash(block.hash)} + +
+
+ ))} +
+ )} +
+ ); +}; + +export default ZcashBlocksTable; diff --git a/src/components/pages/zcash/ZcashDashboardStats.tsx b/src/components/pages/zcash/ZcashDashboardStats.tsx new file mode 100644 index 00000000..0c8d3e72 --- /dev/null +++ b/src/components/pages/zcash/ZcashDashboardStats.tsx @@ -0,0 +1,78 @@ +import type React from "react"; +import { useTranslation } from "react-i18next"; +import { useSettings } from "../../../context/SettingsContext"; +import type { ZcashNetworkStats } from "../../../types"; +import { + formatDifficulty, + formatNumber, + formatSize, + formatZECCompact, +} from "../../../utils/zcashFormatters"; +import { getShieldedSupplyPercent } from "../../../utils/zcashUtils"; +import HelperTooltip from "../../common/HelperTooltip"; + +interface ZcashDashboardStatsProps { + stats: ZcashNetworkStats | null; + currency: string; + loading: boolean; +} + +const skeleton = (width: string) => ( + +); + +const ZcashDashboardStats: React.FC = ({ stats, currency, loading }) => { + const { t } = useTranslation("zcash"); + const { t: tTooltips } = useTranslation("tooltips"); + const { settings } = useSettings(); + const showTooltips = settings.showHelperTooltips !== false; + const isLoading = loading && !stats; + const shieldedPercent = stats ? getShieldedSupplyPercent(stats) : null; + + return ( +
+
+
{t("dashboard.blockHeight")}
+
+ {isLoading ? skeleton("100px") : stats ? `#${formatNumber(stats.blockHeight)}` : "—"} +
+
+ {stats ? t("dashboard.difficulty", { value: formatDifficulty(stats.difficulty) }) : ""} +
+
+ +
+
{t("dashboard.mempool")}
+
+ {isLoading + ? skeleton("90px") + : stats + ? t("dashboard.mempoolTxs", { count: stats.mempoolSize }) + : "—"} +
+
{stats ? formatSize(stats.mempoolBytes) : ""}
+
+ +
+
+ {t("dashboard.chainSupply")} + {showTooltips && } +
+
+ {isLoading + ? skeleton("140px") + : stats?.chainSupplyZat !== undefined + ? formatZECCompact(stats.chainSupplyZat, currency) + : "—"} +
+
+ {shieldedPercent !== null + ? t("dashboard.shieldedShare", { percent: shieldedPercent.toFixed(1) }) + : ""} +
+
+
+ ); +}; + +export default ZcashDashboardStats; diff --git a/src/components/pages/zcash/ZcashTransactionsTable.tsx b/src/components/pages/zcash/ZcashTransactionsTable.tsx new file mode 100644 index 00000000..5f3517e0 --- /dev/null +++ b/src/components/pages/zcash/ZcashTransactionsTable.tsx @@ -0,0 +1,111 @@ +import type React from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import type { ZcashTransaction, ZcashTxKind } from "../../../types"; +import { formatZEC, truncateHash } from "../../../utils/zcashFormatters"; +import { classifyTransaction, getTransparentOutputZat } from "../../../utils/zcashUtils"; + +const KIND_LABEL_KEYS = { + coinbase: "transactions.kinds.coinbase", + transparent: "transactions.kinds.transparent", + shielding: "transactions.kinds.shielding", + deshielding: "transactions.kinds.deshielding", + shielded: "transactions.kinds.shielded", + mixed: "transactions.kinds.mixed", +} as const satisfies Record; + +interface ZcashTransactionsTableProps { + transactions: ZcashTransaction[]; + loading: boolean; + networkId: string; + currency: string; +} + +const ZcashTransactionsTable: React.FC = ({ + transactions, + loading, + networkId, + currency, +}) => { + const { t } = useTranslation("zcash"); + + return ( +
+
+ +

{t("transactions.title")}

+ ↗ + + + {t("transactions.viewAll")} → + +
+ + {loading && transactions.length === 0 ? ( +
+ {Array.from({ length: 5 }).map((_, i) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholder +
+
+ +
+
+ +
+
+ +
+
+ ))} +
+ ) : transactions.length === 0 ? ( +
{t("transactions.noTransactions")}
+ ) : ( +
+ {transactions.map((tx) => { + const kind = classifyTransaction(tx); + const transparentOutputZat = getTransparentOutputZat(tx); + + return ( +
+
+ + {truncateHash(tx.txid, "medium")} + +
+
+ + {t(KIND_LABEL_KEYS[kind])} + +
+
+ {transparentOutputZat > 0 ? ( + + {formatZEC(transparentOutputZat, currency)} + + ) : ( + {t("transactions.shieldedValue")} + )} +
+
+ ); + })} +
+ )} +
+ ); +}; + +export default ZcashTransactionsTable; diff --git a/src/components/pages/zcash/ZcashValuePools.tsx b/src/components/pages/zcash/ZcashValuePools.tsx new file mode 100644 index 00000000..55b7cab7 --- /dev/null +++ b/src/components/pages/zcash/ZcashValuePools.tsx @@ -0,0 +1,76 @@ +import type React from "react"; +import { useTranslation } from "react-i18next"; +import { useSettings } from "../../../context/SettingsContext"; +import type { ZcashNetworkStats, ZcashValuePoolId } from "../../../types"; +import { formatZECCompact } from "../../../utils/zcashFormatters"; +import HelperTooltip from "../../common/HelperTooltip"; + +const POOL_LABEL_KEYS = { + transparent: "valuePools.pools.transparent", + sprout: "valuePools.pools.sprout", + sapling: "valuePools.pools.sapling", + orchard: "valuePools.pools.orchard", + lockbox: "valuePools.pools.lockbox", + ironwood: "valuePools.pools.ironwood", +} as const satisfies Record; + +const POOL_TOOLTIP_KEYS = { + transparent: "zcash.pools.transparent", + sprout: "zcash.pools.sprout", + sapling: "zcash.pools.sapling", + orchard: "zcash.pools.orchard", + lockbox: "zcash.pools.lockbox", + ironwood: "zcash.pools.ironwood", +} as const satisfies Record; + +interface ZcashValuePoolsProps { + stats: ZcashNetworkStats | null; + currency: string; +} + +const ZcashValuePools: React.FC = ({ stats, currency }) => { + 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 sharePercent = (valueZat: number) => (valueZat / totalZat) * 100; + + return ( +
+
+

{t("valuePools.title")}

+ {showTooltips && } +
+ +
+ {pools.map((pool) => ( + + ))} +
+ +
    + {pools.map((pool) => ( +
  • + + {t(POOL_LABEL_KEYS[pool.id])} + {showTooltips && } + {formatZECCompact(pool.valueZat, currency)} + {sharePercent(pool.valueZat).toFixed(1)}% +
  • + ))} +
+
+ ); +}; + +export default ZcashValuePools; diff --git a/src/components/pages/zcash/index.tsx b/src/components/pages/zcash/index.tsx new file mode 100644 index 00000000..263420f3 --- /dev/null +++ b/src/components/pages/zcash/index.tsx @@ -0,0 +1,103 @@ +import { useTranslation } from "react-i18next"; +import { useLocation } from "react-router-dom"; +import { getAllNetworks } from "../../../config/networks"; +import { useZcashDashboard } from "../../../hooks/useZcashDashboard"; +import { ZcashRpcError } from "../../../services/adapters/ZcashAdapter"; +import type { NetworkConfig } from "../../../types"; +import { resolveNetwork } from "../../../utils/networkResolver"; +import SearchBox from "../../common/SearchBox"; +import ZcashBlocksTable from "./ZcashBlocksTable"; +import ZcashDashboardStats from "./ZcashDashboardStats"; +import ZcashTransactionsTable from "./ZcashTransactionsTable"; +import ZcashValuePools from "./ZcashValuePools"; + +// Default Zcash network config for fallback +const DEFAULT_ZCASH_NETWORK: NetworkConfig = { + type: "zcash", + networkId: "bip122:00040fe8ec8471911baa1db1266ea15d", + slug: "zec", + name: "Zcash Mainnet", + shortName: "Zcash", + currency: "ZEC", + color: "#F4B728", +}; + +export default function ZcashNetwork() { + const { t } = useTranslation("zcash"); + const location = useLocation(); + + // Extract network slug from path (e.g., "/tzec" → "tzec", "/zec" → "zec") + const pathSlug = location.pathname.split("/")[1] || "zec"; + const network = resolveNetwork(pathSlug, getAllNetworks()) || DEFAULT_ZCASH_NETWORK; + const dashboard = useZcashDashboard(network); + + const networkName = network.name.toUpperCase(); + const networkColor = network.color || "#F4B728"; + const { error } = dashboard; + + return ( +
+
+

+ + {networkName} + +

+ {network.description &&

{network.description}

} + + + {error && ( +

+ {error instanceof ZcashRpcError && error.kind === "rateLimited" + ? t("dashboard.rateLimited") + : t("dashboard.loadError", { message: error.message })} +

+ )} + + + + + +
+ + +
+ + {network.links && network.links.length > 0 && ( +
+
+ {network.links.map((link) => ( + + {link.name} + + ))} +
+
+ )} +
+
+ ); +} diff --git a/src/config/networks.json b/src/config/networks.json index 98c90881..8bdf199e 100644 --- a/src/config/networks.json +++ b/src/config/networks.json @@ -1,5 +1,5 @@ { - "updatedAt": "2026-01-30", + "updatedAt": "2026-09-14", "networks": [ { "type": "evm", @@ -524,6 +524,59 @@ "description": "Get testnet BTC" } ] + }, + { + "type": "zcash", + "networkId": "bip122:00040fe8ec8471911baa1db1266ea15d", + "slug": "zec", + "name": "Zcash Mainnet", + "shortName": "Zcash", + "description": "Privacy-preserving cryptocurrency with shielded transactions", + "currency": "ZEC", + "color": "#F4B728", + "isTestnet": false, + "logo": "assets/networks/zcash-mainnet.svg", + "links": [ + { + "name": "Website", + "url": "https://z.cash", + "description": "Official Zcash website" + }, + { + "name": "Docs", + "url": "https://zebra.zfnd.org", + "description": "Zebra node documentation" + }, + { + "name": "GitHub", + "url": "https://github.com/ZcashFoundation/zebra", + "description": "Zebra repository" + } + ] + }, + { + "type": "zcash", + "networkId": "bip122:05a60a92d99d85997cce3b87616c089f", + "slug": "tzec", + "name": "Zcash Testnet", + "shortName": "ZEC Testnet", + "description": "Zcash testnet for developers", + "currency": "TAZ", + "color": "#F4B728", + "isTestnet": true, + "logo": "assets/networks/zcash-mainnet.svg", + "links": [ + { + "name": "Website", + "url": "https://z.cash", + "description": "Official Zcash website" + }, + { + "name": "Docs", + "url": "https://zebra.zfnd.org", + "description": "Zebra node documentation" + } + ] } ] } diff --git a/src/config/zcashConstants.ts b/src/config/zcashConstants.ts index 2a985ee1..07a5d43f 100644 --- a/src/config/zcashConstants.ts +++ b/src/config/zcashConstants.ts @@ -36,3 +36,10 @@ export const MAX_INPUT_LOOKUPS = 10; // Backoff before retrying a rate-limited call (hosted gateways allow ~5 requests/min per IP) export const RATE_LIMIT_RETRY_DELAYS_MS = [15_000, 30_000]; + +// Dashboard sizing, kept small so a refresh fits within hosted rate limits +export const DASHBOARD_BLOCKS = 5; +export const DASHBOARD_TXS = 10; + +// Zcash targets a 75 second block interval +export const REFRESH_INTERVAL_MS = 90_000; diff --git a/src/hooks/useZcashDashboard.ts b/src/hooks/useZcashDashboard.ts new file mode 100644 index 00000000..8e6c49cf --- /dev/null +++ b/src/hooks/useZcashDashboard.ts @@ -0,0 +1,113 @@ +/** + * Hook for fetching Zcash network dashboard data with auto-refresh + * + * Hosted Zcash gateways allow only a few requests per minute, so data loads in two stages: + * network stats and the tip block (3 calls) render first, then summaries for the previous + * blocks load one at a time. Summaries are cached across refreshes, so a refresh usually + * only fetches the stats, the new tip and any block mined since. + */ + +import { useCallback, useEffect, useRef, useState } from "react"; +import { DASHBOARD_BLOCKS, DASHBOARD_TXS, REFRESH_INTERVAL_MS } from "../config/zcashConstants"; +import type { NetworkConfig, ZcashBlock, ZcashNetworkStats, ZcashTransaction } from "../types"; +import { useDataService } from "./useDataService"; + +export interface ZcashDashboardData { + stats: ZcashNetworkStats | null; + latestBlocks: ZcashBlock[]; + latestTransactions: ZcashTransaction[]; + loading: boolean; + loadingBlocks: boolean; + error: Error | null; + lastUpdated: number | null; +} + +const initialState: ZcashDashboardData = { + stats: null, + latestBlocks: [], + latestTransactions: [], + loading: true, + loadingBlocks: true, + error: null, + lastUpdated: null, +}; + +export function useZcashDashboard(network: NetworkConfig): ZcashDashboardData { + const dataService = useDataService(network); + const [data, setData] = useState(initialState); + const isFetchingRef = useRef(false); + const blockCacheRef = useRef(new Map()); + + const fetchDashboardData = useCallback(async () => { + if (!dataService || !dataService.isZcash() || isFetchingRef.current) { + return; + } + + isFetchingRef.current = true; + const cache = blockCacheRef.current; + + try { + const adapter = dataService.getZcashAdapter(); + + // Stage 1: stats and value pools, then the tip block with its transactions + const { data: stats } = await adapter.getNetworkStats(); + const { data: tip } = await adapter.getBlock(stats.blockHeight); + cache.set(tip.block.height, tip.block); + + const heights = Array.from( + { length: DASHBOARD_BLOCKS }, + (_, i) => tip.block.height - i, + ).filter((height) => height >= 0); + const collectBlocks = () => + heights.flatMap((height) => { + const block = cache.get(height); + return block ? [block] : []; + }); + + setData((prev) => ({ + ...prev, + stats, + latestBlocks: collectBlocks(), + latestTransactions: tip.transactions.slice(0, DASHBOARD_TXS), + loading: false, + error: null, + lastUpdated: Date.now(), + })); + + // Stage 2: summaries only for blocks not fetched by an earlier refresh + const missing = heights.filter((height) => !cache.has(height)); + for (const block of await adapter.getBlockSummaries(missing)) { + cache.set(block.height, block); + } + for (const height of cache.keys()) { + if (!heights.includes(height)) cache.delete(height); + } + + setData((prev) => ({ ...prev, latestBlocks: collectBlocks(), loadingBlocks: false })); + } catch (err) { + setData((prev) => ({ + ...prev, + loading: false, + loadingBlocks: false, + error: err instanceof Error ? err : new Error(String(err)), + })); + } finally { + isFetchingRef.current = false; + } + }, [dataService]); + + // Initial fetch + useEffect(() => { + setData(initialState); + blockCacheRef.current.clear(); + fetchDashboardData(); + }, [fetchDashboardData]); + + // Set up polling interval + useEffect(() => { + const intervalId = setInterval(fetchDashboardData, REFRESH_INTERVAL_MS); + return () => clearInterval(intervalId); + }, [fetchDashboardData]); + + return data; +} diff --git a/src/hooks/useZcashTimeAgo.ts b/src/hooks/useZcashTimeAgo.ts new file mode 100644 index 00000000..3e1a2629 --- /dev/null +++ b/src/hooks/useZcashTimeAgo.ts @@ -0,0 +1,20 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; + +/** + * Localized short relative time ("5m ago") for Zcash pages + */ +export function useZcashTimeAgo(): (timestamp: number) => string { + const { t } = useTranslation("zcash"); + + return useCallback( + (timestamp: number) => { + const seconds = Math.max(0, Math.floor(Date.now() / 1000 - timestamp)); + if (seconds < 60) return t("common.secondsAgo", { count: seconds }); + if (seconds < 3600) return t("common.minutesAgo", { count: Math.floor(seconds / 60) }); + if (seconds < 86400) return t("common.hoursAgo", { count: Math.floor(seconds / 3600) }); + return t("common.daysAgo", { count: Math.floor(seconds / 86400) }); + }, + [t], + ); +} diff --git a/src/styles/components.css b/src/styles/components.css index 2299c363..b7e5d072 100644 --- a/src/styles/components.css +++ b/src/styles/components.css @@ -6353,6 +6353,133 @@ button.tx-section-header-toggle { justify-content: center; } +/* Zcash value pools */ +.zec-value-pools { + background: var(--bg-secondary); + border: 1px solid var(--overlay-light-8); + border-radius: 12px; + padding: 16px 20px; + margin: 16px 0; +} + +.zec-value-pools-header { + display: flex; + align-items: center; + gap: 6px; + margin-bottom: 12px; +} + +.zec-pool-bar { + display: flex; + height: 10px; + border-radius: 5px; + overflow: hidden; + background: var(--overlay-light-5); +} + +.zec-pool-segment { + width: var(--pool-share); + background: var(--pool-color); +} + +.zec-pool-list { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 8px 16px; + list-style: none; + margin: 12px 0 0; + padding: 0; +} + +.zec-pool-item { + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + font-size: 0.85rem; +} + +.zec-pool-swatch { + width: 10px; + height: 10px; + border-radius: 2px; + flex-shrink: 0; + background: var(--pool-color); +} + +.zec-pool-name { + color: var(--text-primary); +} + +.zec-pool-value { + margin-left: auto; + color: var(--text-secondary); + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.zec-pool-share { + min-width: 3.5em; + text-align: right; + color: var(--color-text-muted); + font-variant-numeric: tabular-nums; +} + +.zec-pool-transparent { + --pool-color: var(--text-tertiary); +} + +.zec-pool-sprout { + --pool-color: var(--color-primary-muted); +} + +.zec-pool-sapling { + --pool-color: var(--color-info); +} + +.zec-pool-orchard { + --pool-color: var(--color-primary); +} + +.zec-pool-lockbox { + --pool-color: var(--color-warning); +} + +.zec-pool-ironwood { + --pool-color: var(--color-accent); +} + +@media (max-width: 768px) { + .zec-pool-list { + grid-template-columns: 1fr; + } +} + +/* Zcash transaction kind badge */ +.zec-kind-badge { + display: inline-block; + padding: 1px 8px; + border-radius: 10px; + font-size: 0.7rem; + font-weight: 600; + white-space: nowrap; + background: var(--overlay-light-5); + color: var(--text-secondary); +} + +.zec-kind-shielded, +.zec-kind-shielding, +.zec-kind-deshielding, +.zec-kind-mixed { + background: var(--color-primary-alpha-15); + color: var(--color-primary); +} + +.zec-kind-coinbase { + background: var(--color-warning-alpha-15); + color: var(--color-warning); +} + /* Clickable stat label */ .dashboard-stat-label-link { display: block; diff --git a/src/utils/zcashFormatters.ts b/src/utils/zcashFormatters.ts index ba54bfcc..b4c5b16c 100644 --- a/src/utils/zcashFormatters.ts +++ b/src/utils/zcashFormatters.ts @@ -22,3 +22,13 @@ export { export function formatZEC(valueZat: number, currency = "ZEC"): string { return `${(valueZat / ZATOSHIS_PER_ZEC).toFixed(8)} ${currency}`; } + +/** + * Format a zatoshi amount as ZEC with thousands separators and few decimals (for dashboards) + */ +export function formatZECCompact(valueZat: number, currency = "ZEC"): string { + const value = valueZat / ZATOSHIS_PER_ZEC; + const maximumFractionDigits = value < 1_000 ? 2 : 0; + return `${value.toLocaleString(undefined, { maximumFractionDigits })} ${currency}`; +} + diff --git a/src/utils/zcashUtils.test.ts b/src/utils/zcashUtils.test.ts index d50ab5f2..6309fc93 100644 --- a/src/utils/zcashUtils.test.ts +++ b/src/utils/zcashUtils.test.ts @@ -6,6 +6,7 @@ import { computeFee, detectZcashAddressType, getShieldedNetZat, + getShieldedSupplyPercent, getTransactionPools, isZcashAddress, normalizeZcashAddress, @@ -234,3 +235,25 @@ describe("zecToZat", () => { expect(zecToZat(0.0001)).toBe(10_000); }); }); + +describe("getShieldedSupplyPercent", () => { + it("sums the shielded pools but not transparent or lockbox funds", () => { + const percent = getShieldedSupplyPercent({ + chainSupplyZat: 1_000, + valuePools: [ + { id: "transparent", valueZat: 600 }, + { id: "sprout", valueZat: 10 }, + { id: "sapling", valueZat: 100 }, + { id: "orchard", valueZat: 90 }, + { id: "lockbox", valueZat: 50 }, + { id: "ironwood", valueZat: 150 }, + ], + }); + + expect(percent).toBe(35); + }); + + it("returns null when the chain supply is unknown", () => { + expect(getShieldedSupplyPercent({ chainSupplyZat: undefined, valuePools: [] })).toBeNull(); + }); +}); diff --git a/src/utils/zcashUtils.ts b/src/utils/zcashUtils.ts index 41bb5a70..22b91cfe 100644 --- a/src/utils/zcashUtils.ts +++ b/src/utils/zcashUtils.ts @@ -10,6 +10,7 @@ import { import type { ZcashAddressType, ZcashFee, + ZcashNetworkStats, ZcashShieldedPool, ZcashTransaction, ZcashTxKind, @@ -164,6 +165,19 @@ export function computeFee(tx: ZcashTransaction): ZcashFee { return { kind: "known", zat: inputZat + getShieldedNetZat(tx) - getTransparentOutputZat(tx) }; } +/** + * Percentage of the chain supply held in shielded pools, or null when the supply is unknown + */ +export function getShieldedSupplyPercent( + stats: Pick, +): number | null { + if (!stats.chainSupplyZat) return null; + const shieldedZat = stats.valuePools + .filter((pool) => (ZCASH_SHIELDED_POOLS as readonly string[]).includes(pool.id)) + .reduce((sum, pool) => sum + pool.valueZat, 0); + return (shieldedZat / stats.chainSupplyZat) * 100; +} + export type ZcashRpcErrorKind = "unsupported" | "rateLimited" | "failed"; const RATE_LIMITED_PATTERN = /status: 429/; From a5841b99a69ef5eedc99e54ec4b145fbcd976eb8 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:21:26 -0300 Subject: [PATCH 3/7] test(e2e): add hermetic Zcash dashboard spec --- e2e/fixtures/zcash.ts | 91 +++++++++++++++++++ .../shared/mocked/zcash-dashboard.spec.ts | 51 +++++++++++ 2 files changed, 142 insertions(+) create mode 100644 e2e/fixtures/zcash.ts create mode 100644 e2e/tests/shared/mocked/zcash-dashboard.spec.ts diff --git a/e2e/fixtures/zcash.ts b/e2e/fixtures/zcash.ts new file mode 100644 index 00000000..abbceb6d --- /dev/null +++ b/e2e/fixtures/zcash.ts @@ -0,0 +1,91 @@ +import type { Page } from "@playwright/test"; +import { BLOCK_3483400 } from "../../src/services/adapters/ZcashAdapter/fixtures"; +import { mockJsonRpc } from "./rpcMock"; + +/** The built-in Zcash RPC defaults are Tatum's gateways, so every Zcash request matches this */ +export const ZCASH_RPC_PATTERN = /zcash-(mainnet|testnet)(-zebrad)?\.gateway\.tatum\.io/; + +export const ZCASH = { + networkSlug: "zec", + tipHeight: BLOCK_3483400.height, + mempoolSize: 9, +} as const; + +// Mainnet value pools at block 3,483,461, in zatoshis +const VALUE_POOLS: Array<[string, number]> = [ + ["transparent", 1_197_461_726_829_416], + ["sprout", 2_259_146_261_837], + ["sapling", 51_144_292_792_244], + ["orchard", 41_719_811_959_765], + ["lockbox", 6_319_912_500_000], + ["ironwood", 394_349_188_711_218], +]; +const CHAIN_SUPPLY_ZAT = 1_693_254_079_054_480; + +export interface RecordedRpcCall { + method: string; + params: unknown[]; +} + +/** Earlier blocks reuse the tip's header with their own height and hash */ +function blockSummary(height: number) { + return { + ...BLOCK_3483400, + height, + hash: height.toString(16).padStart(64, "0"), + confirmations: ZCASH.tipHeight - height + 1, + tx: [height.toString(16).padStart(64, "f")], + }; +} + +/** + * Serve a Zcash chain whose tip is mainnet block 3,483,400 and record every Zcash RPC call + * the page makes, including methods that are not mocked. + */ +export async function mockZcashRpc(page: Page): Promise { + const calls: RecordedRpcCall[] = []; + page.on("request", (request) => { + if (request.method() !== "POST" || !ZCASH_RPC_PATTERN.test(request.url())) return; + try { + const body = JSON.parse(request.postData() ?? "{}"); + calls.push({ method: body.method, params: body.params ?? [] }); + } catch { + // Not a JSON-RPC body + } + }); + + await mockJsonRpc(page, ZCASH_RPC_PATTERN, { + getblockcount: { result: ZCASH.tipHeight }, + getblockchaininfo: { + result: { + chain: "main", + blocks: ZCASH.tipHeight, + headers: ZCASH.tipHeight, + bestblockhash: BLOCK_3483400.hash, + difficulty: BLOCK_3483400.difficulty, + estimatedheight: ZCASH.tipHeight, + verificationprogress: 1, + chainSupply: { + chainValue: CHAIN_SUPPLY_ZAT / 1e8, + chainValueZat: CHAIN_SUPPLY_ZAT, + monitored: true, + }, + valuePools: VALUE_POOLS.map(([id, chainValueZat]) => ({ + id, + chainValue: chainValueZat / 1e8, + chainValueZat, + monitored: true, + })), + }, + }, + getmempoolinfo: { result: { size: ZCASH.mempoolSize, bytes: 4_512, usage: 9_000 } }, + getblock: (params) => { + const [hashOrHeight, verbosity] = params as [string, number]; + const isTip = + hashOrHeight === String(ZCASH.tipHeight) || hashOrHeight === BLOCK_3483400.hash; + return isTip && verbosity === 2 ? BLOCK_3483400 : blockSummary(Number(hashOrHeight)); + }, + }); + + return calls; +} diff --git a/e2e/tests/shared/mocked/zcash-dashboard.spec.ts b/e2e/tests/shared/mocked/zcash-dashboard.spec.ts new file mode 100644 index 00000000..fdb80e5d --- /dev/null +++ b/e2e/tests/shared/mocked/zcash-dashboard.spec.ts @@ -0,0 +1,51 @@ +import { expect, test } from "../../../fixtures/test"; +import { mockZcashRpc, ZCASH } from "../../../fixtures/zcash"; + +/** + * Hermetic Zcash network dashboard. RPC traffic to the built-in Tatum gateways is served + * from mainnet block 3,483,400, so the page renders without a live node or rate limits. + */ +test.describe("Zcash dashboard", () => { + test("renders chain stats, value pools, latest blocks and transactions", async ({ page }) => { + await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}`); + + await expect(page.locator(".network-title-name")).toHaveText("ZCASH MAINNET"); + + const stats = page.locator(".dashboard-stats-row"); + await expect(stats).toContainText("#3,483,400"); + await expect(stats).toContainText(`${ZCASH.mempoolSize} txs`); + await expect(stats).toContainText("% shielded"); + + const pools = page.getByTestId("zcash-value-pools"); + for (const name of ["Transparent", "Sprout", "Sapling", "Orchard", "Lockbox", "Ironwood"]) { + await expect(pools).toContainText(name); + } + + const blocks = page.getByTestId("zcash-blocks-table"); + await expect(blocks).toContainText("#3,483,400"); + await expect(blocks).toContainText("#3,483,396"); + + const transactions = page.getByTestId("zcash-transactions-table"); + await expect(transactions).toContainText("Coinbase"); + await expect(transactions).toContainText("Fully shielded"); + await expect(transactions).toContainText("Shielding"); + + await expect(page.locator(".network-block-number")).toHaveText("#3,483,400"); + }); + + test("requests blocks by height string and never calls getblockhash", async ({ page }) => { + const calls = await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}`); + await expect(page.getByTestId("zcash-blocks-table")).toContainText("#3,483,396"); + + const getblockCalls = calls.filter((call) => call.method === "getblock"); + expect(getblockCalls.length).toBeGreaterThanOrEqual(5); + for (const call of getblockCalls) { + expect(typeof call.params[0]).toBe("string"); + } + expect(calls.map((call) => call.method)).not.toContain("getblockhash"); + }); +}); From 8320627506972e99d86a7bebbb9e1fb3d11a4530 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Mon, 14 Sep 2026 19:21:27 -0300 Subject: [PATCH 4/7] docs(readme): list Zcash networks and slugs --- .claude/rules/commands.md | 2 ++ README.md | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/.claude/rules/commands.md b/.claude/rules/commands.md index 2683cf2f..4ea76118 100644 --- a/.claude/rules/commands.md +++ b/.claude/rules/commands.md @@ -144,3 +144,5 @@ npm start ``` Supported chain IDs: 1 (Ethereum), 42161 (Arbitrum), 10 (Optimism), 8453 (Base), 56 (BSC), 137 (Polygon), 31337 (Hardhat), 97 (BSC Testnet), 11155111 (Sepolia), 43114 (Avalanche) + +Non-EVM networks are selected by slug: `btc`, `tbtc`, `zec`, `tzec`, `sol`, `sol-devnet`, `sol-testnet` (e.g. `OPENSCAN_NETWORKS="1,btc,zec"`). diff --git a/README.md b/README.md index fb6ee43d..4c9fb1af 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,10 @@ A trustless, open-source blockchain explorer for Bitcoin, Ethereum, and Layer 2 - **Bitcoin Mainnet** (`/btc`) - The main Bitcoin network - **Bitcoin Testnet4** (`/tbtc`) - Bitcoin test network for development +#### Zcash Networks +- **Zcash Mainnet** (`/zec`) - Privacy-preserving network with transparent and shielded value pools +- **Zcash Testnet** (`/tzec`) - Zcash test network for development + #### EVM Networks - **Ethereum Mainnet** - The main Ethereum network - **Sepolia Testnet** - Ethereum test network for development From 56eed5695c888f17e12a99e6e7086829237797b1 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 20:06:56 -0300 Subject: [PATCH 5/7] perf(adapter): share zcash chain info between navbar and dashboard The navbar polled getblockcount while the dashboard fetched getblockchaininfo for the same height. Both now read one getblockchaininfo response, shared for 30s per network and endpoint list. One caller aborting doesn't cancel it for the others, and a failed response isn't reused. The per-endpoint state (unsupported methods, chain info) now lives in a ZcashSession from getZcashSession(). --- src/hooks/useZcashTimeAgo.ts | 20 ---- src/services/DataService.ts | 4 +- .../ZcashAdapter/ZcashAdapter.test.ts | 98 +++++++++++++++---- .../adapters/ZcashAdapter/ZcashAdapter.ts | 97 ++++++++++++------ 4 files changed, 150 insertions(+), 69 deletions(-) delete mode 100644 src/hooks/useZcashTimeAgo.ts diff --git a/src/hooks/useZcashTimeAgo.ts b/src/hooks/useZcashTimeAgo.ts deleted file mode 100644 index 3e1a2629..00000000 --- a/src/hooks/useZcashTimeAgo.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { useCallback } from "react"; -import { useTranslation } from "react-i18next"; - -/** - * Localized short relative time ("5m ago") for Zcash pages - */ -export function useZcashTimeAgo(): (timestamp: number) => string { - const { t } = useTranslation("zcash"); - - return useCallback( - (timestamp: number) => { - const seconds = Math.max(0, Math.floor(Date.now() / 1000 - timestamp)); - if (seconds < 60) return t("common.secondsAgo", { count: seconds }); - if (seconds < 3600) return t("common.minutesAgo", { count: Math.floor(seconds / 60) }); - if (seconds < 86400) return t("common.hoursAgo", { count: Math.floor(seconds / 3600) }); - return t("common.daysAgo", { count: Math.floor(seconds / 86400) }); - }, - [t], - ); -} diff --git a/src/services/DataService.ts b/src/services/DataService.ts index 9d444b7f..293342b6 100644 --- a/src/services/DataService.ts +++ b/src/services/DataService.ts @@ -15,7 +15,7 @@ import { AdapterFactory } from "./adapters/adaptersFactory"; import type { NetworkAdapter } from "./adapters/NetworkAdapter"; import type { BitcoinAdapter } from "./adapters/BitcoinAdapter/BitcoinAdapter"; import type { SolanaAdapter } from "./adapters/SolanaAdapter/SolanaAdapter"; -import { getUnsupportedMethods, type ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; +import { getZcashSession, type ZcashAdapter } from "./adapters/ZcashAdapter/ZcashAdapter"; import type { NetworkConfig, NetworkType, RpcUrlsContextType } from "../types"; import { getRPCUrls } from "../config/rpcConfig"; import { getNetworkRpcKey, getChainIdFromNetwork } from "../utils/networkResolver"; @@ -85,7 +85,7 @@ export class DataService { type: strategy, }); this.zcashAdapter = AdapterFactory.createZcashAdapter(network.networkId, zcashClient, { - unsupportedMethods: getUnsupportedMethods(network.networkId, rpcUrls), + session: getZcashSession(network.networkId, rpcUrls), }); this.networkAdapter = null as unknown as NetworkAdapter; } else if (network.type === "solana") { diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts index a211df80..dc2e53b9 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.test.ts @@ -10,7 +10,7 @@ import { SHIELDING_TX, } from "./fixtures"; import type { ZcashRawBlock, ZcashRawTransaction } from "./utils"; -import { getUnsupportedMethods, ZcashAdapter, ZcashRpcError } from "./ZcashAdapter"; +import { getZcashSession, ZcashAdapter, ZcashRpcError, type ZcashSession } from "./ZcashAdapter"; const NETWORK_ID = "bip122:00040fe8ec8471911baa1db1266ea15d"; const T_ADDRESS = "t1KAuVfS2r2hc7RwSh6GTuyfqCGMFEpwkZ2"; @@ -43,16 +43,18 @@ function createClient() { }; } -function setup(unsupportedMethods = new Set()) { +function setup(session: ZcashSession = { unsupportedMethods: new Set() }) { const client = createClient(); const sleep = vi.fn().mockResolvedValue(undefined); const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient, { sleep, - unsupportedMethods, + session, }); return { adapter, client, sleep }; } +const CHAIN_INFO = { chain: "main", blocks: 3483464, bestblockhash: "0".repeat(64), difficulty: 1 }; + afterEach(() => { vi.useRealTimers(); }); @@ -310,24 +312,24 @@ describe("ZcashAdapter transactions", () => { describe("ZcashAdapter RPC failures", () => { it("retries rate-limited calls after a backoff", async () => { const { adapter, client, sleep } = setup(); - client.getBlockCount - .mockResolvedValueOnce(fail("HTTP error! status: 429", "HTTP error! status: 429")) - .mockResolvedValueOnce(ok(3483464)); + client.getRawMempool + .mockResolvedValueOnce(fail(RATE_LIMITED, RATE_LIMITED)) + .mockResolvedValueOnce(ok({})); - await expect(adapter.getLatestBlockNumber()).resolves.toBe(3483464); + await expect(adapter.getMempoolEntries()).resolves.toMatchObject({ data: [] }); expect(sleep).toHaveBeenCalledWith(15_000, undefined); }); it("gives up after the last backoff", async () => { const { adapter, client, sleep } = setup(); - client.getBlockCount.mockResolvedValue(fail("HTTP error! status: 429")); + client.getRawMempool.mockResolvedValue(fail(RATE_LIMITED)); - await expect(adapter.getLatestBlockNumber()).rejects.toMatchObject({ + await expect(adapter.getMempoolEntries()).rejects.toMatchObject({ name: "ZcashRpcError", kind: "rateLimited", }); expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([15_000, 30_000]); - expect(client.getBlockCount).toHaveBeenCalledTimes(3); + expect(client.getRawMempool).toHaveBeenCalledTimes(3); }); it("throws instead of returning empty data when every endpoint fails", async () => { @@ -376,17 +378,17 @@ describe("ZcashAdapter RPC failures", () => { vi.useFakeTimers(); const client = createClient(); const adapter = new ZcashAdapter(NETWORK_ID, client as unknown as ZcashClient); - client.getBlockCount.mockResolvedValue(fail(RATE_LIMITED)); + client.getRawMempool.mockResolvedValue(fail(RATE_LIMITED)); const controller = new AbortController(); - const pending = adapter.getLatestBlockNumber({ signal: controller.signal }); + const pending = adapter.getMempoolEntries({ signal: controller.signal }); const outcome = pending.catch((caught: unknown) => caught); await vi.advanceTimersByTimeAsync(5_000); controller.abort(); expect(await outcome).toMatchObject({ name: "AbortError" }); await vi.advanceTimersByTimeAsync(60_000); - expect(client.getBlockCount).toHaveBeenCalledTimes(1); + expect(client.getRawMempool).toHaveBeenCalledTimes(1); }); it("doesn't send a call that was aborted before it started", async () => { @@ -401,17 +403,79 @@ describe("ZcashAdapter RPC failures", () => { }); it("remembers unsupported methods across adapters sharing an endpoint list", async () => { - const unsupported = getUnsupportedMethods(NETWORK_ID, ["https://rpc.test/remember"]); - const first = setup(unsupported); + const first = setup(getZcashSession(NETWORK_ID, ["https://rpc.test/remember"])); first.client.getAddressBalance.mockResolvedValue(fail(METHOD_NOT_FOUND)); await first.adapter.getAddress(T_ADDRESS); - const second = setup(getUnsupportedMethods(NETWORK_ID, ["https://rpc.test/remember"])); + const second = setup(getZcashSession(NETWORK_ID, ["https://rpc.test/remember"])); const result = await second.adapter.getAddress(T_ADDRESS); expect(result.balance).toEqual({ availability: "unsupported" }); expect(second.client.getAddressBalance).not.toHaveBeenCalled(); - expect(getUnsupportedMethods(NETWORK_ID, ["https://other.test"]).size).toBe(0); + expect(getZcashSession(NETWORK_ID, ["https://other.test"]).unsupportedMethods.size).toBe(0); + }); +}); + +describe("ZcashAdapter shared chain info", () => { + it("serves the height and the network stats from one getblockchaininfo call", async () => { + const { adapter, client } = setup(); + client.getBlockchainInfo.mockResolvedValue(ok(CHAIN_INFO)); + client.getMempoolInfo.mockResolvedValue(ok({ size: 0, bytes: 0, usage: 0 })); + + const [height, stats] = await Promise.all([ + adapter.getLatestBlockNumber(), + adapter.getNetworkStats(), + ]); + + expect(height).toBe(3483464); + expect(stats.data.blockHeight).toBe(3483464); + expect(client.getBlockchainInfo).toHaveBeenCalledTimes(1); + expect(client.getBlockCount).not.toHaveBeenCalled(); + }); + + it("shares the response across adapters of one session, then refreshes it", async () => { + vi.useFakeTimers(); + const session: ZcashSession = { unsupportedMethods: new Set() }; + const navbar = setup(session); + const page = setup(session); + navbar.client.getBlockchainInfo.mockResolvedValue(ok(CHAIN_INFO)); + page.client.getBlockchainInfo.mockResolvedValue(ok({ ...CHAIN_INFO, blocks: 3483465 })); + + await navbar.adapter.getLatestBlockNumber(); + await expect(page.adapter.getLatestBlockNumber()).resolves.toBe(3483464); + expect(page.client.getBlockchainInfo).not.toHaveBeenCalled(); + + vi.advanceTimersByTime(31_000); + await expect(page.adapter.getLatestBlockNumber()).resolves.toBe(3483465); + }); + + it("lets one caller abort without cancelling the shared request for the others", async () => { + const { adapter, client } = setup(); + let respond: (value: unknown) => void = () => {}; + client.getBlockchainInfo.mockReturnValue( + new Promise((resolve) => { + respond = resolve; + }), + ); + const controller = new AbortController(); + + const aborted = adapter.getLatestBlockNumber({ signal: controller.signal }); + const other = adapter.getLatestBlockNumber(); + controller.abort(); + respond(ok(CHAIN_INFO)); + + await expect(aborted).rejects.toMatchObject({ name: "AbortError" }); + await expect(other).resolves.toBe(3483464); + }); + + it("drops a failed response so the next caller asks again", async () => { + const { adapter, client } = setup(); + client.getBlockchainInfo + .mockResolvedValueOnce(fail("HTTP error! status: 502")) + .mockResolvedValueOnce(ok(CHAIN_INFO)); + + await expect(adapter.getLatestBlockNumber()).rejects.toBeInstanceOf(ZcashRpcError); + await expect(adapter.getLatestBlockNumber()).resolves.toBe(3483464); }); }); diff --git a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts index c6ab533c..8921e32c 100644 --- a/src/services/adapters/ZcashAdapter/ZcashAdapter.ts +++ b/src/services/adapters/ZcashAdapter/ZcashAdapter.ts @@ -69,16 +69,27 @@ export interface ZcashCallOptions { signal?: AbortSignal; } +/** + * State shared by every adapter for one network and endpoint list. A new DataService (and + * adapter) is created per page, so anything worth keeping across pages lives here. + */ +export interface ZcashSession { + /** Methods the endpoints reported as unsupported, so pages stop probing them */ + unsupportedMethods: Set; + /** Latest getblockchaininfo request, reused briefly by the navbar and the dashboard */ + chainInfo?: { at: number; request: Promise> }; +} + export interface ZcashAdapterOptions { /** Wait between rate-limit retries (injectable for tests) */ sleep?: (ms: number, signal?: AbortSignal) => Promise; - /** - * Methods the configured endpoints reported as unsupported. Share one set per endpoint list - * (see getUnsupportedMethods) so pages stop probing methods a gateway blocks. - */ - unsupportedMethods?: Set; + /** Shared session state (see getZcashSession); a private one by default */ + session?: ZcashSession; } +// How long a getblockchaininfo result is shared (blocks arrive every ~75s) +const CHAIN_INFO_TTL_MS = 30_000; + export interface ZcashBlockSummaries { /** Newest first */ blocks: ZcashBlock[]; @@ -115,20 +126,32 @@ const defaultSleep = (ms: number, signal?: AbortSignal) => signal?.addEventListener("abort", onAbort, { once: true }); }); -const unsupportedByEndpoints = new Map>(); +const sessions = new Map(); /** - * The session-wide set of unsupported methods for one network and endpoint list. A new - * DataService is created per page, so the set lives here rather than on the adapter. + * The session state for one network and endpoint list, shared by every page's adapter */ -export function getUnsupportedMethods(networkId: string, rpcUrls: string[]): Set { +export function getZcashSession(networkId: string, rpcUrls: string[]): ZcashSession { const key = `${networkId}|${rpcUrls.join(",")}`; - let methods = unsupportedByEndpoints.get(key); - if (!methods) { - methods = new Set(); - unsupportedByEndpoints.set(key, methods); + let session = sessions.get(key); + if (!session) { + session = { unsupportedMethods: new Set() }; + sessions.set(key, session); } - return methods; + return session; +} + +/** + * Wait for a shared request without letting one caller's abort cancel it for the others + */ +function untilAborted(request: Promise, signal?: AbortSignal): Promise { + if (!signal) return request; + signal.throwIfAborted(); + return new Promise((resolve, reject) => { + const onAbort = () => reject(signal.reason); + signal.addEventListener("abort", onAbort, { once: true }); + request.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort)); + }); } function mapSection(section: ZcashRpcSection, map: (data: T) => U): ZcashRpcSection { @@ -148,13 +171,13 @@ export class ZcashAdapter { readonly networkId: string; private client: ZcashClient; private sleep: (ms: number, signal?: AbortSignal) => Promise; - private unsupportedMethods: Set; + private session: ZcashSession; constructor(networkId: string, client: ZcashClient, options: ZcashAdapterOptions = {}) { this.networkId = networkId; this.client = client; this.sleep = options.sleep ?? defaultSleep; - this.unsupportedMethods = options.unsupportedMethods ?? new Set(); + this.session = options.session ?? { unsupportedMethods: new Set() }; } /** @@ -181,7 +204,7 @@ export class ZcashAdapter { request: () => Promise>, signal?: AbortSignal, ): Promise> { - if (this.unsupportedMethods.has(method)) { + if (this.session.unsupportedMethods.has(method)) { throw new ZcashRpcError(method, "unsupported", [ `${method} is not supported by the configured endpoints`, ]); @@ -202,7 +225,7 @@ export class ZcashAdapter { response.error ? [response.error] : [], ); const kind = classifyRpcErrors(messages); - if (kind === "unsupported") this.unsupportedMethods.add(method); + if (kind === "unsupported") this.session.unsupportedMethods.add(method); const delay = RATE_LIMIT_RETRY_DELAYS_MS[attempt]; if (kind !== "rateLimited" || delay === undefined) { @@ -237,15 +260,33 @@ export class ZcashAdapter { } /** - * Get the latest block height (1 call) + * getblockchaininfo, shared for a few seconds between every caller on this network (the + * navbar polls the height while the dashboard reads the same response for its stats) */ - async getLatestBlockNumber(options: ZcashCallOptions = {}): Promise { - const { data } = await this.call( - "getblockcount", - () => this.client.getBlockCount(), - options.signal, + private getChainInfo(signal?: AbortSignal): Promise> { + const cached = this.session.chainInfo; + if (cached && Date.now() - cached.at < CHAIN_INFO_TTL_MS) { + return untilAborted(cached.request, signal); + } + + // Not tied to the caller's signal: other callers may be waiting on the same request + const request = this.call("getblockchaininfo", () => + this.client.getBlockchainInfo(), ); - return data; + const entry = { at: Date.now(), request }; + this.session.chainInfo = entry; + request.catch(() => { + if (this.session.chainInfo === entry) this.session.chainInfo = undefined; + }); + return untilAborted(request, signal); + } + + /** + * Get the latest block height (1 call, shared with getNetworkStats) + */ + async getLatestBlockNumber(options: ZcashCallOptions = {}): Promise { + const { data } = await this.getChainInfo(options.signal); + return data.blocks; } /** @@ -255,11 +296,7 @@ export class ZcashAdapter { options: ZcashCallOptions = {}, ): Promise> { const [info, mempool] = await Promise.all([ - this.call( - "getblockchaininfo", - () => this.client.getBlockchainInfo(), - options.signal, - ), + this.getChainInfo(options.signal), this.call("getmempoolinfo", () => this.client.getMempoolInfo(), options.signal), ]); From 206ee4de33f4cf79f8f596b7c91e0e81c948ff95 Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 20:06:57 -0300 Subject: [PATCH 6/7] fix(network): guard zcash dashboard against stale and failed loads - The dashboard aborts its requests when the network changes, so a slow (rate-limited) zec response can't fill the tzec page. The in-flight guard is per network, so switching no longer skips the new fetch. - Blocks that fail to load are listed as unavailable rows instead of gaps, and retried on the next refresh. - The navbar indicator shares one code path for UTXO chains and maps poll intervals by network type. - Shared ZcashKindBadge, ZcashOutputValue and ZcashSkeleton cells, typed label keys (labels.ts) and useZcashNetworkFromPath; skeleton sizes move from inline styles to CSS classes. - Relative times use the pluralized block:time keys (useTimeAgo), so useZcashTimeAgo and the zcash:common keys are gone. - Percentages follow the viewer's locale; count keys get plural forms. - Remove the unused loadingBlocks and lastUpdated fields. --- .../shared/mocked/zcash-dashboard.spec.ts | 46 +++++- .../navbar/NetworkBlockIndicator.tsx | 47 +++--- .../pages/zcash/ZcashBlocksTable.tsx | 104 ++++++++----- src/components/pages/zcash/ZcashCells.tsx | 48 ++++++ .../pages/zcash/ZcashDashboardStats.tsx | 40 +++-- .../pages/zcash/ZcashTransactionsTable.tsx | 72 +++------ .../pages/zcash/ZcashValuePools.tsx | 16 +- src/components/pages/zcash/index.tsx | 12 +- src/components/pages/zcash/labels.ts | 21 +++ src/hooks/useTimeAgo.ts | 32 ++++ src/hooks/useZcashDashboard.ts | 143 +++++++++--------- src/hooks/useZcashNetworkFromPath.ts | 38 +++++ src/locales/en/zcash.json | 17 +-- src/locales/es/zcash.json | 17 +-- src/locales/ja/zcash.json | 13 +- src/locales/pt-BR/zcash.json | 17 +-- src/locales/zh/zcash.json | 13 +- src/styles/components.css | 26 ++++ src/utils/zcashFormatters.ts | 10 ++ 19 files changed, 465 insertions(+), 267 deletions(-) create mode 100644 src/components/pages/zcash/ZcashCells.tsx create mode 100644 src/components/pages/zcash/labels.ts create mode 100644 src/hooks/useTimeAgo.ts create mode 100644 src/hooks/useZcashNetworkFromPath.ts diff --git a/e2e/tests/shared/mocked/zcash-dashboard.spec.ts b/e2e/tests/shared/mocked/zcash-dashboard.spec.ts index fdb80e5d..ee57acd8 100644 --- a/e2e/tests/shared/mocked/zcash-dashboard.spec.ts +++ b/e2e/tests/shared/mocked/zcash-dashboard.spec.ts @@ -1,5 +1,5 @@ import { expect, test } from "../../../fixtures/test"; -import { mockZcashRpc, ZCASH } from "../../../fixtures/zcash"; +import { mockZcashRpc, ZCASH, ZCASH_RPC_PATTERN } from "../../../fixtures/zcash"; /** * Hermetic Zcash network dashboard. RPC traffic to the built-in Tatum gateways is served @@ -48,4 +48,48 @@ test.describe("Zcash dashboard", () => { } expect(calls.map((call) => call.method)).not.toContain("getblockhash"); }); + + test("shares one getblockchaininfo call between the navbar height and the stats", async ({ + page, + }) => { + const calls = await mockZcashRpc(page); + + await page.goto(`/#/${ZCASH.networkSlug}`); + await expect(page.getByTestId("zcash-blocks-table")).toContainText("#3,483,396"); + await expect(page.locator(".network-block-number")).toHaveText("#3,483,400"); + + const count = (method: string) => calls.filter((call) => call.method === method).length; + expect(count("getblockchaininfo")).toBe(1); + expect(count("getblockcount")).toBe(0); + // The tip with its transactions, then one summary per earlier block + expect(count("getblock")).toBe(5); + }); + + test("shows a block that couldn't be loaded instead of leaving a gap", async ({ page }) => { + await mockZcashRpc(page); + const failingHeight = String(ZCASH.tipHeight - 2); + await page.route(ZCASH_RPC_PATTERN, async (route) => { + const body = JSON.parse(route.request().postData() ?? "{}"); + if (body.method === "getblock" && body.params?.[0] === failingHeight) { + await route.fulfill({ + contentType: "application/json", + body: JSON.stringify({ + jsonrpc: "2.0", + id: body.id, + error: { code: -8, message: "Block not found" }, + }), + }); + return; + } + await route.fallback(); + }); + + await page.goto(`/#/${ZCASH.networkSlug}`); + + const blocks = page.getByTestId("zcash-blocks-table"); + await expect(blocks).toContainText("#3,483,396"); + const unavailable = blocks.getByTestId("zcash-block-unavailable"); + await expect(unavailable).toHaveCount(1); + await expect(unavailable).toContainText("#3,483,398"); + }); }); diff --git a/src/components/navbar/NetworkBlockIndicator.tsx b/src/components/navbar/NetworkBlockIndicator.tsx index d5894a18..4c12fc0d 100644 --- a/src/components/navbar/NetworkBlockIndicator.tsx +++ b/src/components/navbar/NetworkBlockIndicator.tsx @@ -7,8 +7,17 @@ import { RpcClient } from "@openscan/network-connectors"; import { useDataService } from "../../hooks/useDataService"; import { formatGasPrice } from "../../utils/formatUtils"; import { logger } from "../../utils/logger"; +import type { NetworkType } from "../../types"; import { resolveNetwork, getNetworkRpcKey } from "../../utils/networkResolver"; +// Zcash polls slowly: 75 second blocks served by rate-limited gateways +const POLL_INTERVAL_MS: Record = { + evm: 12_000, + solana: 12_000, + bitcoin: 60_000, + zcash: ZCASH_REFRESH_INTERVAL_MS, +}; + interface NetworkBlockIndicatorProps { className?: string; } @@ -45,26 +54,24 @@ export function NetworkBlockIndicator({ className }: NetworkBlockIndicatorProps) let isMounted = true; let intervalId: NodeJS.Timeout | null = null; + const controller = new AbortController(); const fetchData = async () => { const networkRpcKey = getNetworkRpcKey(network); try { - if (network.type === "bitcoin" && dataService?.isBitcoin()) { - // Fetch Bitcoin block height - const adapter = dataService.getBitcoinAdapter(); - const height = await adapter.getLatestBlockNumber(); - if (isMounted) { - setBlockNumber(height); - setGasPrice(null); // Bitcoin doesn't have gas - setIsLoading(false); - } - } else if (network.type === "zcash" && dataService?.isZcash()) { - // Fetch Zcash block height - const adapter = dataService.getZcashAdapter(); - const height = await adapter.getLatestBlockNumber(); + // UTXO chains (Bitcoin, Zcash) report a block height and have no gas + const getUtxoHeight = dataService?.isBitcoin() + ? () => dataService.getBitcoinAdapter().getLatestBlockNumber() + : dataService?.isZcash() + ? () => + dataService.getZcashAdapter().getLatestBlockNumber({ signal: controller.signal }) + : null; + + if (getUtxoHeight) { + const height = await getUtxoHeight(); if (isMounted) { setBlockNumber(height); - setGasPrice(null); // Zcash doesn't have gas + setGasPrice(null); setIsLoading(false); } } else if (network.type === "solana" && dataService?.isSolana()) { @@ -99,6 +106,7 @@ export function NetworkBlockIndicator({ className }: NetworkBlockIndicatorProps) } } } catch (error) { + if (controller.signal.aborted) return; logger.error("Failed to fetch block number:", error); if (isMounted) { setIsLoading(false); @@ -109,18 +117,11 @@ export function NetworkBlockIndicator({ className }: NetworkBlockIndicatorProps) setIsLoading(true); fetchData(); - // Poll every 12 seconds for EVM, 60 seconds for Bitcoin, and 90 seconds for Zcash - // (75 second blocks served by rate-limited gateways) - const pollInterval = - network.type === "zcash" - ? ZCASH_REFRESH_INTERVAL_MS - : network.type === "bitcoin" - ? 60000 - : 12000; - intervalId = setInterval(fetchData, pollInterval); + intervalId = setInterval(fetchData, POLL_INTERVAL_MS[network.type]); return () => { isMounted = false; + controller.abort(); if (intervalId) { clearInterval(intervalId); } diff --git a/src/components/pages/zcash/ZcashBlocksTable.tsx b/src/components/pages/zcash/ZcashBlocksTable.tsx index 7edc47b2..50fec7f5 100644 --- a/src/components/pages/zcash/ZcashBlocksTable.tsx +++ b/src/components/pages/zcash/ZcashBlocksTable.tsx @@ -2,19 +2,34 @@ import type React from "react"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; import { DASHBOARD_BLOCKS } from "../../../config/zcashConstants"; -import { useZcashTimeAgo } from "../../../hooks/useZcashTimeAgo"; +import { useTimeAgo } from "../../../hooks/useTimeAgo"; import type { ZcashBlock } from "../../../types"; import { truncateBlockHash } from "../../../utils/zcashFormatters"; +import { ZcashSkeleton } from "./ZcashCells"; interface ZcashBlocksTableProps { blocks: ZcashBlock[]; + /** Heights that couldn't be loaded (e.g. rate limited); retried on the next refresh */ + failedHeights: number[]; loading: boolean; networkId: string; } -const ZcashBlocksTable: React.FC = ({ blocks, loading, networkId }) => { +type Row = { height: number; block?: ZcashBlock }; + +const ZcashBlocksTable: React.FC = ({ + blocks, + failedHeights, + loading, + networkId, +}) => { const { t } = useTranslation("zcash"); - const timeAgo = useZcashTimeAgo(); + const timeAgo = useTimeAgo(); + + const rows: Row[] = [ + ...blocks.map((block) => ({ height: block.height, block })), + ...failedHeights.map((height) => ({ height })), + ].sort((a, b) => b.height - a.height); return (
= ({ blocks, loading, ne
- {loading && blocks.length === 0 ? ( + {loading && rows.length === 0 ? (
{Array.from({ length: DASHBOARD_BLOCKS }).map((_, i) => ( // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholder
- +
- +
- +
))}
- ) : blocks.length === 0 ? ( + ) : rows.length === 0 ? (
{t("blocks.noBlocks")}
) : (
- {blocks.map((block) => ( -
-
- - #{block.height.toLocaleString()} - - {timeAgo(block.time)} -
-
- - {t("blocks.txCount", { count: block.nTx })} - + {rows.map(({ height, block }) => + block ? ( +
+
+ + #{block.height.toLocaleString()} + + {timeAgo(block.time)} +
+
+ + {t("blocks.txCount", { count: block.nTx })} + +
+
+ + {truncateBlockHash(block.hash)} + +
-
- - {truncateBlockHash(block.hash)} - + ) : ( +
+
+ + #{height.toLocaleString()} + +
+
+ {t("blocks.unavailable")} +
-
- ))} + ), + )}
)}
diff --git a/src/components/pages/zcash/ZcashCells.tsx b/src/components/pages/zcash/ZcashCells.tsx new file mode 100644 index 00000000..546a2789 --- /dev/null +++ b/src/components/pages/zcash/ZcashCells.tsx @@ -0,0 +1,48 @@ +import type React from "react"; +import { useTranslation } from "react-i18next"; +import type { ZcashTransaction, ZcashTxKind } from "../../../types"; +import { formatZEC } from "../../../utils/zcashFormatters"; +import { getTransparentOutputZat } from "../../../utils/zcashUtils"; +import { TX_KIND_LABEL_KEYS } from "./labels"; + +type SkeletonWidth = 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"; +} + +/** + * Loading placeholder sized by CSS classes (see .zec-skeleton in components.css) + */ +export const ZcashSkeleton: React.FC = ({ width, size = "text" }) => ( + +); + +/** + * How a transaction moves value between pools (coinbase, shielding, fully shielded…) + */ +export const ZcashKindBadge: React.FC<{ kind: ZcashTxKind }> = ({ kind }) => { + const { t } = useTranslation("zcash"); + return {t(TX_KIND_LABEL_KEYS[kind])}; +}; + +interface ZcashOutputValueProps { + transaction: ZcashTransaction; + currency: string; +} + +/** + * Transparent output total, or a "shielded" note when no value is publicly visible + */ +export const ZcashOutputValue: React.FC = ({ transaction, currency }) => { + const { t } = useTranslation("zcash"); + const transparentOutputZat = getTransparentOutputZat(transaction); + + return transparentOutputZat > 0 ? ( + {formatZEC(transparentOutputZat, currency)} + ) : ( + {t("transactions.shieldedValue")} + ); +}; diff --git a/src/components/pages/zcash/ZcashDashboardStats.tsx b/src/components/pages/zcash/ZcashDashboardStats.tsx index 0c8d3e72..870f373f 100644 --- a/src/components/pages/zcash/ZcashDashboardStats.tsx +++ b/src/components/pages/zcash/ZcashDashboardStats.tsx @@ -5,11 +5,13 @@ import type { ZcashNetworkStats } from "../../../types"; import { formatDifficulty, formatNumber, + formatPercent, formatSize, formatZECCompact, } from "../../../utils/zcashFormatters"; import { getShieldedSupplyPercent } from "../../../utils/zcashUtils"; import HelperTooltip from "../../common/HelperTooltip"; +import { ZcashSkeleton } from "./ZcashCells"; interface ZcashDashboardStatsProps { stats: ZcashNetworkStats | null; @@ -17,10 +19,6 @@ interface ZcashDashboardStatsProps { loading: boolean; } -const skeleton = (width: string) => ( - -); - const ZcashDashboardStats: React.FC = ({ stats, currency, loading }) => { const { t } = useTranslation("zcash"); const { t: tTooltips } = useTranslation("tooltips"); @@ -34,7 +32,13 @@ const ZcashDashboardStats: React.FC = ({ stats, curren
{t("dashboard.blockHeight")}
- {isLoading ? skeleton("100px") : stats ? `#${formatNumber(stats.blockHeight)}` : "—"} + {isLoading ? ( + + ) : stats ? ( + `#${formatNumber(stats.blockHeight)}` + ) : ( + "—" + )}
{stats ? t("dashboard.difficulty", { value: formatDifficulty(stats.difficulty) }) : ""} @@ -44,11 +48,13 @@ const ZcashDashboardStats: React.FC = ({ stats, curren
{t("dashboard.mempool")}
- {isLoading - ? skeleton("90px") - : stats - ? t("dashboard.mempoolTxs", { count: stats.mempoolSize }) - : "—"} + {isLoading ? ( + + ) : stats ? ( + t("dashboard.mempoolTxs", { count: stats.mempoolSize }) + ) : ( + "—" + )}
{stats ? formatSize(stats.mempoolBytes) : ""}
@@ -59,15 +65,17 @@ const ZcashDashboardStats: React.FC = ({ stats, curren {showTooltips && }
- {isLoading - ? skeleton("140px") - : stats?.chainSupplyZat !== undefined - ? formatZECCompact(stats.chainSupplyZat, currency) - : "—"} + {isLoading ? ( + + ) : stats?.chainSupplyZat !== undefined ? ( + formatZECCompact(stats.chainSupplyZat, currency) + ) : ( + "—" + )}
{shieldedPercent !== null - ? t("dashboard.shieldedShare", { percent: shieldedPercent.toFixed(1) }) + ? t("dashboard.shieldedShare", { percent: formatPercent(shieldedPercent) }) : ""}
diff --git a/src/components/pages/zcash/ZcashTransactionsTable.tsx b/src/components/pages/zcash/ZcashTransactionsTable.tsx index 5f3517e0..674e8302 100644 --- a/src/components/pages/zcash/ZcashTransactionsTable.tsx +++ b/src/components/pages/zcash/ZcashTransactionsTable.tsx @@ -1,18 +1,10 @@ import type React from "react"; import { useTranslation } from "react-i18next"; import { Link } from "react-router-dom"; -import type { ZcashTransaction, ZcashTxKind } from "../../../types"; -import { formatZEC, truncateHash } from "../../../utils/zcashFormatters"; -import { classifyTransaction, getTransparentOutputZat } from "../../../utils/zcashUtils"; - -const KIND_LABEL_KEYS = { - coinbase: "transactions.kinds.coinbase", - transparent: "transactions.kinds.transparent", - shielding: "transactions.kinds.shielding", - deshielding: "transactions.kinds.deshielding", - shielded: "transactions.kinds.shielded", - mixed: "transactions.kinds.mixed", -} as const satisfies Record; +import type { ZcashTransaction } from "../../../types"; +import { truncateHash } from "../../../utils/zcashFormatters"; +import { classifyTransaction } from "../../../utils/zcashUtils"; +import { ZcashKindBadge, ZcashOutputValue, ZcashSkeleton } from "./ZcashCells"; interface ZcashTransactionsTableProps { transactions: ZcashTransaction[]; @@ -50,22 +42,13 @@ const ZcashTransactionsTable: React.FC = ({ // biome-ignore lint/suspicious/noArrayIndexKey: skeleton placeholder
- +
- +
- +
))} @@ -74,34 +57,21 @@ const ZcashTransactionsTable: React.FC = ({
{t("transactions.noTransactions")}
) : (
- {transactions.map((tx) => { - const kind = classifyTransaction(tx); - const transparentOutputZat = getTransparentOutputZat(tx); - - return ( -
-
- - {truncateHash(tx.txid, "medium")} - -
-
- - {t(KIND_LABEL_KEYS[kind])} - -
-
- {transparentOutputZat > 0 ? ( - - {formatZEC(transparentOutputZat, currency)} - - ) : ( - {t("transactions.shieldedValue")} - )} -
+ {transactions.map((tx) => ( +
+
+ + {truncateHash(tx.txid, "medium")} + +
+
+
- ); - })} +
+ +
+
+ ))}
)}
diff --git a/src/components/pages/zcash/ZcashValuePools.tsx b/src/components/pages/zcash/ZcashValuePools.tsx index 55b7cab7..65f6bd92 100644 --- a/src/components/pages/zcash/ZcashValuePools.tsx +++ b/src/components/pages/zcash/ZcashValuePools.tsx @@ -2,17 +2,9 @@ import type React from "react"; import { useTranslation } from "react-i18next"; import { useSettings } from "../../../context/SettingsContext"; import type { ZcashNetworkStats, ZcashValuePoolId } from "../../../types"; -import { formatZECCompact } from "../../../utils/zcashFormatters"; +import { formatPercent, formatZECCompact } from "../../../utils/zcashFormatters"; import HelperTooltip from "../../common/HelperTooltip"; - -const POOL_LABEL_KEYS = { - transparent: "valuePools.pools.transparent", - sprout: "valuePools.pools.sprout", - sapling: "valuePools.pools.sapling", - orchard: "valuePools.pools.orchard", - lockbox: "valuePools.pools.lockbox", - ironwood: "valuePools.pools.ironwood", -} as const satisfies Record; +import { VALUE_POOL_LABEL_KEYS } from "./labels"; const POOL_TOOLTIP_KEYS = { transparent: "zcash.pools.transparent", @@ -62,10 +54,10 @@ const ZcashValuePools: React.FC = ({ stats, currency }) => {pools.map((pool) => (
  • - {t(POOL_LABEL_KEYS[pool.id])} + {t(VALUE_POOL_LABEL_KEYS[pool.id])} {showTooltips && } {formatZECCompact(pool.valueZat, currency)} - {sharePercent(pool.valueZat).toFixed(1)}% + {formatPercent(sharePercent(pool.valueZat))}
  • ))} diff --git a/src/components/pages/zcash/index.tsx b/src/components/pages/zcash/index.tsx index 263420f3..0ccafabe 100644 --- a/src/components/pages/zcash/index.tsx +++ b/src/components/pages/zcash/index.tsx @@ -1,10 +1,8 @@ import { useTranslation } from "react-i18next"; -import { useLocation } from "react-router-dom"; -import { getAllNetworks } from "../../../config/networks"; import { useZcashDashboard } from "../../../hooks/useZcashDashboard"; +import { useZcashNetworkFromPath } from "../../../hooks/useZcashNetworkFromPath"; import { ZcashRpcError } from "../../../services/adapters/ZcashAdapter"; import type { NetworkConfig } from "../../../types"; -import { resolveNetwork } from "../../../utils/networkResolver"; import SearchBox from "../../common/SearchBox"; import ZcashBlocksTable from "./ZcashBlocksTable"; import ZcashDashboardStats from "./ZcashDashboardStats"; @@ -24,11 +22,8 @@ const DEFAULT_ZCASH_NETWORK: NetworkConfig = { export default function ZcashNetwork() { const { t } = useTranslation("zcash"); - const location = useLocation(); - - // Extract network slug from path (e.g., "/tzec" → "tzec", "/zec" → "zec") - const pathSlug = location.pathname.split("/")[1] || "zec"; - const network = resolveNetwork(pathSlug, getAllNetworks()) || DEFAULT_ZCASH_NETWORK; + const { slug: pathSlug, network: pathNetwork } = useZcashNetworkFromPath(); + const network = pathNetwork ?? DEFAULT_ZCASH_NETWORK; const dashboard = useZcashDashboard(network); const networkName = network.name.toUpperCase(); @@ -68,6 +63,7 @@ export default function ZcashNetwork() {
    diff --git a/src/components/pages/zcash/labels.ts b/src/components/pages/zcash/labels.ts new file mode 100644 index 00000000..4fbcb1bf --- /dev/null +++ b/src/components/pages/zcash/labels.ts @@ -0,0 +1,21 @@ +import type { ZcashTxKind, ZcashValuePoolId } from "../../../types"; + +// i18n keys in the zcash namespace, keyed by domain value so lookups stay type-checked + +export const VALUE_POOL_LABEL_KEYS = { + transparent: "valuePools.pools.transparent", + sprout: "valuePools.pools.sprout", + sapling: "valuePools.pools.sapling", + orchard: "valuePools.pools.orchard", + lockbox: "valuePools.pools.lockbox", + ironwood: "valuePools.pools.ironwood", +} as const satisfies Record; + +export const TX_KIND_LABEL_KEYS = { + coinbase: "transactions.kinds.coinbase", + transparent: "transactions.kinds.transparent", + shielding: "transactions.kinds.shielding", + deshielding: "transactions.kinds.deshielding", + shielded: "transactions.kinds.shielded", + mixed: "transactions.kinds.mixed", +} as const satisfies Record; diff --git a/src/hooks/useTimeAgo.ts b/src/hooks/useTimeAgo.ts new file mode 100644 index 00000000..c3abe72b --- /dev/null +++ b/src/hooks/useTimeAgo.ts @@ -0,0 +1,32 @@ +import { useCallback } from "react"; +import { useTranslation } from "react-i18next"; + +const UNITS = [ + { key: "day", seconds: 60 * 60 * 24 }, + { key: "hour", seconds: 60 * 60 }, + { key: "minute", seconds: 60 }, +] as const; + +/** + * Localized relative time ("5 minutes ago") from a Unix timestamp in seconds, using the + * pluralized `block:time.*` keys + */ +export function useTimeAgo(): (timestamp: number) => string { + const { t } = useTranslation("block"); + + return useCallback( + (timestamp: number) => { + const seconds = Math.max(0, Math.floor(Date.now() / 1000 - timestamp)); + if (seconds < 5) return t("time.justNow"); + + for (const unit of UNITS) { + if (seconds >= unit.seconds) { + const count = Math.floor(seconds / unit.seconds); + return t("time.ago", { count, unit: t(`time.${unit.key}`, { count }) }); + } + } + return t("time.ago", { count: seconds, unit: t("time.second", { count: seconds }) }); + }, + [t], + ); +} diff --git a/src/hooks/useZcashDashboard.ts b/src/hooks/useZcashDashboard.ts index 8e6c49cf..92f5e27a 100644 --- a/src/hooks/useZcashDashboard.ts +++ b/src/hooks/useZcashDashboard.ts @@ -2,12 +2,13 @@ * Hook for fetching Zcash network dashboard data with auto-refresh * * Hosted Zcash gateways allow only a few requests per minute, so data loads in two stages: - * network stats and the tip block (3 calls) render first, then summaries for the previous - * blocks load one at a time. Summaries are cached across refreshes, so a refresh usually - * only fetches the stats, the new tip and any block mined since. + * network stats and the tip block (3 calls, the stats call shared with the navbar) render + * first, then summaries for the previous blocks load one at a time. Summaries are cached + * across refreshes, so a refresh usually only fetches the stats, the new tip and any block + * mined since; heights that failed are retried on the next refresh. */ -import { useCallback, useEffect, useRef, useState } from "react"; +import { useEffect, useState } from "react"; import { DASHBOARD_BLOCKS, DASHBOARD_TXS, REFRESH_INTERVAL_MS } from "../config/zcashConstants"; import type { NetworkConfig, ZcashBlock, ZcashNetworkStats, ZcashTransaction } from "../types"; import { useDataService } from "./useDataService"; @@ -15,99 +16,99 @@ import { useDataService } from "./useDataService"; export interface ZcashDashboardData { stats: ZcashNetworkStats | null; latestBlocks: ZcashBlock[]; + /** Recent heights whose summary couldn't be loaded */ + failedHeights: number[]; latestTransactions: ZcashTransaction[]; loading: boolean; - loadingBlocks: boolean; error: Error | null; - lastUpdated: number | null; } const initialState: ZcashDashboardData = { stats: null, latestBlocks: [], + failedHeights: [], latestTransactions: [], loading: true, - loadingBlocks: true, error: null, - lastUpdated: null, }; export function useZcashDashboard(network: NetworkConfig): ZcashDashboardData { const dataService = useDataService(network); const [data, setData] = useState(initialState); - const isFetchingRef = useRef(false); - const blockCacheRef = useRef(new Map()); - const fetchDashboardData = useCallback(async () => { - if (!dataService || !dataService.isZcash() || isFetchingRef.current) { - return; - } + useEffect(() => { + setData(initialState); + if (!dataService?.isZcash()) return; - isFetchingRef.current = true; - const cache = blockCacheRef.current; + // Everything below belongs to this network: switching networks aborts it, so a slow + // (rate-limited) response for the previous network can't land on this one + const controller = new AbortController(); + const { signal } = controller; + const adapter = dataService.getZcashAdapter(); + const cache = new Map(); + let inFlight = false; - try { - const adapter = dataService.getZcashAdapter(); + const refresh = async () => { + if (inFlight) return; + inFlight = true; - // Stage 1: stats and value pools, then the tip block with its transactions - const { data: stats } = await adapter.getNetworkStats(); - const { data: tip } = await adapter.getBlock(stats.blockHeight); - cache.set(tip.block.height, tip.block); + try { + // Stage 1: stats and value pools, then the tip block with its transactions + const { data: stats } = await adapter.getNetworkStats({ signal }); + const { data: tip } = await adapter.getBlock(stats.blockHeight, { signal }); + if (signal.aborted) return; + cache.set(tip.block.height, tip.block); - const heights = Array.from( - { length: DASHBOARD_BLOCKS }, - (_, i) => tip.block.height - i, - ).filter((height) => height >= 0); - const collectBlocks = () => - heights.flatMap((height) => { - const block = cache.get(height); - return block ? [block] : []; - }); + const heights = Array.from( + { length: DASHBOARD_BLOCKS }, + (_, i) => tip.block.height - i, + ).filter((height) => height >= 0); + const collectBlocks = () => + heights.flatMap((height) => { + const block = cache.get(height); + return block ? [block] : []; + }); - setData((prev) => ({ - ...prev, - stats, - latestBlocks: collectBlocks(), - latestTransactions: tip.transactions.slice(0, DASHBOARD_TXS), - loading: false, - error: null, - lastUpdated: Date.now(), - })); + setData((prev) => ({ + ...prev, + stats, + latestBlocks: collectBlocks(), + latestTransactions: tip.transactions.slice(0, DASHBOARD_TXS), + loading: false, + error: null, + })); - // Stage 2: summaries only for blocks not fetched by an earlier refresh - const missing = heights.filter((height) => !cache.has(height)); - for (const block of await adapter.getBlockSummaries(missing)) { - cache.set(block.height, block); - } - for (const height of cache.keys()) { - if (!heights.includes(height)) cache.delete(height); + // Stage 2: summaries only for blocks not fetched by an earlier refresh + const missing = heights.filter((height) => !cache.has(height)); + const { blocks, failedHeights } = await adapter.getBlockSummaries(missing, { signal }); + if (signal.aborted) return; + for (const block of blocks) { + cache.set(block.height, block); + } + for (const height of cache.keys()) { + if (!heights.includes(height)) cache.delete(height); + } + + setData((prev) => ({ ...prev, latestBlocks: collectBlocks(), failedHeights })); + } catch (err) { + if (signal.aborted) return; + setData((prev) => ({ + ...prev, + loading: false, + error: err instanceof Error ? err : new Error(String(err)), + })); + } finally { + inFlight = false; } + }; - setData((prev) => ({ ...prev, latestBlocks: collectBlocks(), loadingBlocks: false })); - } catch (err) { - setData((prev) => ({ - ...prev, - loading: false, - loadingBlocks: false, - error: err instanceof Error ? err : new Error(String(err)), - })); - } finally { - isFetchingRef.current = false; - } + refresh(); + const intervalId = setInterval(refresh, REFRESH_INTERVAL_MS); + return () => { + controller.abort(); + clearInterval(intervalId); + }; }, [dataService]); - // Initial fetch - useEffect(() => { - setData(initialState); - blockCacheRef.current.clear(); - fetchDashboardData(); - }, [fetchDashboardData]); - - // Set up polling interval - useEffect(() => { - const intervalId = setInterval(fetchDashboardData, REFRESH_INTERVAL_MS); - return () => clearInterval(intervalId); - }, [fetchDashboardData]); - return data; } diff --git a/src/hooks/useZcashNetworkFromPath.ts b/src/hooks/useZcashNetworkFromPath.ts new file mode 100644 index 00000000..08321bc3 --- /dev/null +++ b/src/hooks/useZcashNetworkFromPath.ts @@ -0,0 +1,38 @@ +import { useMemo } from "react"; +import { useLocation } from "react-router-dom"; +import { getNetworkBySlug } from "../config/networks"; +import type { NetworkConfig } from "../types"; + +export interface ZcashPathNetwork { + /** Route slug, e.g. "zec" or "tzec" (also the prefix of every Zcash route) */ + slug: string; + network: NetworkConfig | undefined; + /** Full network name, e.g. "Zcash Mainnet" */ + name: string; + /** Short label for headings, e.g. "Zcash" */ + label: string; + /** Ticker for amounts (testnet uses TAZ) */ + currency: string; + /** Network ID used as the cache key prefix */ + cacheNetworkId: string; +} + +/** + * The Zcash network a page belongs to, from the first segment of the route + */ +export function useZcashNetworkFromPath(): ZcashPathNetwork { + const { pathname } = useLocation(); + const slug = pathname.split("/")[1] || "zec"; + + return useMemo(() => { + const network = getNetworkBySlug(slug); + return { + slug, + network, + name: network?.name ?? slug, + label: network?.shortName || slug.toUpperCase(), + currency: network?.currency ?? "ZEC", + cacheNetworkId: network?.networkId ?? slug, + }; + }, [slug]); +} diff --git a/src/locales/en/zcash.json b/src/locales/en/zcash.json index 78e67405..24e194b4 100644 --- a/src/locales/en/zcash.json +++ b/src/locales/en/zcash.json @@ -3,9 +3,10 @@ "blockHeight": "Block Height", "difficulty": "Difficulty: {{value}}", "mempool": "Mempool", - "mempoolTxs": "{{count}} txs", + "mempoolTxs": "{{count}} tx", + "mempoolTxs_other": "{{count}} txs", "chainSupply": "Chain Supply", - "shieldedShare": "{{percent}}% shielded", + "shieldedShare": "{{percent}} shielded", "loadError": "Couldn't load data from the RPC endpoint: {{message}}", "rateLimited": "The RPC endpoint is rate limiting requests. Data refreshes automatically." }, @@ -24,8 +25,10 @@ "blocks": { "title": "Latest Blocks", "viewAll": "View all", - "txCount": "{{count}} txns", - "noBlocks": "No blocks found" + "txCount": "{{count}} txn", + "txCount_other": "{{count}} txns", + "noBlocks": "No blocks found", + "unavailable": "Couldn't load this block. It will be retried on the next refresh." }, "transactions": { "title": "Latest Transactions", @@ -40,11 +43,5 @@ "shielded": "Fully shielded", "mixed": "Mixed" } - }, - "common": { - "secondsAgo": "{{count}}s ago", - "minutesAgo": "{{count}}m ago", - "hoursAgo": "{{count}}h ago", - "daysAgo": "{{count}}d ago" } } diff --git a/src/locales/es/zcash.json b/src/locales/es/zcash.json index 6f1311b1..da27380e 100644 --- a/src/locales/es/zcash.json +++ b/src/locales/es/zcash.json @@ -3,9 +3,10 @@ "blockHeight": "Altura de bloque", "difficulty": "Dificultad: {{value}}", "mempool": "Mempool", - "mempoolTxs": "{{count}} txs", + "mempoolTxs": "{{count}} tx", + "mempoolTxs_other": "{{count}} txs", "chainSupply": "Suministro total", - "shieldedShare": "{{percent}}% blindado", + "shieldedShare": "{{percent}} blindado", "loadError": "No se pudieron cargar datos del endpoint RPC: {{message}}", "rateLimited": "El endpoint RPC está limitando las solicitudes. Los datos se actualizan automáticamente." }, @@ -24,8 +25,10 @@ "blocks": { "title": "Últimos bloques", "viewAll": "Ver todos", - "txCount": "{{count}} txs", - "noBlocks": "No se encontraron bloques" + "txCount": "{{count}} tx", + "txCount_other": "{{count}} txs", + "noBlocks": "No se encontraron bloques", + "unavailable": "No se pudo cargar este bloque. Se reintentará en la próxima actualización." }, "transactions": { "title": "Últimas transacciones", @@ -40,11 +43,5 @@ "shielded": "Totalmente blindada", "mixed": "Mixta" } - }, - "common": { - "secondsAgo": "hace {{count}} s", - "minutesAgo": "hace {{count}} min", - "hoursAgo": "hace {{count}} h", - "daysAgo": "hace {{count}} d" } } diff --git a/src/locales/ja/zcash.json b/src/locales/ja/zcash.json index 08b2d900..e9b18d88 100644 --- a/src/locales/ja/zcash.json +++ b/src/locales/ja/zcash.json @@ -4,8 +4,9 @@ "difficulty": "難易度: {{value}}", "mempool": "メンプール", "mempoolTxs": "{{count}} 件", + "mempoolTxs_other": "{{count}} 件", "chainSupply": "総供給量", - "shieldedShare": "{{percent}}% シールド", + "shieldedShare": "{{percent}} シールド", "loadError": "RPCエンドポイントからデータを読み込めませんでした: {{message}}", "rateLimited": "RPCエンドポイントがリクエストを制限しています。データは自動的に更新されます。" }, @@ -25,7 +26,9 @@ "title": "最新ブロック", "viewAll": "すべて表示", "txCount": "{{count}} 件", - "noBlocks": "ブロックが見つかりません" + "txCount_other": "{{count}} 件", + "noBlocks": "ブロックが見つかりません", + "unavailable": "このブロックを読み込めませんでした。次回の更新で再試行します。" }, "transactions": { "title": "最新トランザクション", @@ -40,11 +43,5 @@ "shielded": "完全シールド", "mixed": "混合" } - }, - "common": { - "secondsAgo": "{{count}}秒前", - "minutesAgo": "{{count}}分前", - "hoursAgo": "{{count}}時間前", - "daysAgo": "{{count}}日前" } } diff --git a/src/locales/pt-BR/zcash.json b/src/locales/pt-BR/zcash.json index e0505505..f89d893c 100644 --- a/src/locales/pt-BR/zcash.json +++ b/src/locales/pt-BR/zcash.json @@ -3,9 +3,10 @@ "blockHeight": "Altura do bloco", "difficulty": "Dificuldade: {{value}}", "mempool": "Mempool", - "mempoolTxs": "{{count}} txs", + "mempoolTxs": "{{count}} tx", + "mempoolTxs_other": "{{count}} txs", "chainSupply": "Oferta total", - "shieldedShare": "{{percent}}% blindado", + "shieldedShare": "{{percent}} blindado", "loadError": "Não foi possível carregar dados do endpoint RPC: {{message}}", "rateLimited": "O endpoint RPC está limitando as requisições. Os dados são atualizados automaticamente." }, @@ -24,8 +25,10 @@ "blocks": { "title": "Últimos blocos", "viewAll": "Ver todos", - "txCount": "{{count}} txs", - "noBlocks": "Nenhum bloco encontrado" + "txCount": "{{count}} tx", + "txCount_other": "{{count}} txs", + "noBlocks": "Nenhum bloco encontrado", + "unavailable": "Não foi possível carregar este bloco. Ele será tentado novamente na próxima atualização." }, "transactions": { "title": "Últimas transações", @@ -40,11 +43,5 @@ "shielded": "Totalmente blindada", "mixed": "Mista" } - }, - "common": { - "secondsAgo": "há {{count}} s", - "minutesAgo": "há {{count}} min", - "hoursAgo": "há {{count}} h", - "daysAgo": "há {{count}} d" } } diff --git a/src/locales/zh/zcash.json b/src/locales/zh/zcash.json index 3b64c42c..48cef60e 100644 --- a/src/locales/zh/zcash.json +++ b/src/locales/zh/zcash.json @@ -4,8 +4,9 @@ "difficulty": "难度: {{value}}", "mempool": "内存池", "mempoolTxs": "{{count}} 笔交易", + "mempoolTxs_other": "{{count}} 笔交易", "chainSupply": "总供应量", - "shieldedShare": "{{percent}}% 已屏蔽", + "shieldedShare": "{{percent}} 已屏蔽", "loadError": "无法从 RPC 端点加载数据: {{message}}", "rateLimited": "RPC 端点正在限制请求。数据会自动刷新。" }, @@ -25,7 +26,9 @@ "title": "最新区块", "viewAll": "查看全部", "txCount": "{{count}} 笔交易", - "noBlocks": "未找到区块" + "txCount_other": "{{count}} 笔交易", + "noBlocks": "未找到区块", + "unavailable": "无法加载此区块,将在下次刷新时重试。" }, "transactions": { "title": "最新交易", @@ -40,11 +43,5 @@ "shielded": "完全屏蔽", "mixed": "混合" } - }, - "common": { - "secondsAgo": "{{count}}秒前", - "minutesAgo": "{{count}}分钟前", - "hoursAgo": "{{count}}小时前", - "daysAgo": "{{count}}天前" } } diff --git a/src/styles/components.css b/src/styles/components.css index b7e5d072..04522cd6 100644 --- a/src/styles/components.css +++ b/src/styles/components.css @@ -6353,6 +6353,32 @@ button.tx-section-header-toggle { justify-content: center; } +/* Zcash loading placeholders, sized like the text they stand in for */ +.zec-skeleton { + display: inline-block; +} + +.zec-skeleton-small { + height: 12px; +} + +.zec-skeleton-text { + height: 14px; +} + +.zec-skeleton-stat { + height: 20px; +} + +.zec-skeleton-w50 { width: 50px; } +.zec-skeleton-w60 { width: 60px; } +.zec-skeleton-w70 { width: 70px; } +.zec-skeleton-w80 { width: 80px; } +.zec-skeleton-w90 { width: 90px; } +.zec-skeleton-w100 { width: 100px; } +.zec-skeleton-w120 { width: 120px; } +.zec-skeleton-w140 { width: 140px; } + /* Zcash value pools */ .zec-value-pools { background: var(--bg-secondary); diff --git a/src/utils/zcashFormatters.ts b/src/utils/zcashFormatters.ts index b4c5b16c..eae681ae 100644 --- a/src/utils/zcashFormatters.ts +++ b/src/utils/zcashFormatters.ts @@ -32,3 +32,13 @@ export function formatZECCompact(valueZat: number, currency = "ZEC"): string { return `${value.toLocaleString(undefined, { maximumFractionDigits })} ${currency}`; } +/** + * Format a percentage (0–100) with one decimal, using the viewer's locale like the amounts + */ +export function formatPercent(percent: number): string { + return (percent / 100).toLocaleString(undefined, { + style: "percent", + minimumFractionDigits: 1, + maximumFractionDigits: 1, + }); +} From dbae080d9748f820d265ff84a48324925789384a Mon Sep 17 00:00:00 2001 From: Mati OS Date: Fri, 20 Nov 2026 20:34:02 -0300 Subject: [PATCH 7/7] fix(rpc): skip zcash gateways in the first-load latency sync Auto-sync probes every network with two or more endpoints 1.5s after the first load. With Zcash support in the latency test, that sent getblockcount to both Tatum hosts of zec and tzec on every fresh load: two of the ~5 requests per minute the mainnet gateways share per IP, spent before the dashboard's own calls. Zcash endpoints keep their order instead; the manual latency test on the RPC page still covers them. --- src/utils/rpcAutoSync.test.ts | 48 +++++++++++++++++++++++++++++++++++ src/utils/rpcAutoSync.ts | 4 ++- 2 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 src/utils/rpcAutoSync.test.ts diff --git a/src/utils/rpcAutoSync.test.ts b/src/utils/rpcAutoSync.test.ts new file mode 100644 index 00000000..2477abe6 --- /dev/null +++ b/src/utils/rpcAutoSync.test.ts @@ -0,0 +1,48 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { NetworkConfig } from "../types"; +import { autoSyncRpcs } from "./rpcAutoSync"; + +const testRpcEndpoint = vi.hoisted(() => vi.fn()); +vi.mock("../components/pages/rpcs/useRpcLatencyTest", () => ({ testRpcEndpoint })); +vi.mock("./rpcStorage", () => ({ getMetadataEndpointMap: () => new Map() })); + +const network = (type: NetworkConfig["type"], networkId: string): NetworkConfig => ({ + type, + networkId, + name: networkId, + shortName: networkId, + currency: "X", +}); + +const ZCASH = network("zcash", "bip122:00040fe8ec8471911baa1db1266ea15d"); +const BITCOIN = network("bitcoin", "bip122:000000000019d6689c085ae165831e93"); + +afterEach(() => { + testRpcEndpoint.mockReset(); +}); + +describe("autoSyncRpcs", () => { + it("sorts endpoints by latency", async () => { + testRpcEndpoint.mockImplementation(async (url: string) => ({ + url, + status: "online", + latency: url.includes("slow") ? 500 : 50, + })); + + const sorted = await autoSyncRpcs( + { [BITCOIN.networkId]: ["https://slow.test", "https://fast.test"] }, + [BITCOIN], + ); + + expect(sorted[BITCOIN.networkId]).toEqual(["https://fast.test", "https://slow.test"]); + }); + + it("leaves rate-limited Zcash gateways alone instead of probing them", async () => { + const zcashUrls = ["https://zcash-a.test", "https://zcash-b.test"]; + + const sorted = await autoSyncRpcs({ [ZCASH.networkId]: zcashUrls }, [ZCASH]); + + expect(testRpcEndpoint).not.toHaveBeenCalled(); + expect(sorted[ZCASH.networkId]).toEqual(zcashUrls); + }); +}); diff --git a/src/utils/rpcAutoSync.ts b/src/utils/rpcAutoSync.ts index 0ad925ba..ad81644c 100644 --- a/src/utils/rpcAutoSync.ts +++ b/src/utils/rpcAutoSync.ts @@ -55,7 +55,9 @@ export async function autoSyncRpcs( .filter(([, urls]) => urls.length >= 2) .map(async ([networkId, urls]) => { const network = networks.find((n) => n.networkId === networkId); - if (!network) return; + // Zcash's built-in gateways share a ~5 requests/min per-IP limit: probing them on every + // first load would spend the budget its pages need, so they keep their order + if (!network || network.type === "zcash") return; const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 5_000); try {