From a59d43234570988c9da0b334faeb1062a556bb3f Mon Sep 17 00:00:00 2001 From: Randall Naar Date: Thu, 12 Nov 2026 09:47:14 -0500 Subject: [PATCH] Added usd display for bitcoin amounts. --- README.md | 4 + client/src/app.js | 44 ++- client/src/components/amount-with-usd.js | 9 + client/src/lib/network.js | 3 + client/src/views/addr.js | 36 ++- client/src/views/asset.js | 10 +- client/src/views/block.js | 1 + client/src/views/blocks.js | 1 + client/src/views/fee-market.js | 4 +- client/src/views/layout.js | 3 +- client/src/views/mempool.js | 4 +- client/src/views/overview.js | 11 +- .../src/views/pending-block-details-card.js | 7 +- client/src/views/transactions.js | 12 +- client/src/views/tx.js | 33 ++- client/src/views/util.js | 26 +- test/amount-with-usd.test.js | 109 ++++++++ test/block-details-card.test.js | 1 + test/fee-market.test.js | 1 + test/overview.test.js | 4 + test/recent-transactions.test.js | 262 ++++++++++++++++++ www/css/components/amount-with-usd.css | 17 ++ www/css/layout/addr.css | 40 +++ www/css/layout/mempool.css | 16 ++ www/css/layout/transactions.css | 23 ++ www/css/layout/tx.css | 44 +++ www/css/manifest.json | 5 + 27 files changed, 680 insertions(+), 50 deletions(-) create mode 100644 client/src/components/amount-with-usd.js create mode 100644 test/amount-with-usd.test.js create mode 100644 test/recent-transactions.test.js create mode 100644 www/css/components/amount-with-usd.css create mode 100644 www/css/layout/addr.css create mode 100644 www/css/layout/mempool.css create mode 100644 www/css/layout/transactions.css create mode 100644 www/css/layout/tx.css diff --git a/README.md b/README.md index f20cbdd8f..2fd4e00e9 100644 --- a/README.md +++ b/README.md @@ -74,6 +74,10 @@ Browser polling uses three shared cadence tiers defined in `client/src/const.js` - **Slow (10 minutes):** the Bitcoin market chart, the Liquid high-value-assets panel, and a block-list safety poll used to detect same-height reorganizations. +On Bitcoin and Liquid mainnet, the market chart also supplies the USD values +shown beside BTC amounts, so it polls on every page that shows them. Other +networks poll it only on the dashboard. + View-scoped polls run only while their view is active and the browser window is focused. Their first tick occurs after a full interval because route entry already requests the initial data. This avoids sending duplicate requests when diff --git a/client/src/app.js b/client/src/app.js index 4c4b1484e..a03c8468f 100644 --- a/client/src/app.js +++ b/client/src/app.js @@ -5,7 +5,8 @@ import {setAdapt} from '@cycle/run/lib/adapt'; import { getMempoolDepth, getConfEstimate, calcSegwitFeeGains } from './lib/fees' import { summarizeBlockTemplate } from './lib/block-template' import { getPriceFeedApiBase } from './lib/high-value-assets' -import { isBitcoinNetwork } from './lib/network' +import { getLatestBitcoinPrice } from './lib/market' +import { isBitcoinNetwork, isBitcoinOrLiquidMainnet } from './lib/network' import { normalizeSearchQuery } from './lib/search-query' import { debounceAutocompleteQueries, getAutocompletePlan } from './lib/search-autocomplete' import getPrivacyAnalysis from './lib/privacy-analysis' @@ -173,6 +174,21 @@ export const parseTipHeight = text => { const isUnconfirmedTx = tx => !!tx && !tx.status.confirmed +const isBitcoinUsdValuePage = pathname => + pathname == '/' || pathname == '/tx/recent' || pathname == '/mempool' + || /^\/(tx|block)\/[a-f0-9]{64}\/?$/i.test(pathname) + || /^\/address\/[^/]+\/?$/.test(pathname) + || (!!process.env.IS_ELEMENTS && /^\/asset\/[a-f0-9]{64}\/?$/i.test(pathname)) + +// Keep a trigger only when `ms` has passed since the last kept trigger. +const skipWhileFresh = (ms, now, trigger$) => + trigger$ + .scan(({ sentAt }) => { + const at = now() + return at - sentAt >= ms ? { sentAt: at, send: true } : { sentAt, send: false } + }, { sentAt: -Infinity }) + .filter(({ send }) => send) + export const subsequentTipHeights = tipHeight$ => tipHeight$.distinctUntilChanged().skip(1) @@ -263,6 +279,10 @@ export default function main( /// User actions , page$ = route() + , bitcoinUsdValuePage$ = page$ + .map(({ pathname }) => pathname.replace(/\/$/, '') || '/') + .map(pathname => isBitcoinOrLiquidMainnet && isBitcoinUsdValuePage(pathname) ? pathname : null) + .distinctUntilChanged() , goHome$ = route('/') , goAPILanding$= route('/explorer-api') , goBlocks$ = route('/blocks/recent').map(loc => ({ start_height: loc.query.start != null ? +loc.query.start : null })) @@ -619,6 +639,7 @@ export default function main( // Bitcoin price chart data , bitcoinMarketChart$ = reply('bitcoin-market-chart').startWith(null) + , bitcoinPrice$ = bitcoinMarketChart$.map(getLatestBitcoinPrice).distinctUntilChanged().shareReplay(1) // Transaction analysis , txAnalysis$ = tx$.filter(Boolean) @@ -731,7 +752,7 @@ export default function main( , dashboardEpochStartBlock$, dashboardPreviousDifficultyBlock$ , newBlockEntries$, newTxEntries$ , goBlock$, block$, blockStatus$, blockTxs$, nextBlockTxs$, prevBlockTxs$, openBlock$ - , mempool$, mempoolRecent$, feeEst$, bitcoinMarketChart$ + , mempool$, mempoolRecent$, feeEst$, bitcoinMarketChart$, bitcoinPrice$ , tx$, txBlock$, previousBlock$, txAnalysis$, openTx$ , goAddr$, addr$, addrTxs$, addrQR$ , assetMap$, assetList$, goAssetList$, goAsset$, asset$, assetTxs$, unblinded$ @@ -860,8 +881,20 @@ export default function main( ) .mapTo( { category: 'recent', method: 'GET', path: '/mempool/recent', bg: true }) - // the market chart contains hourly samples and uses the slow cadence - , pollViewing(pollIntervalsMs.slow, 'dashBoard', view$) + // One shared feed supplies the chart and all mainnet BTC/LBTC amounts. Its + // timer spans all price pages, and page entry reuses a price requested + // within the slow interval. Other networks keep dashboard-only fetching. + , (isBitcoinOrLiquidMainnet + ? skipWhileFresh( + pollIntervalsMs.slow, + () => pollingScheduler ? pollingScheduler.now() : Date.now(), + O.merge( + bitcoinUsdValuePage$.filter(Boolean), + pollActive(pollIntervalsMs.slow, bitcoinUsdValuePage$.map(page => page ? true : null)) + ) + ) + : O.merge(goHome$, pollViewing(pollIntervalsMs.slow, 'dashBoard', view$)) + ) .mapTo({ category: 'bitcoin-market-chart', method: 'GET', path: bitcoinMarketChartUrl, bg: true }) // Refresh the pending block template while the dashboard remains open. A new @@ -872,8 +905,7 @@ export default function main( , goHome$.flatMap(_ => [{ category: 'blocks', method: 'GET', path: '/blocks' } , { category: 'recent', method: 'GET', path: '/mempool/recent' } , { category: 'fee-est', method: 'GET', path: '/fee-estimates' } - , { category: 'mempool', method: 'GET', path: '/mempool' } - , { category: 'bitcoin-market-chart', method: 'GET', path: bitcoinMarketChartUrl, bg: true }]) + , { category: 'mempool', method: 'GET', path: '/mempool' }]) // fetch asset stats and USD prices only while viewing the Liquid dashboard , !showHighValueAssets ? O.empty() : diff --git a/client/src/components/amount-with-usd.js b/client/src/components/amount-with-usd.js new file mode 100644 index 000000000..ddfe56055 --- /dev/null +++ b/client/src/components/amount-with-usd.js @@ -0,0 +1,9 @@ +// An empty secondary line keeps its height so rows do not grow when a price arrives. +export const AmountWithUsd = ({ primary, secondary }) => ( + + {primary} + {secondary == null + ? + : {secondary}} + +); diff --git a/client/src/lib/network.js b/client/src/lib/network.js index 0691d9808..c5b995765 100644 --- a/client/src/lib/network.js +++ b/client/src/lib/network.js @@ -3,3 +3,6 @@ const activeNetwork = process.env.MENU_ACTIVE || ""; export const isBitcoinNetwork = activeNetwork .toLowerCase() .startsWith("bitcoin"); + +export const isBitcoinOrLiquidMainnet = ["bitcoin", "liquid"] + .includes(activeNetwork.toLowerCase()); diff --git a/client/src/views/addr.js b/client/src/views/addr.js index aa0513dbc..a24b4af28 100644 --- a/client/src/views/addr.js +++ b/client/src/views/addr.js @@ -1,12 +1,13 @@ import { last } from "../util"; import layout from "./layout"; import { txBox } from "./tx"; -import { formatSat, formatNumber } from "./util"; +import { formatSat, formatSatWithUsd, formatNumber } from "./util"; import { addrTxsPerPage as perPage, maxMempoolTxs } from "../const"; import loader from "../components/loading"; import { AddressHamburgerIcon, CopyIcon } from "../components/icons"; import { InfoStat } from "../components/info-stat"; import { Tooltip } from "../components/tooltip"; +import { isBitcoinOrLiquidMainnet } from "../lib/network"; const staticRoot = process.env.STATIC_ROOT || ""; @@ -113,6 +114,7 @@ export default ({ chain_stats.funded_txo_count, chain_stats.funded_txo_sum, t, + S, )} /> @@ -155,6 +158,8 @@ export default ({ mempool_stats.funded_txo_count, mempool_stats.funded_txo_sum, t, + S, + true, )} @@ -168,6 +173,8 @@ export default ({ mempool_stats.spent_txo_count, mempool_stats.spent_txo_sum, t, + S, + true, )} @@ -175,7 +182,7 @@ export default ({

{t`Total unspent`}

- {fmtTxos(total_utxo_count, total_utxo_sum, t)} + {fmtTxos(total_utxo_count, total_utxo_sum, t, S, true)}
@@ -225,13 +232,32 @@ export default ({ ); }; -const fmtTxos = (count, sum, t) => { +const fmtTxos = (count, sum, t, S, usdBelowOutputs = false) => { const outputs = count > 0 ? t`${formatNumber(count)} outputs` : t`No outputs`; if (!Number.isFinite(sum)) return outputs; + if (count <= 0) return outputs; - return count > 0 ? `${formatSat(sum)} (${outputs})` : outputs; + if (!isBitcoinOrLiquidMainnet) return `${formatSat(sum)} (${outputs})`; + + if (usdBelowOutputs) return ( + + {formatSatWithUsd(sum, { t, ...S }, ( + + {formatSat(sum)} + ({outputs}) + + ))} + + ); + + return ( + + {formatSatWithUsd(sum, { t, ...S })} + ({outputs}) + + ); }; const pagingNav = ( diff --git a/client/src/views/asset.js b/client/src/views/asset.js index 66bd8959f..a64355f5a 100644 --- a/client/src/views/asset.js +++ b/client/src/views/asset.js @@ -1,5 +1,5 @@ import { last } from '../util' -import { formatNumber, formatAssetAmount, formatSat } from './util' +import { formatNumber, formatAssetAmount, formatSatWithUsd } from './util' import layout from './layout' import { txBox } from './tx' import { maxMempoolTxs, assetTxsPerPage as perPage, nativeAssetName } from '../const' @@ -73,16 +73,16 @@ export default ({ t, asset, assetTxs, goAsset, openTx, spends, tipHeight, loadin : shortenValue(asset.asset_id) , stats = is_native_asset ? [ - { title: 'TOTAL SUPPLY', value: formatSat(circulating) }, + { title: 'TOTAL SUPPLY', value: formatSatWithUsd(circulating, { t, ...S }) }, { title: 'PEGGED IN', - value: formatSat(value(chain_stats.peg_in_amount) + value(mempool_stats.peg_in_amount)) + value: formatSatWithUsd(value(chain_stats.peg_in_amount) + value(mempool_stats.peg_in_amount), { t, ...S }) }, { title: 'PEGGED OUT', - value: formatSat(value(chain_stats.peg_out_amount) + value(mempool_stats.peg_out_amount)) + value: formatSatWithUsd(value(chain_stats.peg_out_amount) + value(mempool_stats.peg_out_amount), { t, ...S }) }, - { title: 'BURNED', value: formatSat(total_burned) }, + { title: 'BURNED', value: formatSatWithUsd(total_burned, { t, ...S }) }, { title: 'TRANSACTIONS', value: formatNumber(total_txs) } ] : [ diff --git a/client/src/views/block.js b/client/src/views/block.js index dda93a80c..9b700ea0c 100644 --- a/client/src/views/block.js +++ b/client/src/views/block.js @@ -87,6 +87,7 @@ export default ({ tipHeight, t, spends, + ...S, listingIndex: +goBlock.start_index + index + 1, listingTotal: b.tx_count, }, diff --git a/client/src/views/blocks.js b/client/src/views/blocks.js index 28afbbe1e..3c1b260ec 100644 --- a/client/src/views/blocks.js +++ b/client/src/views/blocks.js @@ -44,6 +44,7 @@ export const blks = (blocks, viewMore, { t, ...S }) => { {viewMore ? ( [ @@ -22,8 +21,7 @@ const getFeeMarketLevels = (t) => [ }, ]; -export const feeMarket = ({ feeEst, bitcoinMarketChart, t } = {}) => { - const bitcoinPrice = getLatestBitcoinPrice(bitcoinMarketChart); +export const feeMarket = ({ feeEst, bitcoinPrice, t } = {}) => { const unavailable = t`N/A`; return ( diff --git a/client/src/views/layout.js b/client/src/views/layout.js index 475fab332..9a62abe86 100644 --- a/client/src/views/layout.js +++ b/client/src/views/layout.js @@ -1,6 +1,7 @@ import navbar from './navbar' import footer from './footer' import subnav from './sub-navbar' +import { isBitcoinOrLiquidMainnet } from '../lib/network' export default (body, opt) => { const mainKey = opt.view || opt.activeTab || opt.page && opt.page.pathname || 'main' @@ -8,7 +9,7 @@ export default (body, opt) => { return
{ navbar(opt) } { subnav(opt.t, opt.isTouch, opt.activeTab, opt.page, opt.autocomplete) } -
+
{ body }
{ footer(opt) } diff --git a/client/src/views/mempool.js b/client/src/views/mempool.js index 0008c3704..fbcae35f3 100644 --- a/client/src/views/mempool.js +++ b/client/src/views/mempool.js @@ -1,5 +1,5 @@ import { getMempoolDepth, squashFeeHistogram, feerateCutoff } from '../lib/fees' -import { formatSat, formatVMB } from './util' +import { formatSatWithUsd, formatVMB } from './util' import layout from './layout' import search from './search' @@ -19,7 +19,7 @@ export default ({ t, mempool, feeEst, ...S }) => mempool && feeEst && layout(
{t`Total fees`}
-
{formatSat(mempool.total_fee)}
+
{formatSatWithUsd(mempool.total_fee, { t, ...S })}
{t`Total size`}
diff --git a/client/src/views/overview.js b/client/src/views/overview.js index 596ef0638..4324b0355 100644 --- a/client/src/views/overview.js +++ b/client/src/views/overview.js @@ -5,10 +5,7 @@ import { MempoolCongestion } from "../components/mempool-congestion"; import { ReferenceLineChart } from "../components/reference-line-chart"; import { estimateTypicalTransactionFeeUsd } from "../lib/fees"; import { isBitcoinNetwork } from "../lib/network"; -import { - getBitcoinPrices, - getLatestBitcoinPrice, -} from "../lib/market"; +import { getBitcoinPrices } from "../lib/market"; import { formatFeeRate, formatUsd } from "./util"; const staticRoot = process.env.STATIC_ROOT || ""; @@ -53,15 +50,15 @@ export const overview = ({ feeEst, mempool, bitcoinMarketChart, + bitcoinPrice, t, } = {}) => { const latestBlock = blocks && blocks[0]; const chartPrices = getChartPrices(bitcoinMarketChart); - const currentBitcoinPrice = getLatestBitcoinPrice(bitcoinMarketChart); const recommendedFeerate = feeEst && feeEst[feeEstimateTargets.average]; const recommendedFeeUsd = estimateTypicalTransactionFeeUsd( - currentBitcoinPrice, + bitcoinPrice, recommendedFeerate, ); return ( @@ -112,7 +109,7 @@ export const overview = ({ iconSrc={`${staticRoot}img/icons/Bitcoin-menu-logo.svg`} headerValue={ - {formatUsd(currentBitcoinPrice, t`N/A`)} + {formatUsd(bitcoinPrice, t`N/A`)} {getPercentDelta(chartPrices, t`N/A`)} } diff --git a/client/src/views/pending-block-details-card.js b/client/src/views/pending-block-details-card.js index 39bd3a6ab..ebc5f6324 100644 --- a/client/src/views/pending-block-details-card.js +++ b/client/src/views/pending-block-details-card.js @@ -25,8 +25,7 @@ import { formatTransactionDelta, formatWeight, } from "../lib/pending-block-details"; -import { getLatestBitcoinPrice } from "../lib/market"; -import { formatFeeRate, formatSat, formatUsd, formatVMB } from "./util"; +import { formatFeeRate, formatSat, formatSatWithUsd, formatUsd, formatVMB } from "./util"; // Fee estimates are inclusive upper bounds, while the grid expects inclusive // lower thresholds. Move just beyond a boundary so an equal rate stays in the @@ -353,6 +352,7 @@ const feeBucketPanel = ( const PendingBlockDetailsCard = ({ bitcoinMarketChart, + bitcoinPrice, block, blockTemplate, detailsOpen, @@ -377,7 +377,6 @@ const PendingBlockDetailsCard = ({ ? blockTemplate.transactions : null; const feeTierBoundaries = getFeeTierBoundaries(feeEst); - const bitcoinPrice = getLatestBitcoinPrice(bitcoinMarketChart); const weightPercentage = metrics && metrics.weightPercentage; const weightLimit = metrics && metrics.weightLimit; return ( @@ -438,7 +437,7 @@ const PendingBlockDetailsCard = ({ {blockStat( t`TOTAL FEE COLLECTED`, metrics && Number.isFinite(metrics.totalFees) - ? formatSat(metrics.totalFees) + ? formatSatWithUsd(metrics.totalFees, { bitcoinPrice, t }) : templateFallback, )}
diff --git a/client/src/views/transactions.js b/client/src/views/transactions.js index 6deee79b5..a90fccefa 100644 --- a/client/src/views/transactions.js +++ b/client/src/views/transactions.js @@ -1,8 +1,9 @@ -import { formatSat, formatNumber, truncateTxid } from "./util"; +import { formatSatWithUsd, formatNumber, truncateTxid } from "./util"; import loader from "../components/loading"; import { CopyIcon, TxArrowsIcon } from "../components/icons"; import { ConfidentialBadge } from "../components/status-badge"; import { feeRateClass } from "../lib/fees"; +import { isBitcoinOrLiquidMainnet } from "../lib/network"; const staticRoot = process.env.STATIC_ROOT || ""; @@ -13,7 +14,7 @@ export const transactions = (txs, viewMore, { t, ...S }) => ( ) : !txs.length ? (

{t`No recent transactions`}

) : ( -
+
@@ -55,8 +56,7 @@ export const transactions = (txs, viewMore, { t, ...S }) => (
{t`VALUE`}
- {txOverview.value != null ? - formatSat(txOverview.value) : } + {txOverview.value == null ? : formatSatWithUsd(txOverview.value, { t, ...S })}
@@ -65,7 +65,9 @@ export const transactions = (txs, viewMore, { t, ...S }) => (
{t`FEE`}
-
{`${feerate.toFixed(2)} sat/vB`}
+
+ {formatSatWithUsd(txOverview.fee, { t, ...S }, `${feerate.toFixed(2)} sat/vB`)} +
diff --git a/client/src/views/tx.js b/client/src/views/tx.js index 5d727d161..458883b57 100644 --- a/client/src/views/tx.js +++ b/client/src/views/tx.js @@ -4,7 +4,7 @@ import vinView from "./tx-vin"; import voutView from "./tx-vout"; import privacyAnalysisView from "./tx-privacy-analysis"; import segwitGainsView from "./tx-segwit-gains"; -import { formatSat, formatTime, formatVMB, formatNumber } from "./util"; +import { formatSat, formatSatWithUsd, formatTime, formatVMB, formatNumber } from "./util"; import { isAllUnconfidential, isAllNative, @@ -25,6 +25,7 @@ import { StatusBadge, StatusDot } from "../components/status-badge"; import { Tooltip } from "../components/tooltip"; import BlockDetailsCard from "../components/block-details-card"; import { targetBlockIntervalSeconds } from "../const"; +import { isBitcoinOrLiquidMainnet } from "../lib/network"; // Require behind env conditional so it gets removed by `envify` on non-elements builds const deduceBlinded = @@ -234,6 +235,7 @@ const txHeader = ( block, tipHeight, feeEst, + bitcoinPrice, t, txAnalysis: { feerate, @@ -341,18 +343,31 @@ const txHeader = (
)} -
+

TRANSACTION FEES

-
+
{feerate != null ? (
-

- {formatSat(tx.fee)} -

-

- {`(${feerate.toFixed(2)} sat/vB)`} -

+ {isBitcoinOrLiquidMainnet ? ( +

+ {formatSatWithUsd(tx.fee, { bitcoinPrice, t }, ( + + {formatSat(tx.fee)} + + {`(${feerate.toFixed(2)} sat/vB)`} + + + ))} +

+ ) : [ +

+ {formatSat(tx.fee)} +

, +

+ {`(${feerate.toFixed(2)} sat/vB)`} +

, + ]}
{overpaying > OVERPAYMENT_WARN ? (

})} USD` : fallback +// Without a price, leave the USD line blank instead of an N/A line per amount. +export const formatSatWithUsd = (sats, { bitcoinPrice, t } = {}, primary = formatSat(sats)) => { + if (!isBitcoinOrLiquidMainnet) return primary + + const satoshis = typeof sats == 'bigint' ? Number(sats) : sats + if (satoshis < 0) { + console.error('formatSatWithUsd received a negative amount', sats) + return + } + + const usd = Number.isFinite(satoshis) && Number.isFinite(bitcoinPrice) && bitcoinPrice >= 0 + ? (satoshis / satoshisPerBitcoin) * bitcoinPrice + : null + + return +} + export const formatAssetAmount = (value, precision=0, t) => {formatNumber(precision > 0 ? moveDec(value, -precision) : value, precision)} -export const formatOutAmount = (vout, { t, assetMap }, shortDisplay=false) => { +export const formatOutAmount = (vout, { t, assetMap, bitcoinPrice }, shortDisplay=false) => { if (vout.value == null) return if (isNativeOut(vout)) { - return + const primary = {formatNumber(sat2btc(vout.value), NATIVE_PRECISION)} { ' ' } {!vout.asset ? nativeAssetLabel : {nativeAssetLabel}} + return formatSatWithUsd(vout.value, { t, bitcoinPrice }, primary) } const [ domain, ticker, name, _precision ] = vout.asset && assetMap && assetMap[vout.asset] || [] diff --git a/test/amount-with-usd.test.js b/test/amount-with-usd.test.js new file mode 100644 index 000000000..0ded3403c --- /dev/null +++ b/test/amount-with-usd.test.js @@ -0,0 +1,109 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const render = require("snabbdom-to-html"); + +process.env.MENU_ACTIVE = "Bitcoin"; + +const { formatSatWithUsd, formatOutAmount } = require("../client/src/views/util"); +const { transactions } = require("../client/src/views/transactions"); +const t = require("../client/src/l10n").default.en; + +const bitcoinPrice = 100_000; +const tx = { txid: "a".repeat(64), value: 100_000, fee: 1_000, vsize: 500 }; +const state = { t, bitcoinPrice, bitcoinMarketChart: { prices: [[1, bitcoinPrice]] } }; + +test("keeps full BTC precision and converts satoshis to USD", () => { + const html = render(formatSatWithUsd(tx.value, state)); + assert.match(html, /0\.00100000 BTC/); + assert.match(html, /\$100\.00 USD/); + assert.match(render(formatSatWithUsd(BigInt(100_000), state)), /\$100\.00 USD/); + + const large = render(formatSatWithUsd(2_099_999_999_999_999, state)); + assert.match(large, /20,999,999\.99999999 BTC/); + assert.match(large, /\$2,100,000,000,000\.00 USD/); +}); + +test("handles zero, sub-cent, negative, and missing-price conversions", (ctx) => { + for (const [sats, expected] of [[0, "$0.00 USD"], [1, "$0.00 USD"]]) { + assert.ok(render(formatSatWithUsd(sats, state)).includes(expected)); + } + + const logError = ctx.mock.method(console, "error", () => {}); + for (const sats of [-1_000, BigInt(-1_000)]) { + const html = render(formatSatWithUsd(sats, state)); + assert.match(html, /amount-with-usd-secondary">N\/A/); + assert.doesNotMatch(html, /USD/); + } + assert.equal(logError.mock.callCount(), 2); + + assert.match(render(formatSatWithUsd(100, { bitcoinPrice: 0 })), /\$0\.00 USD/); + + for (const price of [null, undefined, NaN, Infinity, -1]) { + const html = render(formatSatWithUsd(tx.value, { t, bitcoinPrice: price })); + assert.match(html, /amount-with-usd-primary">0\.00100000 BTC/); + assert.match(html, /amount-with-usd-secondary" aria-hidden="true">\u00a0 { + const html = render(transactions([tx], false, { + ...state, feeEst: { 12: 2, 3: 4 }, + })); + assert.match(html, /transactions-with-usd-values/); + assert.match(html, /0\.00100000 BTC/); + assert.match(html, /\$100\.00 USD/); + assert.match(html, /transaction-table-transaction-fee success/); + assert.match(html, /2\.00 sat\/vB/); + assert.match(html, /\$1\.00 USD/); + assert.equal((html.match(/amount-with-usd-secondary/g) || []).length, 2); +}); + +test("uses the shared price on the dashboard and preserves confidential values", () => { + const dashboard = render(transactions([tx], true, state)); + assert.match(dashboard, /transactions-with-usd-values/); + assert.match(dashboard, /\$100\.00 USD/); + assert.match(dashboard, /0\.00100000 BTC/); + assert.match(dashboard, /2\.00 sat\/vB/); + + const confidential = render(transactions([{ ...tx, value: null }], false, state)); + assert.match(confidential, /Confidential/); + assert.equal((confidential.match(/amount-with-usd-secondary/g) || []).length, 1); +}); + +test("reserves a blank USD line until a price arrives", () => { + const html = render(transactions([tx], false, { t })); + assert.match(html, /0\.00100000 BTC/); + assert.match(html, /2\.00 sat\/vB/); + assert.equal((html.match(/aria-hidden="true">\u00a0 { + const { nativeAssetId } = require("../client/src/const"); + const native = render(formatOutAmount({ value: 100_000, asset: nativeAssetId }, state)); + assert.match(native, new RegExp(`href="asset/${nativeAssetId}"`)); + assert.match(native, /\$100\.00 USD/); + const issued = render(formatOutAmount({ value: 100_000, asset: "a".repeat(64) }, state)); + assert.doesNotMatch(issued, /amount-with-usd|USD/); + const confidential = render(formatOutAmount({ valuecommitment: "hidden" }, state)); + assert.match(confidential, /Confidential/); + assert.doesNotMatch(confidential, /amount-with-usd|USD/); +}); + +test("keeps pending-block fee panel BTC and USD costs inline as on master", () => { + const PendingBlockDetailsCard = require("../client/src/views/pending-block-details-card").default; + const { summarizeBlockTemplate } = require("../client/src/lib/block-template"); + const blockTemplate = { height: 101, transactions: [{ fee: 1_000, weight: 400, data: "010000000001" }] }; + const feeEst = { 3: 10, 12: 2 }; + const metrics = summarizeBlockTemplate(blockTemplate, feeEst); + const html = render(PendingBlockDetailsCard({ + ...state, block: { height: 100, timestamp: 1_700_000_000 }, blockTemplate, + detailsOpen: true, feeEst, metrics, t, + })); + const feePanels = html.slice(html.indexOf('info-card-container low-fee'), html.indexOf('info-card-container total-fees-collected')); + assert.ok(feePanels.includes('0.00001000 BTC / $1.00 USD')); + assert.doesNotMatch(feePanels, /amount-with-usd/); + assert.match(html, /amount-with-usd-primary">0\.00001000 BTC/); + assert.match(html, /amount-with-usd-secondary">\$1\.00 USD/); +}); diff --git a/test/block-details-card.test.js b/test/block-details-card.test.js index eb4e55337..2ba810d45 100644 --- a/test/block-details-card.test.js +++ b/test/block-details-card.test.js @@ -321,6 +321,7 @@ test("keeps fee cost loading separate from fee-rate availability", () => { test("formats average fees with the shared native-asset formatter", () => { const html = render(PendingBlockDetailsCard({ bitcoinMarketChart: { prices: [[0, 50_000]] }, + bitcoinPrice: 50_000, block, blockTemplate: { transactions: [] }, detailsOpen: true, diff --git a/test/fee-market.test.js b/test/fee-market.test.js index d5de8f2df..44f124189 100644 --- a/test/fee-market.test.js +++ b/test/fee-market.test.js @@ -20,6 +20,7 @@ test("renders low, average, and high fee estimates with dollar footers", () => { bitcoinMarketChart: { prices: [[1, 40_000], [2, 50_000], [3, null]], }, + bitcoinPrice: 50_000, t, })); diff --git a/test/overview.test.js b/test/overview.test.js index 103939252..ddb1549ca 100644 --- a/test/overview.test.js +++ b/test/overview.test.js @@ -16,6 +16,7 @@ test("formats the recommended fee rate and dollar estimate", () => { feeEst: { 3: 6 }, mempool: { vsize: 0 }, bitcoinMarketChart: { prices: [[1, 40_000], [2, 50_000]] }, + bitcoinPrice: 50_000, t, })); @@ -34,6 +35,7 @@ test("formats negative Bitcoin price changes", () => { const html = render(overview({ blocks: [], bitcoinMarketChart: { prices: [[1, 50_000], [2, 40_000]] }, + bitcoinPrice: 40_000, t, })); @@ -44,11 +46,13 @@ test("shows an unavailable Bitcoin price change without a valid baseline", () => const singlePriceHtml = render(overview({ blocks: [], bitcoinMarketChart: { prices: [[1, 50_000]] }, + bitcoinPrice: 50_000, t, })); const zeroBaselineHtml = render(overview({ blocks: [], bitcoinMarketChart: { prices: [[1, 0], [2, 50_000]] }, + bitcoinPrice: 50_000, t, })); diff --git a/test/recent-transactions.test.js b/test/recent-transactions.test.js new file mode 100644 index 000000000..82587b3a1 --- /dev/null +++ b/test/recent-transactions.test.js @@ -0,0 +1,262 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const { execFileSync } = require("node:child_process"); +const path = require("node:path"); + +// Each process loads the actual build-time network configuration independently. +const simulatePage = () => { + const { Subject } = require("./client/node_modules/rxjs/Subject"); + const { TestScheduler } = require("./client/node_modules/rxjs/testing"); + const { Observable: O } = require("./client/src/rxjs"); + const main = require("./client/src/app").default; + const makeRouteDriver = require("./client/src/driver/route"); + const views = require("./client/src/views"); + const { recentTxs } = views; + const { nativeAssetId } = require("./client/src/const"); + const render = require("snabbdom-to-html"); + + const scheduler = new TestScheduler(() => {}); + const page$ = new Subject(); + const requests = []; + const responses = Object.fromEntries( + ["recent", "fee-est", "tip-height", "bitcoin-market-chart", "asset-map", "mempool", + "tx", "tx-status", "tx-block", "previous-block", "block", "block-stat", "block-txs", + "address", "addr-txs", "asset", "asset-txs"] + .map(category => [category, new Subject()]), + ); + const block = { + id: "d".repeat(64), previousblockhash: "e".repeat(64), height: 100, + timestamp: 1_700_000_000, size: 1_000, weight: 4_000, tx_count: 1, + }; + const output = { value: 100_000, asset: process.env.IS_ELEMENTS ? nativeAssetId : undefined, + scriptpubkey: "", scriptpubkey_asm: "", scriptpubkey_type: "v0_p2wpkh", scriptpubkey_address: "bc1qpreview" }; + const tx = { + txid: "a".repeat(64), value: 100_000, fee: 1_000, vsize: 500, weight: 2_000, + size: 500, version: 2, locktime: 0, + vin: [{ txid: "b".repeat(64), vout: 0, prevout: { ...output, value: 101_000 }, sequence: 0xffffffff, scriptsig: "", witness: [] }], + vout: [output], + status: process.env.PAGE_KIND === "confirmed" + ? { confirmed: true, block_hash: block.id, block_height: 100, block_time: block.timestamp } + : { confirmed: false }, + }; + const asset = { + asset_id: nativeAssetId, + chain_stats: { tx_count: 0, peg_in_amount: 1_000_000, peg_out_amount: 200_000, burned_amount: 100_000 }, + mempool_stats: { tx_count: 0, peg_in_amount: 200_000, peg_out_amount: 100_000, burned_amount: 50_000 }, + }; + const address = { + address: "bc1qpreview", display_addr: "bc1qpreview", + chain_stats: { tx_count: 3, funded_txo_count: 3, funded_txo_sum: 400_000, spent_txo_count: 1, spent_txo_sum: 100_000 }, + mempool_stats: { tx_count: 2, funded_txo_count: 2, funded_txo_sum: 200_000, spent_txo_count: 1, spent_txo_sum: 50_000 }, + }; + const pages = { recent: "/tx/recent", unconfirmed: `/tx/${tx.txid}`, confirmed: `/tx/${tx.txid}`, + block: `/block/${block.id}`, addr: "/address/bc1qpreview", mempool: "/mempool", asset: `/asset/${nativeAssetId}` }; + const initialPage = pages[process.env.PAGE_KIND || "recent"]; + const renderPage = state => render(views[state.view](state)); + let state, htmlAfterFailure, cachedPrice, focused = true; + const sinks = main({ + DOM: { select: () => ({ elements: () => O.empty(), events: () => O.empty() }) }, + HTTP: { select: category => responses[category] || O.empty() }, + route: makeRouteDriver(() => page$)(O.empty()), + storage: { local: { getItem: () => O.of(null) } }, + scanner: O.empty(), search: O.empty(), autocomplete: O.empty(), blinding: O.empty(), + }, { pollingEnabled: true, pollingScheduler: scheduler, hasFocus: () => focused }); + + sinks.state.subscribe(next => { state = next; }); + sinks.HTTP.subscribe(request => { + requests.push({ category: request.category, frame: scheduler.frame }); + scheduler.schedule(() => { + const category = request.category; + if (!responses[category]) return; + // The regular poll retries a failed feed, without immediate extra requests. + const failedFrame = process.env.SCENARIO === "initial-failure" ? 0 : 600_000; + if (process.env.SCENARIO?.endsWith("failure") && category === "bitcoin-market-chart" && scheduler.frame === failedFrame) { + responses[category].next(new O(observer => observer.error(new Error("Price feed unavailable")))); + return; + } + const body = category === "recent" ? [tx] + : category === "fee-est" ? { 1: 5, 3: 4, 12: 2 } + : category === "bitcoin-market-chart" ? { + prices: [[scheduler.frame, process.env.SCENARIO === "failure" && scheduler.frame >= 1_200_000 ? 200_000 : 100_000]], + } + : category === "mempool" ? { count: 1, vsize: 500, total_fee: 1_000, fee_histogram: [[2, 500]] } + : category === "tx" ? tx + : category === "tx-status" ? tx.status + : category === "block" || category === "tx-block" ? block + : category === "previous-block" ? { ...block, id: block.previousblockhash, previousblockhash: undefined, timestamp: block.timestamp - 600 } + : category === "block-stat" ? { in_best_chain: true } + : category === "block-txs" ? [tx] + : category === "address" ? address + : category === "addr-txs" ? [tx] + : category === "asset" ? asset + : category === "asset-txs" ? [] + : {}; + responses[category].next(O.of({ + body, request, + text: category === "tip-height" ? String(100 + Math.floor(scheduler.frame / (process.env.MENU_ACTIVE === "Bitcoin" ? 600_000 : 60_000))) : undefined, + })); + }, 0); + }); + + const navigate = (pathname, search = "") => page$.next({ pathname, hash: "", search }); + scheduler.schedule(() => navigate(initialPage), 0); + if (process.env.SCENARIO === "failure") { + scheduler.schedule(() => { htmlAfterFailure = render(recentTxs(state)); }, 600_001); + } + if (process.env.SCENARIO === "navigation") { + scheduler.schedule(() => { focused = false; }, 550_000); + scheduler.schedule(() => { focused = true; }, 650_000); + scheduler.schedule(() => navigate("/explorer-api"), 950_000); + scheduler.schedule(() => navigate("/tx/recent"), 1_100_000); + scheduler.schedule(() => navigate("/explorer-api"), 1_750_000); + scheduler.maxFrames = 2_500_000; + } else if (process.env.SCENARIO === "shared") { + scheduler.schedule(() => navigate(initialPage + "/"), 50_000); + scheduler.schedule(() => { + navigate(pages.addr); + cachedPrice = state.bitcoinPrice; + }, 100_000); + scheduler.schedule(() => navigate(pages.addr, "?txids=" + tx.txid), 200_000); + scheduler.schedule(() => navigate(pages.addr, "?expand"), 300_000); + scheduler.schedule(() => navigate(pages.block), 800_000); + scheduler.schedule(() => navigate("/explorer-api"), 900_000); + scheduler.maxFrames = 1_500_000; + } else if (process.env.SCENARIO === "browsing") { + [pages.unconfirmed, pages.block, pages.addr, pages.mempool, "/explorer-api", pages.recent] + .forEach((pathname, index) => scheduler.schedule(() => navigate(pathname), (index + 1) * 60_000)); + scheduler.maxFrames = 3_600_000 - 1; + } else if (process.env.SCENARIO === "initial-failure") { + scheduler.schedule(() => navigate(pages.block), 60_000); + scheduler.schedule(() => navigate(pages.addr), 120_000); + scheduler.schedule(() => { htmlAfterFailure = renderPage(state); }, 180_000); + scheduler.maxFrames = 700_000; + } else { + scheduler.maxFrames = 3_600_000 - 1; + } + scheduler.flush(); + + process.stdout.write(JSON.stringify({ + counts: requests.reduce((counts, request) => ({ + ...counts, [request.category]: (counts[request.category] || 0) + 1, + }), {}), + priceFrames: requests.filter(request => request.category === "bitcoin-market-chart").map(request => request.frame), + total: requests.length, + html: renderPage(state), + htmlAfterFailure, + cachedPrice, + })); +}; + +const runPage = (network, scenario = "hour", pageKind = "recent") => JSON.parse(execFileSync( + process.execPath, + ["--require", "@babel/register", "-e", `(${simulatePage.toString()})()`], + { + cwd: path.resolve(__dirname, ".."), + env: { + ...process.env, + MENU_ACTIVE: network, + NATIVE_ASSET_LABEL: network === "Liquid" ? "LBTC" : "BTC", + IS_ELEMENTS: network.startsWith("Liquid") ? "1" : "", + ASSET_MAP_URL: network.startsWith("Liquid") ? "./_data/assets.minimal.json" : "", + API_URL: "/api", BASE_HREF: "/", SCENARIO: scenario, PAGE_KIND: pageKind, + }, + encoding: "utf8", + }, +)); + +for (const [network, total] of [["Bitcoin", 306], ["Liquid", 307]]) { + test(`${network} recent page stays within its approved first-hour budget`, () => { + const page = runPage(network); + assert.equal(page.total, total); + assert.equal(page.counts["tip-height"], 120); + assert.equal(page.counts.recent, 120); + assert.equal(page.counts["fee-est"], 60); + assert.deepEqual(page.priceFrames, [0, 600_000, 1_200_000, 1_800_000, 2_400_000, 3_000_000]); + assert.match(page.html, /transactions-with-usd-values/); + assert.match(page.html, /\$100\.00 USD/); + assert.match(page.html, /\$1\.00 USD/); + assert.match(page.html, network === "Liquid" ? /0\.00100000 LBTC/ : /0\.00100000 BTC/); + }); +} + +for (const network of ["Bitcoin Testnet", "Bitcoin Signet", "Liquid Testnet", "Custom"]) { + test(`${network} recent page does not fetch prices or display USD values`, () => { + const page = runPage(network); + assert.deepEqual(page.priceFrames, []); + assert.equal(page.total, network.startsWith("Liquid") ? 301 : 300); + assert.doesNotMatch(page.html, /amount-with-usd|transactions-with-usd-values/); + }); +} + +test("recent-page price polling respects focus, departure, and reentry", () => { + const page = runPage("Bitcoin", "navigation"); + assert.deepEqual(page.priceFrames, [0, 1_100_000, 1_700_000]); +}); + +test("a failed price refresh retains the previous price and waits for the regular retry", () => { + const page = runPage("Bitcoin", "failure"); + assert.equal(page.total, 306); + assert.deepEqual(page.priceFrames, [0, 600_000, 1_200_000, 1_800_000, 2_400_000, 3_000_000]); + assert.match(page.htmlAfterFailure, /\$100\.00 USD/); + assert.match(page.html, /\$200\.00 USD/); +}); + +test("a failed first price request leaves USD lines blank until the regular retry succeeds", () => { + const page = runPage("Bitcoin", "initial-failure", "addr"); + assert.deepEqual(page.priceFrames, [0, 600_000]); + assert.match(page.htmlAfterFailure, /0\.00450000 BTC/); + assert.match(page.htmlAfterFailure, /amount-with-usd-secondary" aria-hidden="true">\u00a0 { + const page = runPage(network, "hour", kind); + assert.equal(page.total, count + extra, JSON.stringify(page.counts)); + assert.deepEqual(page.priceFrames, [0, 600_000, 1_200_000, 1_800_000, 2_400_000, 3_000_000]); + assert.match(page.html, /amount-with-usd-secondary/); + assert.doesNotMatch(page.html, /amount-with-usd-secondary">N\/A/); + if (kind === "confirmed") { + const footer = page.html.match(/class="transaction-table-footer-confirmation-text text-success">([\s\S]*?)<\/div>/)[1]; + assert.match(footer, /0\.00100000 (L)?BTC/); + assert.doesNotMatch(footer, /USD|amount-with-usd/); + } + if (kind === "addr") assert.match(page.html, /\$450\.00 USD/); + }); + } + test(`${network} unconfirmed transaction adds no tip-driven price fetches`, () => { + const page = runPage(network, "hour", "unconfirmed"); + const statusRequests = network === "Bitcoin" ? 5 : 59; + assert.equal(page.counts["tx-status"], statusRequests); + assert.equal(page.total, 1 + 120 + 60 + 60 + statusRequests + 6 + extra); + assert.equal(page.priceFrames.length, 6); + assert.match(page.html, /\$101\.00 USD/); + assert.match(page.html, /\$100\.00 USD/); + assert.match(page.html, /\$1\.00 USD/); + const footer = page.html.match(/class="transaction-table-footer-confirmation-text text-warning">([\s\S]*?)<\/div>/)[1]; + assert.match(footer, /0\.00100000 (L)?BTC/); + assert.doesNotMatch(footer, /USD|amount-with-usd/); + }); +} + +test("Liquid native asset statistics use the shared BTC price with peg-outs and burns kept separate", () => { + const page = runPage("Liquid", "hour", "asset"); + assert.equal(page.total, 129); + for (const amount of ["$750.00 USD", "$1,200.00 USD", "$300.00 USD", "$150.00 USD"]) { + assert.ok(page.html.includes(amount), amount); + } +}); + +test("pages share the cached price, with no fetch on page changes, pagination, or expanding details", () => { + const page = runPage("Bitcoin", "shared"); + assert.equal(page.cachedPrice, 100_000); + assert.deepEqual(page.priceFrames, [0, 600_000]); +}); + +test("browsing price pages reuses a fresh price and keeps one timer across page changes", () => { + const page = runPage("Bitcoin", "browsing"); + // Returning at 360s from a non-price page reuses the price and restarts the timer. + assert.deepEqual(page.priceFrames, [0, 960_000, 1_560_000, 2_160_000, 2_760_000, 3_360_000]); +}); diff --git a/www/css/components/amount-with-usd.css b/www/css/components/amount-with-usd.css new file mode 100644 index 000000000..91b99fb5c --- /dev/null +++ b/www/css/components/amount-with-usd.css @@ -0,0 +1,17 @@ +.amount-with-usd { + display: inline-flex; + flex-direction: column; + gap: 2px; + vertical-align: middle; +} + +.amount-with-usd-primary, +.amount-with-usd-secondary { + white-space: nowrap; +} + +.amount-with-usd-secondary { + color: var(--foreground-muted); + font-size: .8em; + font-weight: 400; +} diff --git a/www/css/layout/addr.css b/www/css/layout/addr.css new file mode 100644 index 000000000..104f915ae --- /dev/null +++ b/www/css/layout/addr.css @@ -0,0 +1,40 @@ +.bitcoin-usd-values .addr-page .detail-field { + min-width: 0; + flex-wrap: wrap; + gap: 8px 24px; +} + +.bitcoin-usd-values .addr-page .info-stats-row { + flex-wrap: wrap; +} + +.address-output-summary { + display: inline-flex; + flex-wrap: wrap; + align-items: baseline; + gap: 4px 6px; +} + +.address-output-count { + white-space: nowrap; +} + +.address-output-summary-stacked > .amount-with-usd { + width: 100%; + text-align: right; +} + +.address-output-primary { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 4px 6px; +} + +.address-output-primary > span { + white-space: nowrap; +} + +.bitcoin-usd-values .addr-page .detail-field-content .address-output-summary { + justify-content: flex-end; +} diff --git a/www/css/layout/mempool.css b/www/css/layout/mempool.css new file mode 100644 index 000000000..d07f9a7da --- /dev/null +++ b/www/css/layout/mempool.css @@ -0,0 +1,16 @@ +@media (max-width: 1328px) { + .bitcoin-usd-values .mempool-page .stats-table > div { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px 12px; + height: auto; + min-height: 52px; + padding: 8px 0; + } + + .bitcoin-usd-values .mempool-page .stats-table > div > div:last-child { + margin-inline-start: auto; + } +} diff --git a/www/css/layout/transactions.css b/www/css/layout/transactions.css new file mode 100644 index 000000000..df9e19aa0 --- /dev/null +++ b/www/css/layout/transactions.css @@ -0,0 +1,23 @@ +.transactions-with-usd-values .transaction-table-row { + align-items: center; +} + +.transactions-with-usd-values .transaction-table-transaction-fee { + justify-content: flex-end; +} + +@media (max-width: 1328px) { + .transactions-with-usd-values .transaction-table-row { + gap: 12px; + } + + .transactions-with-usd-values .transaction-table-row .transaction-table-field { + flex-wrap: wrap; + justify-content: space-between; + gap: 4px 12px; + } + + .transactions-with-usd-values .transaction-table-field-value { + margin-inline-start: auto; + } +} diff --git a/www/css/layout/tx.css b/www/css/layout/tx.css new file mode 100644 index 000000000..726654de3 --- /dev/null +++ b/www/css/layout/tx.css @@ -0,0 +1,44 @@ +.transaction-fee-primary { + display: flex; + flex-wrap: wrap; + align-items: baseline; + justify-content: flex-end; + gap: 4px 8px; +} + +.transaction-fee-primary > span { + white-space: nowrap; +} + +.bitcoin-usd-values .transaction-fees-content { + flex: 1 1 auto; + min-width: min-content; + max-width: 100%; + justify-content: flex-end; +} + +.bitcoin-usd-values .transaction-fees-content > div, +.bitcoin-usd-values .transaction-fee-value { + min-width: 0; + max-width: 100%; +} + +.bitcoin-usd-values .transaction-fee-value .amount-with-usd { + display: flex; +} + +.bitcoin-usd-values .tx-page .transaction-fees-field { + min-width: 0; + flex-wrap: wrap; + gap: 8px 24px; +} + +.bitcoin-usd-values .tx-page .info-stats-row { + flex-wrap: wrap; +} + +@media (max-width: 1328px) { + .bitcoin-usd-values .transaction-table-footer .amount { + font-size: 14px; + } +} diff --git a/www/css/manifest.json b/www/css/manifest.json index eefe9e181..02b3f7640 100644 --- a/www/css/manifest.json +++ b/www/css/manifest.json @@ -9,6 +9,11 @@ "components/search.css", "components/status-badge.css", "components/asset-icon.css", + "components/amount-with-usd.css", + "layout/transactions.css", + "layout/tx.css", + "layout/addr.css", + "layout/mempool.css", "layout/footer.css", "layout/asset.css" ]