From 98ef5c6f2332be6a99672e3ebdca5b6269231646 Mon Sep 17 00:00:00 2001 From: Alexander Wilke Date: Mon, 16 Nov 2026 18:39:06 +0100 Subject: [PATCH 1/5] feat(frontend): simplify stocks fee summaries --- apps/stocks/CLAUDE.md | 5 +- apps/stocks/README.md | 7 +- apps/stocks/src/components/FeeSummary.jsx | 61 ++++++++++ .../stocks/src/components/PurchasePreview.jsx | 27 +++-- apps/stocks/src/components/QuoteCosts.jsx | 75 +++--------- apps/stocks/src/flows/BuyFlow.jsx | 28 +++-- apps/stocks/src/flows/LiveUsdcFlow.jsx | 10 +- apps/stocks/src/flows/SellFlow.jsx | 23 ++-- apps/stocks/src/flows/SimulatedUsdcFlow.jsx | 10 +- apps/stocks/src/lib/fee-summary.js | 42 +++++++ apps/stocks/src/styles.css | 60 +++++++--- apps/stocks/tests/fee-summary-ui.test.mjs | 110 ++++++++++++++++++ apps/stocks/tests/fee-summary.test.mjs | 66 +++++++++++ apps/stocks/tests/flow-ui.test.mjs | 20 +++- apps/stocks/tests/gas-reserve.test.mjs | 6 +- apps/stocks/tests/jsx-module.mjs | 19 +++ .../stocks/tests/purchase-preview-ui.test.mjs | 34 ++++-- 17 files changed, 464 insertions(+), 139 deletions(-) create mode 100644 apps/stocks/src/components/FeeSummary.jsx create mode 100644 apps/stocks/src/lib/fee-summary.js create mode 100644 apps/stocks/tests/fee-summary-ui.test.mjs create mode 100644 apps/stocks/tests/fee-summary.test.mjs create mode 100644 apps/stocks/tests/jsx-module.mjs diff --git a/apps/stocks/CLAUDE.md b/apps/stocks/CLAUDE.md index 4fb49e73d..efb616b8a 100644 --- a/apps/stocks/CLAUDE.md +++ b/apps/stocks/CLAUDE.md @@ -119,8 +119,9 @@ the sibling of `apps/gold`. route. `validateStockQuote` requires the server's `routingStrategy: "direct"` and `partnerFeeFiat = 0`. `provider-costs.js` validates and renders `providerCosts` (schema in README): `fees` partition reported fees, `rate` - describes signed price effects embedded in output. Unknown amounts remain unknown. The review - shows provider rows, Vortex as the only own revenue fee and an explicit zero Stocks surcharge. + describes signed price effects embedded in output. Unknown amounts remain unknown. The fee-total row expands + into localized functional categories and individual provider rows. Retained ETH is shown separately + from spent fees; Vortex is the only own revenue fee and Stocks adds no surcharge. `fees.total` means reported fees, not necessarily the full spread against a fresh market rate. Simulated costs are illustrative round placeholders, never a provider's real rates. - **Base USDC:** English `/en/stocks/` and the Brazil USDC choice ship in all builds. Live execution is independently gated by `VITE_STOCKS_USDC_ENABLED=true` and backend `STOCKS_USDC_ENABLED_DIRECTIONS`; discover with `paymentMethod=usdc`. `LiveUsdcFlow.jsx` waits for two Base confirmations in the user's own wallet, refreshes the quote, then requires explicit approval before an exact-amount source permit. No fiat KYC call is made. `vortex-stocks.js` shares the existing Pix recovery lock, nonce/deadline/maintenance checks and persisted ephemeral keys. Native Base USDC is code-pinned. `USDC_SIMULATION` removes `SimulatedUsdcFlow.jsx` and simulated payment controls from live builds; demo/preview remain fake and never show payable addresses. See README for deployment order and recovery behavior. diff --git a/apps/stocks/README.md b/apps/stocks/README.md index 3d4e7a321..adf56216b 100644 --- a/apps/stocks/README.md +++ b/apps/stocks/README.md @@ -17,8 +17,9 @@ The route bridges Base USDC to Robinhood Chain USDG through Relay, then swaps to through Uniswap. Stocks adds no surcharge. Live costs come from the Vortex quote; the frontend never overrides them. -The review shows Avenia (Pix), Nabla (conversion), Relay (bridge), Uniswap (stock swap), Vortex, -network gas and the separate ETH reserve. The extra Stocks fee is explicitly zero. Demo prices and +The expandable review groups payment/conversion, token trading/delivery and the Vortex service, +with individual provider details underneath. Any retained ETH balance is separate from spent fees. +Stocks adds no extra fee. Demo prices and all simulated costs are illustrative round placeholders; they mirror no provider's rates. A quote response carries these fields: @@ -59,7 +60,7 @@ The user previews a quote, transfers **native Base USDC into their own wallet**, `vortex-stocks.js` reuses the existing SDK/recovery/maintenance/nonce policies for both payment methods. Before granting a source permit, it pins the delivery token, chain, wallet, quote, input and exact output, plus the client-generated ephemeral spender. Recovery is saved before keys/signatures. A rejected signature or uncertain start resumes the same order; a potentially sent authorization (the wallet prompt opened) retains recovery even if a failed status arrives, while a declined prompt does not hold the wallet lock. Pix and registered USDC operations share the one-operation wallet lock. History retains USDC units. -Provider costs distinguish reported fees from signed execution-price effects, include the ETH reserve once, and show zero additional product fee. Pix quotes may separately show the configured Nabla DEX-fee subsidy; the Nabla row is already net of it. USDC bypasses both Pix and Nabla and receives no Nabla subsidy. Sending wallets/exchanges may charge independently. +The fee-total row expands into plain-language categories, with individual provider names secondary, in Portuguese and English. Unknown amounts remain unknown; partial breakdowns show reported fees without claiming complete costs. Price effects are counted once, and an already-applied discount is explained without being subtracted again. Retained ETH is displayed separately from spent fees; the displayed funding and receipt amounts remain unchanged. There is no additional product fee. Pix quotes may separately show the configured Nabla DEX-fee subsidy; the Nabla row is already net of it. USDC bypasses both Pix and Nabla and receives no Nabla subsidy. Sending wallets/exchanges may charge independently. Demo/preview keep `usdc-checkout.js`'s simulated balances and payment controls. They make no funding/trading calls and show no payable address. `USDC_SIMULATION` removes those controls and their lazy chunk from live builds. `node apps/stocks/scripts/verify-usdc-ui.mjs` still checks the demo UI; Node DOM tests additionally exercise the live UI with synthetic adapters. No real Pix bank transfer is required for these checks, and real bank settlement remains unverified. diff --git a/apps/stocks/src/components/FeeSummary.jsx b/apps/stocks/src/components/FeeSummary.jsx new file mode 100644 index 000000000..529a80825 --- /dev/null +++ b/apps/stocks/src/components/FeeSummary.jsx @@ -0,0 +1,61 @@ +import { BRAND } from "../brand.js"; +import { formatCostAmount, formatCostPercent, groupedFees } from "../lib/fee-summary.js"; + +export function FeeSummary({ rows, total, reserve = 0, basis, currency = "BRL", method = "pix", direction = "BUY", locale = "pt-BR", illustrative = false, subsidy = null }) { + const en = locale === "en", sell = direction === "SELL", t = (pt, english) => en ? english : pt; + const model = groupedFees({ rows, total, reserve, currency, method, direction }); + const money = value => formatCostAmount(value, currency, locale); + const percent = formatCostPercent(model.amount, basis, locale); + const groups = { + payment: t("Pagamento e câmbio", "Payment and currency conversion"), + tradeDelivery: sell ? t("Venda e entrega do valor", "Token sale and delivery") : t("Compra e entrega dos tokens", "Token purchase and delivery"), + trade: sell ? t("Venda do token", "Token sale") : t("Compra do token", "Token purchase"), + delivery: t("Transferência e entrega", "Network transfer and delivery"), + service: t("Serviço Vortex", "Vortex service"), + }; + const items = { + ramp: [sell ? t("Recebimento com Pix", "Pix payout") : t("Pagamento com Pix", "Pix payment"), "Avenia"], + conversion: [sell ? t("Conversão para reais", "Conversion to reais") : t("Conversão para dólar digital", "Conversion to digital dollars"), "Nabla"], + bridge: [t("Transferência entre redes", "Transfer between networks"), sell ? "Relay · Robinhood Chain → Base" : "Relay · Base → Robinhood Chain"], + swap: [sell ? t("Venda do token", "Token sale") : t("Compra do token", "Token purchase"), "Uniswap"], + network: [t("Taxas das transações", "Network transaction fees"), "Base · Robinhood Chain"], + vortex: [sell ? t("Execução e acompanhamento da sua venda", "Execution and tracking of your sale") : t("Execução e acompanhamento da sua compra", "Execution and tracking of your purchase"), "Vortex"], + }; + const title = model.label === "reported" ? t("Taxas informadas", "Reported fees") + : model.label === "costs" ? sell ? t("Custos da venda", "Sale costs") : t("Custos da compra", "Purchase costs") + : sell ? t("Taxas da venda", "Sale fees") : t("Taxas da compra", "Purchase fees"); + const included = model.label === "costs" ? t("já incluídos", "included") : t("já incluídas", "included"); + const deducted = model.label === "costs" ? t("já descontados", "already deducted") : t("já descontadas", "already deducted"); + return
+ + {title}, {sell ? deducted : included} + + {money(model.amount)}{percent && ({percent})} + {t("Ver detalhes", "Show details")}{t("Ocultar detalhes", "Hide details")} + + +
+ {model.groups.map(group =>
+

{groups[group.id]}{money(group.amount)}

+ {group.items.length === 1 ?

{group.id === "service" ? items[group.items[0].id][0] : items[group.items[0].id][1]}{group.items[0].includedIn === "rate" && <> · {t("já refletido no preço", "already reflected in the price")}}

:
{group.items.map(item =>
+
{items[item.id][0]} {items[item.id][1]}{item.includedIn === "rate" && <> · {t("já refletido no preço", "already reflected in the price")}}
+
{money(item.amount)}
+
)}
} +
)} +

{t("Os valores acima já estão incluídos na cotação. Não são cobrados de novo.", "These costs are included in your quote. They are not charged again.")} {t(`A ${BRAND.name} não adiciona outra taxa.`, `${BRAND.name} adds no extra fee.`)}

+ {!model.complete &&

{t("Detalhamento parcial: o total acima mostra as taxas informadas. Custos não discriminados permanecem desconhecidos; não significam custo zero.", "Partial breakdown: the total above shows reported fees. Costs that are not itemized remain unknown; they do not mean zero cost.")}

} + {model.hasPriceEffects &&

{t("Alguns valores já estão no preço de conversão ou negociação e podem aumentar ou reduzir o custo. Não são uma taxa adicional.", "Some amounts are already in the conversion or trading price and can increase or reduce the cost. They are not an additional charge.")}

} + {Number.isFinite(Number(subsidy?.amountFiat)) && Number(subsidy?.amountFiat) > 0 &&

{t("Desconto já aplicado ao câmbio:", "Discount already applied to the conversion:")} {money(Number(subsidy.amountFiat))}. {t("Não é descontado novamente do total.", "It is not subtracted from the total again.")}

} + {illustrative &&

{t("Valores ilustrativos, não tarifas atuais dos provedores.", "Illustrative amounts, not current provider tariffs.")}

} +
+
; +} + +export function ReserveBalance({ amount, currency = "BRL", locale = "pt-BR" }) { + if (!(amount > 0)) return null; + const en = locale === "en"; + return
+

{en ? "Balance for future network fees" : "Saldo para futuras taxas de rede"}{en ? "It stays yours, in your wallet. It is not a fee charged." : "Continua seu, na sua carteira. Não é uma taxa cobrada."}
{en ? "Held as ETH on Robinhood Chain." : "Reservado como ETH na Robinhood Chain."}

+ {formatCostAmount(amount, currency, locale)} +
; +} diff --git a/apps/stocks/src/components/PurchasePreview.jsx b/apps/stocks/src/components/PurchasePreview.jsx index 796525613..35a388696 100644 --- a/apps/stocks/src/components/PurchasePreview.jsx +++ b/apps/stocks/src/components/PurchasePreview.jsx @@ -2,12 +2,12 @@ import { useId, useState } from "react"; import { ArrowRight, CheckCircle } from "./icons.js"; import { STOCK_TOKENS, findStock } from "../lib/stocks.js"; import { estimatePurchase, PREVIEW_DEFAULT, PREVIEW_MINIMUM } from "../lib/purchase-preview.js"; -import { formatBRL, formatNumber } from "../format.js"; -import { formatTokensEn, formatUsdc } from "../lib/international.js"; +import { formatBRL } from "../format.js"; +import { FeeSummary, ReserveBalance } from "./FeeSummary.jsx"; +import { formatCostAmount } from "../lib/fee-summary.js"; +import { DIRECT_PROVIDERS } from "../lib/provider-costs.js"; +import { formatTokensEn } from "../lib/international.js"; import { formatTokenAmount } from "../lib/token.js"; -import { BRAND } from "../brand.js"; - -const PROVIDERS = { avenia: "Avenia · Pix", nabla: "Nabla", relay: "Relay", uniswap: "Uniswap", vortex: "Vortex", network: "Rede / Networks", reserve: "Reserva de ETH / ETH reserve" }; export function PurchasePreview({ prices = {}, locale = "pt-BR", symbol = null, onContinue, canContinue = () => true, id }) { const en = locale === "en", uid = useId(); @@ -18,7 +18,9 @@ export function PurchasePreview({ prices = {}, locale = "pt-BR", symbol = null, const [error, setError] = useState(""); const token = findStock(symbol || selected); const preview = estimatePurchase({ symbol: token.symbol, method, amount, locale }, prices[token.symbol]?.[method === "pix" ? "brl" : "usd"]); - const money = value => method === "pix" ? formatBRL(value) : formatUsdc(value, 4); + const money = value => formatCostAmount(value, method === "pix" ? "BRL" : "USDC", locale); + const reserve = preview?.costs.find(cost => cost.provider === "reserve")?.amount || 0; + const rows = preview?.costs.filter(cost => cost.provider !== "reserve").map(cost => ({ id: DIRECT_PROVIDERS.find(item => item.provider === cost.provider)?.id, amount: cost.amount, includedIn: "fees" })) || []; const available = preview && canContinue(preview.selection); const change = fn => { fn(); setReviewed(false); setError(""); }; const next = async () => { @@ -26,7 +28,7 @@ export function PurchasePreview({ prices = {}, locale = "pt-BR", symbol = null, try { await onContinue(preview.selection); } catch (e) { setError(en ? "We could not keep your selection for sign-in. Please try again." : e.message); } }; return
-

{en ? "Your first purchase" : "Sua primeira compra"}

+

{en ? "Your first purchase" : "Sua primeira compra"}

{en ? "How much would you like to start with?" : "Com quanto você quer começar?"}

{symbol ?

{en ? token.underlyingName : token.namePt} {token.symbol} · Stock Token

: } {!en &&
{["pix", "usdc"].filter(value => value === "pix" || canContinue({ method: value })).map(value => )}
} @@ -37,9 +39,14 @@ export function PurchasePreview({ prices = {}, locale = "pt-BR", symbol = null,
{(method === "pix" ? [100, 500, 1000] : [10, 100, 250]).map(value => )}
{reviewed && preview &&

{en ? "Your estimate" : "Sua estimativa"}

-
{en ? "You pay" : "Você paga"}
{money(preview.amount)}
{en ? "Estimated costs, included" : "Custos estimados, já incluídos"}
{money(preview.total)} ({en ? (preview.total / preview.amount * 100).toFixed(2) : formatNumber(preview.total / preview.amount * 100, 2)}%)
{en ? "You receive, approximately" : "Você recebe, aproximadamente"}
≈ {en ? formatTokensEn(preview.tokenAmount) : formatTokenAmount(preview.tokenAmount)} {token.symbol}
-
{en ? "See providers and costs" : "Ver provedores e custos"}
{preview.costs.map(cost =>
{cost.provider === "network" ? en ? "Network fees" : "Taxas de rede" : cost.provider === "reserve" ? en ? "ETH reserve in your wallet" : "Reserva de ETH na sua carteira" : PROVIDERS[cost.provider]}
{money(cost.amount)}
)}
{en ? `Extra ${BRAND.name} fee` : `Taxa extra ${BRAND.name}`}
{money(0)}
-

{en ? "Reference price and illustrative costs, including a small ETH reserve that stays in your wallet. Your final quote is checked after sign-in and shown before any payment. Your sending wallet or exchange may charge separately." : "Preço de referência e custos ilustrativos, com uma pequena reserva de ETH que fica na sua carteira. A cotação final é atualizada depois que você entrar e aparece antes de qualquer pagamento."}

+

{en ? "Illustrative example. Review a fresh quote after signing in, before you pay." : "Exemplo ilustrativo. Confira a cotação atualizada depois de entrar, antes de pagar."}

+
+
{en ? "You pay" : "Você paga"}
{money(preview.amount)}
+ +
{en ? "Amount used to buy your tokens" : "Valor usado para comprar seus tokens"}
{money(preview.net)}≈ {en ? formatTokensEn(preview.tokenAmount) : formatTokenAmount(preview.tokenAmount)} {en ? `${token.symbol} tokens` : `tokens ${token.symbol}`}
+
+ + {method === "usdc" &&

{en ? "Your sending wallet or exchange may charge separately." : "A carteira ou corretora de origem pode cobrar à parte."}

}
} {error &&

{error}

} {!reviewed ? diff --git a/apps/stocks/src/components/QuoteCosts.jsx b/apps/stocks/src/components/QuoteCosts.jsx index 6b3aabe37..ae986f3ce 100644 --- a/apps/stocks/src/components/QuoteCosts.jsx +++ b/apps/stocks/src/components/QuoteCosts.jsx @@ -1,69 +1,22 @@ -import { formatBRL, formatNumber } from "../format.js"; -import { BRAND } from "../brand.js"; -import { formatUsdc } from "../lib/international.js"; -import { quoteProviderCosts, costBps } from "../lib/provider-costs.js"; +import { FeeSummary } from "./FeeSummary.jsx"; +import { quoteProviderCosts } from "../lib/provider-costs.js"; export function QuoteCosts({ quote }) { - const details = quoteProviderCosts(quote.rawQuote, { reserve: quote.gasReserve, simulated: quote.simulated }); - const basis = quote.direction === "BUY" ? quote.brlAmount : quote.brlAmount + quote.fees.total; - const rows = quote.direction === "SELL" - ? ["swap", "bridge", "conversion", "ramp", "vortex", "network"].map((id) => details.rows.find((row) => row.id === id)) - : details.rows; - return ( -
- Provedores e custos {quote.simulated ? "Simulação" : "Cotação"}Relay + Uniswap · sem taxa adicional {BRAND.name} -
-

{details.routing === "direct" ? "Rota direta · Relay + Uniswap" : "Rota ainda não confirmada pelo provedor"}

-
- {rows.map((row) =>
-
{row.name}{row.label}
-
{row.amount === null ? "Não discriminado" : formatBRL(row.amount)} - {row.amount === null ? "Detalhe não informado na cotação" : `${formatNumber(costBps(row.amount, basis), 2)} bps · ${row.includedIn === "rate" ? "no câmbio" : "nas taxas"}`} -
-
)} -
Taxa adicional {BRAND.name}Sem cobrança além do serviço Vortex e dos provedores
{formatBRL(details.extraProductFee)}0 bps
- {quote.gasReserve &&
Reserva de ETHFica na sua carteira como ETH na Robinhood Chain
{formatBRL(quote.gasReserve.brl)}Já incluída nas taxas
} - {quote.rawQuote.nablaFeeSubsidy &&
Subsídio da taxa NablaTaxa DEX efetiva: {Number(quote.rawQuote.nablaFeeSubsidy.effectiveFeeBps).toFixed(2)} bps
−{formatBRL(Number(quote.rawQuote.nablaFeeSubsidy.amountFiat))}Já refletido no câmbio acima
} - {details.identifiedTotal !== null &&
Custos identificadosTaxas, efeitos de preço informados e reserva de ETH
{formatBRL(details.identifiedTotal)}{formatNumber(costBps(details.identifiedTotal, basis), 2)} bps
} -
-

Os valores acima já estão refletidos no que você paga e recebe. Não são cobrados novamente.{!details.complete && " O detalhamento está incompleto: taxas informadas não representam necessariamente todo o efeito de câmbio e negociação."}

- {quote.simulated &&

Provedores planejados e valores ilustrativos. A cotação real pode variar.

} -
-
- ); + return ; } -export function UsdcQuoteCosts({ quote }) { - const basis = Number(quote.grossRaw); - const costs = quote.direction === "SELL" ? ["swap", "bridge", "vortex", "network", "reserve"].map((id) => quote.costs.find((c) => c.id === id)) : quote.costs; - return
- Providers and costs SimulationDirect Relay + Uniswap · no additional product fee -
-
- {costs.map((cost) =>
{cost.provider}{cost.label}
{formatUsdc(Number(cost.raw) / 1e6, 4)}{(Number(cost.raw) / basis * 10_000).toFixed(2)} bps · included
)} -
Additional {BRAND.name} fee
0.00 USDC0 bps
-
Total included costs
{formatUsdc(Number(quote.totalFeesRaw) / 1e6, 4)}{(Number(quote.totalFeesRaw) / basis * 10_000).toFixed(2)} bps
-
-

All listed costs are already reflected in your quoted output. The ETH reserve is included once and remains in your wallet. Your sending wallet or exchange may charge separately.

-

Illustrative provider costs, not live tariffs. The Vortex fee is our only service revenue.

-
-
; +export function UsdcQuoteCosts({ quote, locale = "en" }) { + return cost.id !== "reserve").map(cost => ({ id: cost.id, amount: Number(cost.raw) / 1e6, includedIn: "fees" }))} + total={Number(quote.totalFeesRaw) / 1e6} reserve={Number(quote.costs.find(cost => cost.id === "reserve")?.raw || 0) / 1e6} + basis={Number(quote.grossRaw) / 1e6} currency="USDC" method="usdc" direction={quote.direction} locale={locale} illustrative />; } export function LiveUsdcCosts({ quote, locale = "en" }) { - const pt = locale !== "en", t = (en, br) => pt ? br : en; - const money = (value, digits = 6) => formatUsdc(value, digits, pt ? "pt-BR" : "en-US"); - const bps = value => new Intl.NumberFormat(pt ? "pt-BR" : "en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value); - const details = quoteProviderCosts(quote.rawQuote, { reserve: quote.gasReserve }); - const basis = quote.direction === "BUY" ? quote.usdcAmount : quote.usdcAmount + quote.fees.total; - const names = { bridge: ["Relay", "Base ↔ Robinhood Chain"], swap: ["Uniswap", "USDG ↔ Stock Token"], vortex: ["Vortex", t("Service and execution", "Serviço e execução")], network: [t("Networks", "Redes"), t("Gas on Base and Robinhood Chain", "Gas na Base e na Robinhood Chain")] }; - const rows = (quote.direction === "SELL" ? ["swap", "bridge", "vortex", "network"] : ["bridge", "swap", "vortex", "network"]).map(id => details.rows.find(r => r.id === id)); - const identified = details.complete ? quote.fees.total + details.rows.filter(r => r.includedIn === "rate").reduce((sum,r) => sum + r.amount, 0) : null; - return
{t("Providers and costs", "Provedores e custos")}{t("Live quote", "Cotação atual")}{t("Direct Relay + Uniswap · no additional product fee", "Relay + Uniswap direto · sem taxa adicional do produto")}
- {rows.map(row =>
{names[row.id][0]}{names[row.id][1]}
{row.amount == null ? t("Not itemized", "Não discriminado") : money(row.amount, 6)}{row.amount == null ? "—" : `${bps(costBps(row.amount,basis))} bps · ${row.includedIn === "rate" ? t("in execution price", "no preço de execução") : t("in fees", "nas taxas")}`}
)} -
{t("Additional product fee", "Taxa adicional do produto")}
0 USDC0 bps
- {quote.gasReserve &&
{t("ETH reserve in your wallet", "Reserva de ETH na sua carteira")}
{money(quote.gasReserve.brl, 6)}{t("Already inside network fees", "Já incluída nas taxas de rede")}
} -
{t("Reported fees", "Taxas informadas")}
{money(quote.fees.total, 6)}
- {identified != null &&
{t("Identified costs including price effects", "Custos identificados, incluindo efeitos de preço")}
{money(identified, 6)}{bps(costBps(identified,basis))} bps
} -

{t("All amounts are already reflected in the quote and are not deducted again. Price effects can be favorable or unfavorable. Your sending wallet or exchange can charge separately. The Vortex fee is our only service revenue.", "Os valores já estão refletidos na cotação e não são descontados de novo. Os efeitos de preço podem ser favoráveis ou desfavoráveis. A carteira ou corretora de origem pode cobrar à parte. A taxa Vortex é nossa única receita de serviço.")}

; + return ; } diff --git a/apps/stocks/src/flows/BuyFlow.jsx b/apps/stocks/src/flows/BuyFlow.jsx index 0a2961a49..d61f48d8d 100644 --- a/apps/stocks/src/flows/BuyFlow.jsx +++ b/apps/stocks/src/flows/BuyFlow.jsx @@ -6,16 +6,17 @@ import { useEffect, useRef, useState } from "react"; import { isTransientError } from "@vortexfi/consumer-kit"; import { ArrowLeft, ArrowRight, Info } from "../components/icons.js"; import { Modal } from "../components/Modal.jsx"; +import { ReserveBalance } from "../components/FeeSummary.jsx"; import { QuoteCosts } from "../components/QuoteCosts.jsx"; import { Notice } from "../components/ui.jsx"; import { DEMO_TOOLS } from "../lib/config.js"; -import { formatBRL, formatNumber, formatPercent, priceBRL } from "../format.js"; -import { gasReserveLinePt, sellLaterNotePt } from "../lib/gas-reserve.js"; +import { formatBRL, formatPercent, priceBRL } from "../format.js"; +import { sellLaterNotePt } from "../lib/gas-reserve.js"; import { MARKET_CLOSED_NOTE_PT, tokenizationClosedNotePt, tokenizationWindowOpen, usMarketStatus } from "../lib/market-hours.js"; import { waitingCopyPt } from "../lib/phases.js"; import { checkQuotePrice } from "../lib/price-guard.js"; import { freshPauseReason } from "../lib/ramp-contract.js"; -import { DEFAULT_BUY, MIN_BUY, QUICK_BUY_VALUES, buyFeePercent, quoteNeedsRefresh, showSmallBuyNote, stepAfterCode, validBuyAmount } from "../lib/purchase-options.js"; +import { DEFAULT_BUY, MIN_BUY, QUICK_BUY_VALUES, quoteNeedsRefresh, showSmallBuyNote, stepAfterCode, validBuyAmount } from "../lib/purchase-options.js"; import { estimateTokensForBrl, formatSharesApproxPt, formatTokenAmount, multiplierWeiFor, sharesWei } from "../lib/token.js"; import { FlowIssue, FlowProgress, GuardCard, KYC_IN_REVIEW_PT, KycStep, OtpStep, POLL_RESTART_MS, ProcessingSteps, QuoteTimer, SuccessSeal, TokenSummary, Waiting, errorMessage, needsCode, unavailableMessage } from "./parts.jsx"; import { PixStep } from "./PixStep.jsx"; @@ -57,25 +58,22 @@ function AmountStep({ token, price, amount, setAmount, onNext, busy, error, onPa function ConfirmStep({ token, quote, guard, reference, multiplierWei, onConfirm, onRefresh, busy, error, notice }) { const [accepted, setAccepted] = useState(false); const [guardAccepted, setGuardAccepted] = useState(false); - const fee = buyFeePercent(quote, quote.brlAmount); const shares = sharesWei(quote.tokenAmountWei, multiplierWeiFor(token, multiplierWei)); const deviation = guard?.deviationPct; const blocked = guard?.status === "block"; const canConfirm = accepted && !blocked && (guard?.status !== "warn" || guardAccepted) && !busy; - const reserve = gasReserveLinePt(quote); return (
{notice && {notice}} -
-
Você paga
{formatBRL(quote.brlAmount)}
-
Taxas informadas (já incluídas)
{formatBRL(quote.fees.total)}{fee != null && {formatNumber(fee, 2)}% do valor}
-
Conversão e serviço
{formatBRL(quote.fees.service)}
-
Taxas das redes
{formatBRL(quote.fees.network)}
- {reserve &&
{reserve.label}{reserve.note}
{formatBRL(reserve.brl)}
} -
Preço por token nesta cotação
{priceBRL(quote.impliedBrlPerToken)}{reference && referência {priceBRL(reference.brl)}{deviation != null ? ` (${formatPercent(deviation)})` : ""}}
-
Você recebe
{formatTokenAmount(quote.tokenAmount)} {token.symbol} (token){formatSharesApproxPt(shares)}
-
- +
+
Você paga
{formatBRL(quote.brlAmount)}
+ +
+
Preço por token nesta cotação
{priceBRL(quote.impliedBrlPerToken)}{reference && referência {priceBRL(reference.brl)}{deviation != null ? ` (${formatPercent(deviation)})` : ""}}
+
Você recebe
{formatTokenAmount(quote.tokenAmount)} {token.symbol} (token){formatSharesApproxPt(shares)}
+
+
+

{sellLaterNotePt(quote)}

diff --git a/apps/stocks/src/flows/LiveUsdcFlow.jsx b/apps/stocks/src/flows/LiveUsdcFlow.jsx index 1bd3efd6b..a87413833 100644 --- a/apps/stocks/src/flows/LiveUsdcFlow.jsx +++ b/apps/stocks/src/flows/LiveUsdcFlow.jsx @@ -1,6 +1,8 @@ import { useEffect, useRef, useState } from "react"; import { QRCodeSVG } from "qrcode.react"; import { Modal } from "../components/Modal.jsx"; +import { ReserveBalance } from "../components/FeeSummary.jsx"; +import { formatCostAmount } from "../lib/fee-summary.js"; import { LiveUsdcCosts } from "../components/QuoteCosts.jsx"; import { Notice } from "../components/ui.jsx"; import { errorMessage } from "./parts.jsx"; @@ -125,8 +127,12 @@ export default function LiveUsdcFlow({ token, auth, runtime, direction = "BUY",

{t("Minimum order: 10 USDC. You receive a Stock Token, not the underlying share. Bank payments are planned.", "Mínimo de 10 USDC. Você recebe um token de ação, não a ação. O Pix continua disponível como outra forma de pagamento.")}

} {step === "review" && quote && <> -
{direction === "BUY" ? t("You pay", "Você paga") : t("You sell", "Você vende")}
{direction === "BUY" ? money(quote.usdcAmount, 6) : `${(pt ? formatTokenAmount(quote.tokenAmount) : formatTokensEn(quote.tokenAmount))} ${token.symbol}`}
{t("Estimated receipt", "Recebimento estimado")}
{out(quote)}
- +
+
{direction === "BUY" ? t("You pay", "Você paga") : t("You sell", "Você vende")}
{direction === "BUY" ? formatCostAmount(quote.usdcAmount, "USDC", runtime.locale) : `${(pt ? formatTokenAmount(quote.tokenAmount) : formatTokensEn(quote.tokenAmount))} ${token.symbol}`}
+ +
{t("Estimated receipt", "Recebimento estimado")}
{out(quote)}
+
+

{t("Your wallet signs one exact-amount authorization. Vortex pays execution gas. An exchange or sending wallet can charge separately.", "Sua carteira assina uma autorização do valor exato. A Vortex cobre o gas da execução. A corretora ou carteira de origem pode cobrar à parte.")}

diff --git a/apps/stocks/src/flows/SellFlow.jsx b/apps/stocks/src/flows/SellFlow.jsx index a8e2c31ba..8f4aa393e 100644 --- a/apps/stocks/src/flows/SellFlow.jsx +++ b/apps/stocks/src/flows/SellFlow.jsx @@ -8,7 +8,7 @@ import { QuoteCosts } from "../components/QuoteCosts.jsx"; import { ArrowLeft, ArrowRight, Check, Copy, GasPump } from "../components/icons.js"; import { Modal } from "../components/Modal.jsx"; import { Notice } from "../components/ui.jsx"; -import { formatBRL, formatNumber, formatPercent, priceBRL } from "../format.js"; +import { formatBRL, formatPercent, priceBRL } from "../format.js"; import { useCopy } from "../hooks.js"; import { DEMO_TOOLS } from "../lib/config.js"; import { sellGasNoticePt, sellGasRequiredWei } from "../lib/gas-reserve.js"; @@ -86,16 +86,17 @@ function ReviewStep({ token, quote, guard, reference, pixKey, ethWei, requiredWe return (
{notice && {notice}} -
-
Você vende
{formatTokenAmount(quote.tokenAmount)} {token.symbol} (token)
-
Valor bruto
{formatBRL(gross)}
-
Taxas informadas (já descontadas)
{formatBRL(quote.fees.total)}{formatNumber((quote.fees.total / gross) * 100, 2)}% do valor
-
Conversão e serviço
{formatBRL(quote.fees.service)}
-
Gas das redes
{formatBRL(quote.fees.network)}
-
Preço por token nesta cotação
{priceBRL(quote.impliedBrlPerToken)}{reference && referência {priceBRL(reference.brl)}{guard?.deviationPct != null ? ` (${formatPercent(guard.deviationPct)})` : ""}}
-
Você recebe no Pix
{formatBRL(quote.brlAmount)}
-
- +
+
+
Você vende
{formatTokenAmount(quote.tokenAmount)} {token.symbol} (token)
+
Valor bruto
{formatBRL(gross)}
+
+ +
+
Preço por token nesta cotação
{priceBRL(quote.impliedBrlPerToken)}{reference && referência {priceBRL(reference.brl)}{guard?.deviationPct != null ? ` (${formatPercent(guard.deviationPct)})` : ""}}
+
Você recebe no Pix
{formatBRL(quote.brlAmount)}
+
+

Chave Pix: {pixKey}

{gasNotice && {gasNotice.text}} diff --git a/apps/stocks/src/flows/SimulatedUsdcFlow.jsx b/apps/stocks/src/flows/SimulatedUsdcFlow.jsx index 77ade3886..ae86b689d 100644 --- a/apps/stocks/src/flows/SimulatedUsdcFlow.jsx +++ b/apps/stocks/src/flows/SimulatedUsdcFlow.jsx @@ -1,5 +1,6 @@ import { useEffect, useRef, useState } from "react"; import { Modal } from "../components/Modal.jsx"; +import { ReserveBalance } from "../components/FeeSummary.jsx"; import { UsdcQuoteCosts } from "../components/QuoteCosts.jsx"; import { Notice } from "../components/ui.jsx"; import { formatTokensEn, formatUsdc } from "../lib/international.js"; @@ -113,8 +114,13 @@ export default function SimulatedUsdcFlow({ token, auth, runtime, market, direct } {["review", "needs_review"].includes(status) && shown && <> {status === "needs_review" && The price moved outside your approved limit. No stock purchase has been made. Your USDC remains available.} -
{direction === "BUY" ? "You pay" : "You sell"}
{direction === "BUY" ? formatUsdc(shown.input) : `${formatTokensEn(shown.input)} ${token.symbol}`}
Included costs
{formatUsdc(usdcText(shown.totalFeesRaw), 4)}
You receive (estimate)
{outputText(shown)}
Network for USDC
Base
- +
+
{direction === "BUY" ? "You pay" : "You sell"}
{direction === "BUY" ? formatUsdc(shown.input) : `${formatTokensEn(shown.input)} ${token.symbol}`}
+ +
You receive (estimate)
{outputText(shown)}
Network for USDC
Base
+
+ cost.id === "reserve")?.raw || 0) / 1e6} currency="USDC" locale={runtime.locale || "en"} /> +

{runtime.locale === "pt-BR" ? "A carteira ou corretora de origem pode cobrar à parte." : "Your sending wallet or exchange may charge separately."}

Price protection: minimum {outputText({ ...shown, outputRaw: (BigInt(shown.outputRaw) * 9950n / 10000n).toString() })}. Maximum included costs: {formatUsdc(usdcText(BigInt(shown.totalFeesRaw) + (BigInt(shown.grossRaw) * 5n + 9999n) / 10000n), 6)}.

{seconds ? `Quote valid for ${seconds}s.` : "Quote expired. Refresh before continuing."} Funding may take longer. We recheck the price when funds arrive and buy automatically only within your approved limits.

{direction === "BUY" && status === "review" && balance < BigInt(shown.grossRaw) &&
} diff --git a/apps/stocks/src/lib/fee-summary.js b/apps/stocks/src/lib/fee-summary.js new file mode 100644 index 000000000..1e7c23217 --- /dev/null +++ b/apps/stocks/src/lib/fee-summary.js @@ -0,0 +1,42 @@ +// Presentation only: never changes an executable quote, payment amount or approval. +const round = (value, currency) => { + const scale = currency === "USDC" ? 1e6 : 100; + const result = Math.round(value * scale) / scale; + return result === 0 ? 0 : result; +}; + +export function groupedFees({ rows, total, reserve = 0, currency = "BRL", method = "pix", direction = "BUY" }) { + const selling = direction === "SELL"; + const definitions = method === "usdc" + ? [{ id: "trade", ids: ["swap"] }, { id: "delivery", ids: ["bridge", "network"] }, { id: "service", ids: ["vortex"] }] + : [{ id: "payment", ids: selling ? ["conversion", "ramp"] : ["ramp", "conversion"] }, { id: "tradeDelivery", ids: selling ? ["swap", "bridge", "network"] : ["bridge", "swap", "network"] }, { id: "service", ids: ["vortex"] }]; + const groups = definitions.map(group => { + const items = group.ids.map(id => { + const row = rows.find(item => item.id === id); + return { id, amount: typeof row?.amount === "number" && Number.isFinite(row.amount) ? row.amount : null, includedIn: row?.includedIn || "fees" }; + }); + return { id: group.id, items, amount: items.every(item => item.amount !== null) ? round(items.reduce((sum, item) => sum + item.amount, 0), currency) : null }; + }); + const items = groups.flatMap(group => group.items); + const reported = round(total - reserve, currency); + const feeSum = round(items.filter(item => item.includedIn === "fees").reduce((sum, item) => sum + (item.amount ?? 0), 0), currency); + const complete = items.every(item => item.amount !== null) && Math.abs(feeSum - reported) < (currency === "USDC" ? 0.0000005 : 0.005); + const hasPriceEffects = items.some(item => item.includedIn === "rate"); + const priceEffects = items.filter(item => item.includedIn === "rate").reduce((sum, item) => sum + (item.amount ?? 0), 0); + return { groups, complete, hasPriceEffects, reported, amount: complete ? round(reported + priceEffects, currency) : reported, label: !complete ? "reported" : hasPriceEffects ? "costs" : "fees" }; +} + +export function formatCostAmount(amount, currency = "BRL", locale = "pt-BR") { + if (amount === null || !Number.isFinite(amount)) return locale === "en" ? "Not itemized" : "Não discriminado"; + const digits = currency === "USDC" || (amount !== 0 && Math.abs(amount) < 0.01) ? 6 : 2; + const options = { minimumFractionDigits: 2, maximumFractionDigits: digits }; + const language = locale === "en" ? "en-US" : "pt-BR"; + return currency === "USDC" ? `${new Intl.NumberFormat(language, options).format(amount)} USDC` + : new Intl.NumberFormat(language, { ...options, style: "currency", currency: "BRL" }).format(amount); +} + +export function formatCostPercent(amount, basis, locale = "pt-BR") { + if (!Number.isFinite(amount) || !Number.isFinite(basis) || basis <= 0) return null; + const percent = amount / basis * 100; + return `${new Intl.NumberFormat(locale === "en" ? "en-US" : "pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: percent !== 0 && Math.abs(percent) < 0.01 ? 6 : 2 }).format(percent)}%`; +} diff --git a/apps/stocks/src/styles.css b/apps/stocks/src/styles.css index d98a1e126..a69b795cb 100644 --- a/apps/stocks/src/styles.css +++ b/apps/stocks/src/styles.css @@ -671,16 +671,6 @@ select.text-input { appearance: none; background-image: linear-gradient(45deg, t .breakdown .is-total dt { color: var(--ink); font-weight: 600; white-space: nowrap; } .breakdown .is-total dd { font-size: 17px; white-space: normal; } .quote-timer { display: flex; align-items: center; justify-content: space-between; gap: 8px; color: var(--text-muted); font-size: 14px; } -.provider-costs { border: 1px solid var(--hairline); border-radius: var(--radius-md); background: var(--surface); } -.provider-costs summary { min-height: 48px; padding: 14px 16px; cursor: pointer; font-size: 15px; font-weight: 600; } -.provider-costs summary span { float: right; color: var(--text-muted); font-size: 12px; font-weight: 400; } -.provider-costs summary small { display: block; margin-top: 4px; color: var(--text-muted); font-size: 13px; font-weight: 400; } -.provider-costs__body { display: grid; gap: 12px; padding: 0 12px 14px; } -.provider-costs__rows > div { padding: 12px; align-items: flex-start; } -.provider-costs__rows dt { min-width: 0; color: var(--ink); } -.provider-costs__rows .is-total dt { white-space: normal; } -.provider-costs__rows dd { max-width: 46%; white-space: normal; } -.provider-costs__rows dt small, .provider-costs__rows dd small { font-family: var(--font-body); font-size: 12px; line-height: 1.45; } .payment-methods { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } .payment-choice { display: grid; gap: 5px; min-width: 0; padding: 16px; border: 1px solid var(--hairline); border-radius: var(--radius-md); background: var(--surface); text-align: left; font-size: 14px; } button.payment-choice { cursor: pointer; } @@ -839,16 +829,52 @@ button.payment-choice { cursor: pointer; } .preview-result .breakdown dt { min-width: 0; } .preview-result .breakdown .is-total dt { white-space: normal; } .preview-result .breakdown .is-total dd { font-size: 15px; } -.preview-costs { font-size: 13px; } -.preview-costs summary { color: var(--anil-700); cursor: pointer; padding-block: 6px; } -.preview-costs dl { display: grid; gap: 8px; margin-top: 8px; } -.preview-costs dl > div { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; } -.preview-costs dt { color: var(--text-muted); } -.preview-costs dd { font-family: var(--font-numeric); white-space: nowrap; } .preview-note, .preview-assurance { color: var(--text-muted); font-size: 12px; line-height: 1.55; } .preview-assurance { border-top: 1px solid var(--hairline); padding-top: 12px; } .featured-minimum { color: var(--text-muted); font-size: 14px; margin: -8px 0 18px; } .international-detail-preview { max-width: 490px; margin: 24px 0; } .international-notes details summary { cursor: pointer; color: var(--anil-700); padding-block: 10px; } @media (min-width: 900px) { .hero__grid { grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 56px; align-items: center; } .usdc-hero { grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: 56px; } } -@media (max-width: 639px) { .purchase-preview { padding: 20px; gap: 12px; } .hero__grid { gap: 30px; } .purchase-preview .btn--lg { font-size: 15px; } .preview-costs dd { font-size: 12px; } } +@media (max-width: 639px) { .purchase-preview { padding: 20px; gap: 12px; } .hero__grid { gap: 30px; } .purchase-preview .btn--lg { font-size: 15px; } } + + +/* Shared cost presentation: disclosure stays on the fee-total row. */ +.fee-card { border: 1px solid var(--hairline); border-radius: var(--radius-md); overflow: hidden; min-width: 0; } +.fee-card > .breakdown { border: 0; border-radius: 0; } +.fee-summary { border-block: 1px solid var(--hairline); background: var(--surface); min-width: 0; } +.fee-summary > summary { display: flex; flex-wrap: wrap; align-items: center; gap: 16px; min-height: 64px; padding: 10px 16px; list-style: none; cursor: pointer; font-size: 14px; } +.fee-summary > summary::-webkit-details-marker { display: none; } +.fee-summary > summary:focus-visible { outline: 3px solid var(--anil-600); outline-offset: -4px; } +.fee-summary__label { flex: 1 1 160px; min-width: 0; color: var(--text-muted); } +.fee-summary__value { display: flex; flex: 1 1 auto; min-width: 0; align-items: center; justify-content: flex-end; gap: 16px; } +.fee-summary__amount { min-width: 0; overflow-wrap: anywhere; font-family: var(--font-numeric); font-size: 14px; font-weight: 500; text-align: right; font-variant-numeric: tabular-nums; } +.fee-summary__amount small { margin-left: 6px; font-family: var(--font-body); font-size: 12px; color: var(--text-muted); white-space: nowrap; } +.fee-summary__toggle { display: flex; align-items: center; justify-content: flex-end; min-height: 48px; min-width: 104px; color: var(--anil-700); font-size: 13px; font-weight: 600; text-decoration: underline; text-underline-offset: 3px; } +.fee-summary__hide { display: none; } +.fee-summary[open] .fee-summary__show { display: none; } +.fee-summary[open] .fee-summary__hide { display: inline; } +.fee-summary__body { padding: 0 16px 16px; background: #FCFBFF; } +.fee-summary__group { padding: 16px 0 12px; border-bottom: 1px solid var(--hairline); } +.fee-summary__group:last-of-type { border: 0; padding-bottom: 0; } +.fee-summary__group h3 { display: flex; justify-content: space-between; gap: 16px; margin: 0 0 8px; font-size: 15px; font-weight: 600; line-height: 1.4; } +.fee-summary__group h3 > span:last-child { flex-shrink: 0; max-width: 48%; text-align: right; font-family: var(--font-numeric); font-size: 14px; } +.fee-summary__group dl > div { display: flex; justify-content: space-between; gap: 16px; padding: 9px 0; font-size: 13px; } +.fee-summary__group dt { min-width: 0; } +.fee-summary__group dt small { display: block; margin-top: 3px; font-size: 12px; color: var(--text-muted); } +.fee-summary__group dd { flex-shrink: 0; max-width: 48%; text-align: right; font-family: var(--font-numeric); font-variant-numeric: tabular-nums; } +.fee-summary__note { margin-top: 10px; color: var(--text-muted); font-size: 12px; line-height: 1.5; } +.reserve-balance { display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; padding: 14px 16px; border-radius: var(--radius-md); background: var(--anil-50); font-size: 13px; } +.reserve-balance p { min-width: 0; } +.reserve-balance small { display: block; color: var(--text-muted); margin-top: 4px; font-size: 12px; line-height: 1.5; } +.reserve-balance strong { flex-shrink: 0; max-width: 42%; font-family: var(--font-numeric); text-align: right; font-size: 14px; } +.preview-result .fee-card .breakdown .is-total { display: block; padding: 16px; } +.preview-result .fee-card .breakdown .is-total dd { margin-top: 8px; text-align: left; font-size: 25px; } +.preview-result .fee-card .breakdown .is-total dd small { font-family: var(--font-body); font-size: 14px; } +@media (max-width: 600px) { + .fee-summary > summary { gap: 0 12px; padding-inline: 12px; } + .fee-summary__amount { max-width: 180px; font-size: 13px; } + .fee-summary__toggle { min-height: 48px; font-size: 12px; } + .fee-summary__body { padding-inline: 12px; } + .fee-summary__group h3 { font-size: 14px; } + .fee-summary__group h3 > span:last-child { font-size: 12px; } +} diff --git a/apps/stocks/tests/fee-summary-ui.test.mjs b/apps/stocks/tests/fee-summary-ui.test.mjs new file mode 100644 index 000000000..4407cecff --- /dev/null +++ b/apps/stocks/tests/fee-summary-ui.test.mjs @@ -0,0 +1,110 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { readFile } from "node:fs/promises"; +import { JSDOM } from "jsdom"; +import { act, createElement, Fragment } from "react"; +import { createRoot } from "react-dom/client"; +import { importJsx } from "./jsx-module.mjs"; +import { simulatedProviderCosts } from "../src/lib/fee-model.js"; +const { FeeSummary, ReserveBalance } = await importJsx(new URL("../src/components/FeeSummary.jsx", import.meta.url)); +const { QuoteCosts, LiveUsdcCosts, UsdcQuoteCosts } = await importJsx(new URL("../src/components/QuoteCosts.jsx", import.meta.url)); +const css = await readFile(new URL("../src/styles.css", import.meta.url), "utf8"); +const marker = css.indexOf("/* Shared cost presentation:"); +assert.ok(marker >= 0); +const rows = () => simulatedProviderCosts(1000).map(row => ({ id: row.id, amount: row.amountFiat, includedIn: "fees" })); +const text = element => element.textContent.replace(/\u00a0/g, " ").replace(/\s+/g, " ").trim(); + +async function harness(run) { + const previous = [globalThis.window, globalThis.document, globalThis.IS_REACT_ACT_ENVIRONMENT]; + const dom = new JSDOM(`
`, { url: "http://localhost/" }); + Object.assign(globalThis, { window: dom.window, document: dom.window.document, IS_REACT_ACT_ENVIRONMENT: true }); + const root = createRoot(document.getElementById("root")); + try { await run(element => act(async () => root.render(element))); } + finally { + await act(async () => root.unmount()); dom.window.close(); + for (const [key, value] of [["window", previous[0]], ["document", previous[1]], ["IS_REACT_ACT_ENVIRONMENT", previous[2]]]) { + if (value === undefined) delete globalThis[key]; else globalThis[key] = value; + } + } +} + +for (const locale of ["pt-BR", "en"]) { + test(`${locale}: the fee-total row itself expands/collapses and shows each cost once`, () => harness(async render => { + await render(createElement(Fragment, null, + createElement(FeeSummary, { rows: rows(), total: 6.71, reserve: 0.71, basis: 1000, locale }), + createElement(ReserveBalance, { amount: 0.71, locale }))); + const details = document.querySelector("details"), summary = details.querySelector("summary"); + assert.equal(details.open, false); + assert.match(text(summary), locale === "en" ? /Purchase fees.*R\$6.00.*0.60%/ : /Taxas da compra.*R\$ 6,00.*0,60%/); + assert.equal(window.getComputedStyle(summary.querySelector(".fee-summary__hide")).display, "none"); + assert.notEqual(window.getComputedStyle(summary.querySelector(".fee-summary__show")).display, "none"); + await act(async () => summary.click()); + assert.equal(details.open, true); + assert.equal(window.getComputedStyle(summary.querySelector(".fee-summary__show")).display, "none"); + assert.notEqual(window.getComputedStyle(summary.querySelector(".fee-summary__hide")).display, "none"); + assert.equal(document.querySelectorAll("[data-fee-group]").length, 3); + for (const id of ["ramp", "conversion", "bridge", "swap", "network", "vortex", "reserve"]) { + assert.equal(document.querySelectorAll(`[data-cost-id="${id}"]`).length, 1, id); + } + assert.equal(details.querySelector('[data-cost-id="reserve"]'), null); + assert.match(text(document.querySelector('[data-cost-id="bridge"] dt')), locale === "en" ? /^Transfer between networks Relay/ : /^Transferência entre redes Relay/); + assert.match(text(document.querySelector('[data-cost-id="swap"] dt')), locale === "en" ? /^Token purchase Uniswap/ : /^Compra do token Uniswap/); + assert.doesNotMatch(text(details), /\bbps\b/); + await act(async () => summary.click()); assert.equal(details.open, false); + })); + + test(`${locale}: USDC has appropriate categories, localized money and no Pix/Nabla fee`, () => harness(async render => { + await render(createElement(FeeSummary, { rows: rows().filter(r => !["ramp", "conversion"].includes(r.id)), total: 4.1, reserve: 0.1, basis: 1000, currency: "USDC", method: "usdc", locale })); + const summary = document.querySelector("summary"); + assert.match(text(summary), locale === "en" ? /4.00 USDC.*0.40%/ : /4,00 USDC.*0,40%/); + assert.doesNotMatch(document.body.textContent, /Pix|Nabla|BRL|R\$/); + assert.match(text(document.body), locale === "en" ? /Token purchase.*Network transfer and delivery.*Vortex service/ : /Compra do token.*Transferência e entrega.*Serviço Vortex/); + })); + + test(`${locale}: missing provider detail is unknown, not a fabricated zero or complete cost`, () => harness(async render => { + await render(createElement(FeeSummary, { rows: rows().filter(r => r.id !== "bridge"), total: 6, basis: 1000, locale })); + assert.match(text(document.querySelector("summary")), locale === "en" ? /Reported fees/ : /Taxas informadas/); + assert.equal(text(document.querySelector('[data-cost-id="bridge"] dd')), locale === "en" ? "Not itemized" : "Não discriminado"); + assert.match(text(document.querySelector('[role="note"]')), locale === "en" ? /Partial breakdown.*do not mean zero/ : /Detalhamento parcial.*não significam custo zero/); + })); + + test(`${locale}: signed price effects and already-applied discounts keep the correct net total`, () => harness(async render => { + const costs = rows(); costs.find(r => r.id === "conversion").includedIn = "rate"; costs.find(r => r.id === "conversion").amount = -0.5; + await render(createElement(FeeSummary, { rows: costs, total: 5, basis: 1000, locale, subsidy: { amountFiat: "2.00" } })); + assert.match(text(document.querySelector("summary")), locale === "en" ? /Purchase costs.*R\$4.50/ : /Custos da compra, já incluídos.*R\$ 4,50/); + assert.match(text(document.querySelector('[data-cost-id="conversion"]')), locale === "en" ? /already reflected in the price/ : /já refletido no preço/); + assert.match(text(document.querySelector('[data-cost-id="subsidy"]')), locale === "en" ? /not subtracted.*again/ : /Não é descontado novamente/); + })); +} + +test("retained balance is omitted when no reserve was quoted", () => harness(async render => { + await render(createElement(ReserveBalance, { amount: 0 })); assert.equal(document.querySelector(".reserve-balance"), null); + await render(createElement(ReserveBalance, {})); assert.equal(document.querySelector(".reserve-balance"), null); +})); + +test("real Pix quote wrapper uses gross sell proceeds as the percentage basis and does not mutate the quote", () => harness(async render => { + const quote = { direction: "SELL", brlAmount: 94, fees: { total: 6 }, rawQuote: { totalFeeFiat: 6, providerCosts: simulatedProviderCosts(1000) } }; + const original = structuredClone(quote); + await render(createElement(QuoteCosts, { quote })); + assert.match(text(document.querySelector("summary")), /Taxas da venda, já descontadas.*6,00%/); + assert.match(text(document.body), /Venda do token.*Robinhood Chain → Base/); + assert.deepEqual(quote, original); +})); + +test("real USDC wrapper is complete without unused Pix providers and keeps reserve in USDC units", () => harness(async render => { + const costs = simulatedProviderCosts(1000).filter(r => !["ramp", "conversion"].includes(r.id)); + const quote = { direction: "BUY", usdcAmount: 1000, fees: { total: 4.1 }, gasReserve: { brl: 0.1 }, rawQuote: { totalFeeFiat: 4.1, providerCosts: costs } }; + await render(createElement(Fragment, null, createElement(LiveUsdcCosts, { quote, locale: "pt-BR" }), createElement(ReserveBalance, { amount: quote.gasReserve.brl, currency: "USDC", locale: "pt-BR" }))); + assert.match(text(document.querySelector("summary")), /Taxas da compra.*4,00 USDC/); + assert.doesNotMatch(text(document.body), /Detalhamento parcial|R\$|Nabla|Pix/); + assert.match(text(document.querySelector(".reserve-balance")), /0,10 USDC/); +})); + +for (const locale of ["en", "pt-BR"]) test(`${locale}: simulated USDC quote wrapper separates retained ETH from costs`, () => harness(async render => { + const quote = { direction: "BUY", grossRaw: "1000000000", totalFeesRaw: "3200000", costs: [ + { id: "bridge", raw: "1000000" }, { id: "swap", raw: "1000000" }, { id: "vortex", raw: "1000000" }, { id: "network", raw: "100000" }, { id: "reserve", raw: "100000" }, + ] }; + await render(createElement(UsdcQuoteCosts, { quote, locale })); + assert.match(text(document.querySelector("summary")), locale === "en" ? /Purchase fees.*3.10 USDC/ : /Taxas da compra.*3,10 USDC/); + assert.match(text(document.body), locale === "en" ? /Illustrative amounts/ : /Valores ilustrativos/); +})); diff --git a/apps/stocks/tests/fee-summary.test.mjs b/apps/stocks/tests/fee-summary.test.mjs new file mode 100644 index 000000000..71466eef6 --- /dev/null +++ b/apps/stocks/tests/fee-summary.test.mjs @@ -0,0 +1,66 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { formatCostAmount, formatCostPercent, groupedFees } from "../src/lib/fee-summary.js"; +const rows = () => ["ramp", "conversion", "bridge", "swap", "vortex", "network"].map(id => ({ id, amount: 1, includedIn: "fees" })); + +test("Pix groups every fee once and separates retained ETH without changing the input", () => { + const input = { rows: rows(), total: 6.71, reserve: 0.71 }; + const original = structuredClone(input); + const result = groupedFees(input); + assert.equal(result.complete, true); assert.equal(result.amount, 6); assert.equal(result.reported, 6); + assert.deepEqual(result.groups.map(g => [g.id, g.amount]), [["payment", 2], ["tradeDelivery", 3], ["service", 1]]); + assert.deepEqual(result.groups.flatMap(g => g.items.map(i => i.id)), ["ramp", "conversion", "bridge", "swap", "network", "vortex"]); + assert.deepEqual(input, original); +}); + +test("USDC has no Pix or currency-conversion charge and preserves six-decimal precision", () => { + const input = { rows: rows().filter(r => !["ramp", "conversion"].includes(r.id)), total: 4.100001, reserve: 0.1, method: "usdc", currency: "USDC" }; + input.rows[0].amount = 1.000001; + const result = groupedFees(input); + assert.equal(result.complete, true); assert.equal(result.amount, 4.000001); + assert.deepEqual(result.groups.map(g => g.id), ["trade", "delivery", "service"]); + assert.equal(result.groups.some(g => g.items.some(i => ["ramp", "conversion", "reserve"].includes(i.id))), false); +}); + +test("signed price effects are counted once, including already-net discounted conversion", () => { + const input = { rows: rows(), total: 4.71, reserve: 0.71 }; + input.rows.find(r => r.id === "conversion").includedIn = "rate"; + input.rows.find(r => r.id === "bridge").includedIn = "rate"; + const result = groupedFees(input); + assert.equal(result.complete, true); assert.equal(result.reported, 4); assert.equal(result.amount, 6); assert.equal(result.label, "costs"); + input.rows.find(r => r.id === "conversion").amount = -1.5; + assert.equal(groupedFees(input).amount, 3.5); + input.rows.find(r => r.id === "conversion").amount = -10; + assert.equal(groupedFees(input).amount, -5, "favorable price effects are not clamped to zero"); +}); + +test("partial provider detail stays unknown; neither missing amounts nor an unallocated fee become zero", () => { + const input = { rows: rows().filter(r => r.id !== "bridge"), total: 6 }; + const result = groupedFees(input); + assert.equal(result.complete, false); assert.equal(result.label, "reported"); assert.equal(result.amount, 6); + assert.equal(result.groups.find(g => g.id === "tradeDelivery").amount, null); + assert.equal(result.groups.flatMap(g => g.items).find(i => i.id === "bridge").amount, null); + input.rows.push({ id: "bridge", amount: 0, includedIn: "fees" }); + assert.equal(groupedFees(input).groups.flatMap(g => g.items).find(i => i.id === "bridge").amount, 0); + assert.equal(groupedFees(input).complete, false, "a real zero does not explain a missing charge elsewhere"); + assert.equal(groupedFees({ rows: rows(), total: 6.01 }).complete, false); +}); + +test("sell grouping reverses the relevant route and keeps the same accounting", () => { + const result = groupedFees({ rows: rows(), total: 6, direction: "SELL" }); + assert.equal(result.amount, 6); + assert.deepEqual(result.groups[0].items.map(i => i.id), ["conversion", "ramp"]); + assert.deepEqual(result.groups[1].items.map(i => i.id), ["swap", "bridge", "network"]); +}); + +test("localized overview amounts omit trailing precision but keep exact USDC and small nonzero fees", () => { + assert.equal(formatCostAmount(1000, "USDC", "en"), "1,000.00 USDC"); + assert.equal(formatCostAmount(1000.123456, "USDC", "pt-BR"), "1.000,123456 USDC"); + assert.equal(formatCostAmount(0.000001, "USDC", "en"), "0.000001 USDC"); + assert.equal(formatCostAmount(-0.000001, "USDC", "pt-BR"), "-0,000001 USDC"); + assert.equal(formatCostAmount(null, "BRL", "pt-BR"), "Não discriminado"); + assert.equal(formatCostAmount(null, "USDC", "en"), "Not itemized"); + assert.equal(formatCostPercent(6, 1000), "0,60%"); + assert.equal(formatCostPercent(6, 1000, "en"), "0.60%"); + assert.equal(formatCostPercent(1, 0), null); +}); diff --git a/apps/stocks/tests/flow-ui.test.mjs b/apps/stocks/tests/flow-ui.test.mjs index 49f60d0bf..3a46e5744 100644 --- a/apps/stocks/tests/flow-ui.test.mjs +++ b/apps/stocks/tests/flow-ui.test.mjs @@ -665,7 +665,7 @@ test("a cancelled USDC permit resumes the same registered order instead of regis })); test("Brazilian live USDC uses Portuguese copy and the same provider costs",()=>harness(async s=>{ const f=liveUsdcFixtures("pt-BR");await s.render(createElement(LiveUsdcFlow,f.props));await s.click("Ver cotação"); - assert.match(s.text(),/Provedores e custos/);assert.match(s.text(),/100,000000 USDC/);assert.match(s.text(),/0,5000 NVDA/);assert.match(s.text(),/Taxas informadas/);assert.doesNotMatch(s.text(),/Illustrative provider/); + assert.ok(document.querySelector(".fee-card .fee-summary > summary"));assert.match(s.text(),/Ver detalhes/);assert.match(s.text(),/100,00 USDC/);assert.match(s.text(),/0,5000 NVDA/);assert.match(s.text(),/Taxas informadas/);assert.doesNotMatch(s.text(),/Illustrative provider/); })); test("Brazilian live USDC words a cancelled permit in Portuguese and keeps the same order", () => harness(async s => { @@ -692,3 +692,21 @@ test("a saved USDC order remains resumable when new USDC purchases are disabled" await s.render(createElement(LiveUsdcFlow,f.props));assert.ok(s.has("Resume order"));await s.click("Resume order"); assert.match(s.text(),/Your Stock Tokens have arrived/);assert.doesNotMatch(s.text(),/USDC is coming soon/); })); + + +for (const reserve of [null, { brl: 0.71, ethAmount: "0.00005" }]) { + test(`Pix review renders retained ETH separately when quoted: ${Boolean(reserve)}`, () => harness(async s => { + const props = fixtures(approved); + props.runtime.adapter.quoteBuy = async () => ({ ...quote, gasReserve: reserve, fees: { ...quote.fees, total: 3 + (reserve?.brl || 0) } }); + await s.render(createElement(BuyFlow, props)); + await s.click("Continuar"); + const line = document.querySelector(".reserve-balance"); + assert.equal(Boolean(line), Boolean(reserve)); + if (line) { + assert.match(line.textContent.replace(/\u00a0/g, " "), /Saldo para futuras taxas.*R\$ 0,71/); + assert.equal(line.closest(".fee-summary"), null); + assert.match(line.textContent, /Não é uma taxa cobrada/); + } + assert.match(document.querySelector(".fee-summary > summary").textContent.replace(/\u00a0/g, " "), /R\$ 3,00/); + })); +} diff --git a/apps/stocks/tests/gas-reserve.test.mjs b/apps/stocks/tests/gas-reserve.test.mjs index b0b0fb757..dad6fd00e 100644 --- a/apps/stocks/tests/gas-reserve.test.mjs +++ b/apps/stocks/tests/gas-reserve.test.mjs @@ -189,15 +189,13 @@ test("ETH amounts read the pt-BR way, with two significant digits", () => { assert.equal(formatEthPt(300_000_000_000_000n), "0,0003"); }); -test("buy review: the reserve gets its own line, only when the quote includes one", () => { +test("reserve copy helper returns a balance only when the quote includes one", () => { assert.equal(GAS_RESERVE_LABEL_PT, "Reserva de ETH na sua carteira"); assert.equal(gasReserveNotePt(RESERVE), "≈ 0,00005 ETH na Robinhood Chain, que fica na sua carteira"); assert.deepEqual(gasReserveLinePt({ gasReserve: RESERVE }), { label: GAS_RESERVE_LABEL_PT, note: gasReserveNotePt(RESERVE), brl: 0.71 }); assert.equal(gasReserveLinePt({ gasReserve: null }), null); assert.equal(gasReserveLinePt(null), null); - const confirm = flowStep("src/flows/BuyFlow.jsx", "function ConfirmStep"); - assert.match(confirm, /const reserve = gasReserveLinePt\(quote\);/); - assert.match(confirm, /\{reserve &&
\{reserve\.label\}\{reserve\.note\}<\/small><\/dt>
\{formatBRL\(reserve\.brl\)\}<\/dd><\/div>\}/); + }); test("the wallet check before a sell transaction: only advice that works while the sell is open", () => { diff --git a/apps/stocks/tests/jsx-module.mjs b/apps/stocks/tests/jsx-module.mjs new file mode 100644 index 000000000..c393c9ac0 --- /dev/null +++ b/apps/stocks/tests/jsx-module.mjs @@ -0,0 +1,19 @@ +import { readFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; +import { transformWithEsbuild } from "vite"; + +// The app's actual JSX and nested JSX imports, with the existing Vite transformer. +const loaded = new Map(); +async function jsxModuleUrl(url) { + if (!loaded.has(url.href)) loaded.set(url.href, (async () => { + const { code } = await transformWithEsbuild(await readFile(url, "utf8"), fileURLToPath(url), { jsx: "automatic" }); + let rewritten = code; + for (const [statement, keyword, specifier] of [...code.matchAll(/(from\s+|import\()["']([^"']+)["']/g)]) { + const target = specifier.endsWith(".jsx") ? await jsxModuleUrl(new URL(specifier, url)) : specifier.startsWith(".") ? new URL(specifier, url).href : import.meta.resolve(specifier); + rewritten = rewritten.replace(statement, `${keyword}${JSON.stringify(target)}`); + } + return `data:text/javascript;base64,${Buffer.from(rewritten).toString("base64")}`; + })()); + return loaded.get(url.href); +} +export const importJsx = async url => import(await jsxModuleUrl(url)); diff --git a/apps/stocks/tests/purchase-preview-ui.test.mjs b/apps/stocks/tests/purchase-preview-ui.test.mjs index 945aaeceb..aad56e4b4 100644 --- a/apps/stocks/tests/purchase-preview-ui.test.mjs +++ b/apps/stocks/tests/purchase-preview-ui.test.mjs @@ -1,19 +1,11 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { readFile } from "node:fs/promises"; -import { createRequire } from "node:module"; -import { fileURLToPath, pathToFileURL } from "node:url"; import { JSDOM } from "jsdom"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; -import { transformWithEsbuild } from "vite"; -// Exercise the actual JSX with the app's existing Vite transformer; no browser or new runner. -const source = new URL("../src/components/PurchasePreview.jsx", import.meta.url); -const requireFromSource = createRequire(source); -const transformed = await transformWithEsbuild(await readFile(source, "utf8"), fileURLToPath(source), { jsx: "automatic" }); -const code = transformed.code.replace(/from\s+["']([^"']+)["']/g, (_, specifier) => `from ${JSON.stringify(specifier.startsWith(".") ? new URL(specifier, source).href : pathToFileURL(requireFromSource.resolve(specifier)).href)}`); -const { PurchasePreview } = await import(`data:text/javascript;base64,${Buffer.from(code).toString("base64")}`); +import { importJsx } from "./jsx-module.mjs"; +const { PurchasePreview } = await importJsx(new URL("../src/components/PurchasePreview.jsx", import.meta.url)); const prices = { NVDA: { brl: 1000, usd: 200 } }; async function harness(run) { @@ -41,8 +33,15 @@ test("anonymous Pix preview needs no sign-in and hands off only the selected amo assert.equal(document.querySelector("input").value, "100"); await s.click("Ver custos da compra"); assert.match(s.text(), /Sua estimativa/); - assert.match(s.text().replace(/\u00a0/g, " "), /R\$ 3,11/); + assert.match(document.querySelector(".fee-summary > summary").textContent.replace(/\u00a0/g, " "), /R\$ 2,40/); + assert.match(document.querySelector(".reserve-balance").textContent.replace(/\u00a0/g, " "), /R\$ 0,71/); + assert.match(document.querySelector(".fee-card .is-total").textContent.replace(/\u00a0/g, " "), /R\$ 96,89/); assert.equal(calls.length, 0); + await act(async () => document.querySelector(".fee-summary > summary").click()); + assert.equal(document.querySelector(".fee-summary").open, true); + assert.equal(calls.length, 0, "expanding costs never starts the purchase"); + await act(async () => document.querySelector(".fee-summary > summary").click()); + assert.equal(document.querySelector("input").value, "100"); await s.click("Continuar com Pix"); assert.deepEqual(calls, [{ symbol: "NVDA", method: "pix", amount: "100", locale: "pt-BR" }]); })); @@ -106,3 +105,16 @@ test("while the ramp's answer is unknown the preview promises neither buying nor assert.equal(s.button("Continuar com Pix").disabled, true); assert.match(s.text(), /Compra em breve/); })); + + +for (const locale of ["pt-BR", "en"]) { + test(`${locale}: the USDC sending-wallet notice appears once, including expanded fees`, () => harness(async s => { + await s.render({ locale }); + if (locale !== "en") await s.click("USDC · na Base"); + await s.click(locale === "en" ? "See purchase costs" : "Ver custos da compra"); + const warning = locale === "en" ? /Your sending wallet or exchange may charge separately/g : /A carteira ou corretora de origem pode cobrar à parte/g; + assert.equal((s.text().match(warning) || []).length, 1); + await act(async () => document.querySelector(".fee-summary > summary").click()); + assert.equal((s.text().match(warning) || []).length, 1); + })); +} From 8da47022cb164fb09bd285c776f88204dd9ab7df Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 17 Nov 2026 08:36:24 +0100 Subject: [PATCH 2/5] fix(frontend): count the api's one-cent rounding as a complete stocks fee breakdown The API rounds each fee line on its own and totalFeeFiat once, so a fully itemized quote often lands one cent (or one micro-USDC) off its total. providerCostProblem already accepts that gap, but groupedFees demanded an exact match, so those quotes showed "Taxas informadas" with the partial note and left their price effects out of the headline. groupedFees now uses the same one-unit allowance. --- apps/stocks/src/lib/fee-summary.js | 4 +++- apps/stocks/tests/fee-summary.test.mjs | 11 ++++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/apps/stocks/src/lib/fee-summary.js b/apps/stocks/src/lib/fee-summary.js index 1e7c23217..59e7bd4cc 100644 --- a/apps/stocks/src/lib/fee-summary.js +++ b/apps/stocks/src/lib/fee-summary.js @@ -20,7 +20,9 @@ export function groupedFees({ rows, total, reserve = 0, currency = "BRL", method const items = groups.flatMap(group => group.items); const reported = round(total - reserve, currency); const feeSum = round(items.filter(item => item.includedIn === "fees").reduce((sum, item) => sum + (item.amount ?? 0), 0), currency); - const complete = items.every(item => item.amount !== null) && Math.abs(feeSum - reported) < (currency === "USDC" ? 0.0000005 : 0.005); + // The same 1-unit allowance as providerCostProblem: the API rounds each fee line, and the total once. + const units = value => Math.round(value * (currency === "USDC" ? 1e6 : 100)); + const complete = items.every(item => item.amount !== null) && Math.abs(units(feeSum) - units(reported)) <= 1; const hasPriceEffects = items.some(item => item.includedIn === "rate"); const priceEffects = items.filter(item => item.includedIn === "rate").reduce((sum, item) => sum + (item.amount ?? 0), 0); return { groups, complete, hasPriceEffects, reported, amount: complete ? round(reported + priceEffects, currency) : reported, label: !complete ? "reported" : hasPriceEffects ? "costs" : "fees" }; diff --git a/apps/stocks/tests/fee-summary.test.mjs b/apps/stocks/tests/fee-summary.test.mjs index 71466eef6..d6c7b6bc0 100644 --- a/apps/stocks/tests/fee-summary.test.mjs +++ b/apps/stocks/tests/fee-summary.test.mjs @@ -43,7 +43,7 @@ test("partial provider detail stays unknown; neither missing amounts nor an unal input.rows.push({ id: "bridge", amount: 0, includedIn: "fees" }); assert.equal(groupedFees(input).groups.flatMap(g => g.items).find(i => i.id === "bridge").amount, 0); assert.equal(groupedFees(input).complete, false, "a real zero does not explain a missing charge elsewhere"); - assert.equal(groupedFees({ rows: rows(), total: 6.01 }).complete, false); + assert.equal(groupedFees({ rows: rows(), total: 6.02 }).complete, false); }); test("sell grouping reverses the relevant route and keeps the same accounting", () => { @@ -64,3 +64,12 @@ test("localized overview amounts omit trailing precision but keep exact USDC and assert.equal(formatCostPercent(6, 1000, "en"), "0.60%"); assert.equal(formatCostPercent(1, 0), null); }); + +test("a fully itemized quote off by the API's one-unit rounding stays complete, as the quote validator accepts it", () => { + const input = { rows: rows(), total: 5.72, reserve: 0.71 }; + input.rows.find(r => r.id === "conversion").includedIn = "rate"; + const result = groupedFees(input); + assert.equal(result.complete, true); assert.equal(result.label, "costs"); assert.equal(result.amount, 6.01); + const usdc = groupedFees({ rows: rows().filter(r => !["ramp", "conversion"].includes(r.id)), total: 4.000001, method: "usdc", currency: "USDC" }); + assert.equal(usdc.complete, true); +}); From 821397aa0d96afccbfb8b308ecc678e8babd81ca Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 17 Nov 2026 08:36:24 +0100 Subject: [PATCH 3/5] fix(frontend): derive the stocks sell gross from the cost headline MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit With a complete breakdown the cost headline also counts the price effects already inside the payout, but "Valor bruto" stayed brlAmount + fees, so gross minus costs no longer equalled "Você recebe no Pix". sellGross adds the headline to the payout; the Pix sell review and the sell percentage bases (Pix and Base USDC) use it. --- apps/stocks/src/components/QuoteCosts.jsx | 17 +++++++++++++---- apps/stocks/src/flows/SellFlow.jsx | 4 ++-- apps/stocks/tests/fee-summary-ui.test.mjs | 11 ++++++++++- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/apps/stocks/src/components/QuoteCosts.jsx b/apps/stocks/src/components/QuoteCosts.jsx index ae986f3ce..761aa0184 100644 --- a/apps/stocks/src/components/QuoteCosts.jsx +++ b/apps/stocks/src/components/QuoteCosts.jsx @@ -1,10 +1,19 @@ import { FeeSummary } from "./FeeSummary.jsx"; +import { groupedFees } from "../lib/fee-summary.js"; import { quoteProviderCosts } from "../lib/provider-costs.js"; +const costRows = quote => quoteProviderCosts(quote.rawQuote, { reserve: quote.gasReserve }).rows; + +/** A sell's gross: its payout plus the cost headline FeeSummary shows, so gross minus costs is the payout on + * screen. A complete breakdown's headline also counts the price effects already inside the payout. */ +export const sellGross = (quote, { currency = "BRL", method = "pix" } = {}) => + (currency === "USDC" ? quote.usdcAmount : quote.brlAmount) + + groupedFees({ rows: costRows(quote), total: quote.fees.total, reserve: quote.gasReserve?.brl || 0, currency, method, direction: "SELL" }).amount; + export function QuoteCosts({ quote }) { - return ; } @@ -15,8 +24,8 @@ export function UsdcQuoteCosts({ quote, locale = "en" }) { } export function LiveUsdcCosts({ quote, locale = "en" }) { - return ; } diff --git a/apps/stocks/src/flows/SellFlow.jsx b/apps/stocks/src/flows/SellFlow.jsx index 8f4aa393e..7f41f9dfc 100644 --- a/apps/stocks/src/flows/SellFlow.jsx +++ b/apps/stocks/src/flows/SellFlow.jsx @@ -4,7 +4,7 @@ // sign (resume): resumeSell -> start; processing -> success | issue import { useEffect, useRef, useState } from "react"; import { isTransientError } from "@vortexfi/consumer-kit"; -import { QuoteCosts } from "../components/QuoteCosts.jsx"; +import { QuoteCosts, sellGross } from "../components/QuoteCosts.jsx"; import { ArrowLeft, ArrowRight, Check, Copy, GasPump } from "../components/icons.js"; import { Modal } from "../components/Modal.jsx"; import { Notice } from "../components/ui.jsx"; @@ -81,7 +81,7 @@ function ReviewStep({ token, quote, guard, reference, pixKey, ethWei, requiredWe const gasNotice = sellGasNoticePt({ gasless: quote.gasless, ethWei, requiredWei }); const noGas = gasNotice?.needsEth === true; const blocked = guard?.status === "block"; - const gross = quote.brlAmount + quote.fees.total; + const gross = sellGross(quote); const canConfirm = accepted && !blocked && !noGas && (guard?.status !== "warn" || guardAccepted) && !busy; return (
diff --git a/apps/stocks/tests/fee-summary-ui.test.mjs b/apps/stocks/tests/fee-summary-ui.test.mjs index 4407cecff..019e47652 100644 --- a/apps/stocks/tests/fee-summary-ui.test.mjs +++ b/apps/stocks/tests/fee-summary-ui.test.mjs @@ -7,7 +7,7 @@ import { createRoot } from "react-dom/client"; import { importJsx } from "./jsx-module.mjs"; import { simulatedProviderCosts } from "../src/lib/fee-model.js"; const { FeeSummary, ReserveBalance } = await importJsx(new URL("../src/components/FeeSummary.jsx", import.meta.url)); -const { QuoteCosts, LiveUsdcCosts, UsdcQuoteCosts } = await importJsx(new URL("../src/components/QuoteCosts.jsx", import.meta.url)); +const { QuoteCosts, LiveUsdcCosts, UsdcQuoteCosts, sellGross } = await importJsx(new URL("../src/components/QuoteCosts.jsx", import.meta.url)); const css = await readFile(new URL("../src/styles.css", import.meta.url), "utf8"); const marker = css.indexOf("/* Shared cost presentation:"); assert.ok(marker >= 0); @@ -108,3 +108,12 @@ for (const locale of ["en", "pt-BR"]) test(`${locale}: simulated USDC quote wrap assert.match(text(document.querySelector("summary")), locale === "en" ? /Purchase fees.*3.10 USDC/ : /Taxas da compra.*3,10 USDC/); assert.match(text(document.body), locale === "en" ? /Illustrative amounts/ : /Valores ilustrativos/); })); + +test("a Pix sell's gross is its payout plus the cost headline, so the review's rows add up", () => harness(async render => { + const cost = (id, provider, amountFiat, includedIn = "fees") => ({ id, provider, amountFiat, includedIn }); + const quote = { direction: "SELL", brlAmount: 96, fees: { total: 4 }, rawQuote: { totalFeeFiat: "4", providerCosts: [cost("ramp", "avenia", "1"), + cost("conversion", "nabla", "0.5", "rate"), cost("bridge", "relay", "0.3", "rate"), cost("swap", "uniswap", "0.2", "rate"), cost("vortex", "vortex", "2"), cost("network", "network", "1")] } }; + assert.equal(sellGross(quote), 101, "R$ 96 paid out + R$ 4 fees + R$ 1 of price effects already inside the payout"); + await render(createElement(QuoteCosts, { quote })); + assert.match(text(document.querySelector("summary")), /Custos da venda.*R\$ 5,00.*4,95%/); +})); From 67b77370b55e7de5c2229193d381bb74140b65b2 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 17 Nov 2026 08:36:25 +0100 Subject: [PATCH 4/5] fix(frontend): show the stocks eth reserve inside the estimate's cost card The estimate's "Valor usado para comprar seus tokens" is the payment minus the fees and the ETH kept for network fees, but the reserve sat below the card, so its rows did not add up. It now sits in the card between the costs and that amount, and the reserve note says it comes out of the payment in both languages. --- apps/stocks/src/components/FeeSummary.jsx | 2 +- apps/stocks/src/components/PurchasePreview.jsx | 2 +- apps/stocks/src/styles.css | 1 + apps/stocks/tests/purchase-preview-ui.test.mjs | 3 +++ 4 files changed, 6 insertions(+), 2 deletions(-) diff --git a/apps/stocks/src/components/FeeSummary.jsx b/apps/stocks/src/components/FeeSummary.jsx index 529a80825..b085f9292 100644 --- a/apps/stocks/src/components/FeeSummary.jsx +++ b/apps/stocks/src/components/FeeSummary.jsx @@ -55,7 +55,7 @@ export function ReserveBalance({ amount, currency = "BRL", locale = "pt-BR" }) { if (!(amount > 0)) return null; const en = locale === "en"; return
-

{en ? "Balance for future network fees" : "Saldo para futuras taxas de rede"}{en ? "It stays yours, in your wallet. It is not a fee charged." : "Continua seu, na sua carteira. Não é uma taxa cobrada."}
{en ? "Held as ETH on Robinhood Chain." : "Reservado como ETH na Robinhood Chain."}

+

{en ? "Balance for future network fees" : "Saldo para futuras taxas de rede"}{en ? "Taken from your payment, it stays yours, in your wallet. It is not a fee charged." : "Sai do valor pago e continua seu, na sua carteira. Não é uma taxa cobrada."}
{en ? "Held as ETH on Robinhood Chain." : "Reservado como ETH na Robinhood Chain."}

{formatCostAmount(amount, currency, locale)}
; } diff --git a/apps/stocks/src/components/PurchasePreview.jsx b/apps/stocks/src/components/PurchasePreview.jsx index 35a388696..12c2493e5 100644 --- a/apps/stocks/src/components/PurchasePreview.jsx +++ b/apps/stocks/src/components/PurchasePreview.jsx @@ -43,9 +43,9 @@ export function PurchasePreview({ prices = {}, locale = "pt-BR", symbol = null,
{en ? "You pay" : "Você paga"}
{money(preview.amount)}
+
{en ? "Amount used to buy your tokens" : "Valor usado para comprar seus tokens"}
{money(preview.net)}≈ {en ? formatTokensEn(preview.tokenAmount) : formatTokenAmount(preview.tokenAmount)} {en ? `${token.symbol} tokens` : `tokens ${token.symbol}`}
- {method === "usdc" &&

{en ? "Your sending wallet or exchange may charge separately." : "A carteira ou corretora de origem pode cobrar à parte."}

}
} {error &&

{error}

} diff --git a/apps/stocks/src/styles.css b/apps/stocks/src/styles.css index a69b795cb..f6ab3a2d1 100644 --- a/apps/stocks/src/styles.css +++ b/apps/stocks/src/styles.css @@ -867,6 +867,7 @@ button.payment-choice { cursor: pointer; } .reserve-balance p { min-width: 0; } .reserve-balance small { display: block; color: var(--text-muted); margin-top: 4px; font-size: 12px; line-height: 1.5; } .reserve-balance strong { flex-shrink: 0; max-width: 42%; font-family: var(--font-numeric); text-align: right; font-size: 14px; } +.fee-card > .reserve-balance { border-radius: 0; border-bottom: 1px solid var(--hairline); } .preview-result .fee-card .breakdown .is-total { display: block; padding: 16px; } .preview-result .fee-card .breakdown .is-total dd { margin-top: 8px; text-align: left; font-size: 25px; } .preview-result .fee-card .breakdown .is-total dd small { font-family: var(--font-body); font-size: 14px; } diff --git a/apps/stocks/tests/purchase-preview-ui.test.mjs b/apps/stocks/tests/purchase-preview-ui.test.mjs index aad56e4b4..f7adc6f5f 100644 --- a/apps/stocks/tests/purchase-preview-ui.test.mjs +++ b/apps/stocks/tests/purchase-preview-ui.test.mjs @@ -36,6 +36,9 @@ test("anonymous Pix preview needs no sign-in and hands off only the selected amo assert.match(document.querySelector(".fee-summary > summary").textContent.replace(/\u00a0/g, " "), /R\$ 2,40/); assert.match(document.querySelector(".reserve-balance").textContent.replace(/\u00a0/g, " "), /R\$ 0,71/); assert.match(document.querySelector(".fee-card .is-total").textContent.replace(/\u00a0/g, " "), /R\$ 96,89/); + // R$ 100 paid \u2212 R$ 2,40 costs \u2212 R$ 0,71 kept as ETH = R$ 96,89 used: all three rows sit in the card, in that order. + assert.deepEqual([...document.querySelector(".fee-card").children].map(child => child.className), ["breakdown", "fee-summary", "reserve-balance", "breakdown"]); + assert.match(document.querySelector(".fee-card .reserve-balance").textContent, /Sai do valor pago/); assert.equal(calls.length, 0); await act(async () => document.querySelector(".fee-summary > summary").click()); assert.equal(document.querySelector(".fee-summary").open, true); From 9629300da653ea49d0446266c02d31c5566d9c5a Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Tue, 17 Nov 2026 08:36:25 +0100 Subject: [PATCH 5/5] test(frontend): point the stocks browser checks at the fee summary verify-pilot-ui and verify-usdc-ui still looked for the removed provider cost table. They now check the fee groups, each cost line, the no-surcharge note and the separate reserve inside the open sheet, and the pilot check confirms that a sell's gross minus costs equals its payout. verify-usdc-ui also waited for an English hero heading that an earlier hero change replaced. Both pass at 1440, 390 and 320 px on a local demo. --- apps/stocks/scripts/verify-pilot-ui.mjs | 22 +++++++++++----------- apps/stocks/scripts/verify-usdc-ui.mjs | 11 ++++++----- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/apps/stocks/scripts/verify-pilot-ui.mjs b/apps/stocks/scripts/verify-pilot-ui.mjs index b8061e9f1..34e39ffb5 100644 --- a/apps/stocks/scripts/verify-pilot-ui.mjs +++ b/apps/stocks/scripts/verify-pilot-ui.mjs @@ -30,16 +30,12 @@ try { await page.goto(`${url}#/acao/NVDA?demoFlow=buy-quote`, { waitUntil: "networkidle" }); const generate = page.getByRole("button", { name: /Gerar Pix de/ }); await generate.waitFor({ timeout: 20_000 }); - const costs = page.locator(".provider-costs"); + const costs = page.locator(".sheet .fee-summary"); assert.equal(await costs.getAttribute("open"), null, "Cost details are available without crowding the review"); await costs.locator("summary").click(); - await costs.getByText("Rota direta · Relay + Uniswap", { exact: true }).waitFor(); - for (const provider of ["Avenia", "Nabla", "Relay", "Uniswap", "Vortex", "Redes"]) { - assert.equal(await costs.getByText(provider, { exact: true }).count(), 1, `${provider} provider shown`); - } - const ownFee = costs.locator('[data-cost-id="product"]'); - assert.match(await ownFee.innerText(), /0,00/); - assert.match(await ownFee.innerText(), /0 bps/); + for (const group of ["payment", "tradeDelivery", "service"]) assert.equal(await costs.locator(`[data-fee-group="${group}"]`).count(), 1, `${group} group shown`); + for (const id of ["ramp", "conversion", "bridge", "swap", "network", "vortex"]) assert.equal(await costs.locator(`[data-cost-id="${id}"]`).count(), 1, `${id} cost shown once`); + await costs.getByText(/não adiciona outra taxa/).waitFor(); assert.ok(await page.evaluate(() => document.querySelector(".sheet").scrollWidth <= document.querySelector(".sheet").clientWidth + 1), "Quote detail overflows its modal"); await page.evaluate(() => { document.querySelector(".sheet").scrollTop = 0; }); await page.screenshot({ path: `${output}/buy-providers-${viewport.width}.png` }); @@ -59,10 +55,14 @@ try { await page.locator(".activity-row").filter({ hasText: /Compra · NVDA/ }).first().waitFor(); await page.goto(`${url}#/acao/NVDA?demoFlow=sell-reserve-used`, { waitUntil: "networkidle" }); await page.getByRole("button", { name: "Confirmar venda", exact: true }).waitFor(); - const sellCosts = page.locator(".provider-costs"); + const sellCosts = page.locator(".sheet .fee-summary"); await sellCosts.locator("summary").click(); - assert.match(await sellCosts.locator("dl > div").first().innerText(), /Uniswap/); - assert.match(await sellCosts.locator('[data-cost-id="product"]').innerText(), /0 bps/); + assert.deepEqual(await sellCosts.locator("[data-fee-group]").evaluateAll((groups) => groups.map((group) => group.dataset.feeGroup)), ["payment", "tradeDelivery", "service"]); + await sellCosts.getByText(/não adiciona outra taxa/).waitFor(); + const brl = async (locator) => Number((await locator.innerText()).replace(/\s/g, " ").match(/R\$ ([\d.]+,\d{2})/)[1].replace(/\./g, "").replace(",", ".")); + const gross = await brl(page.locator(".sheet .fee-card .breakdown > div", { hasText: "Valor bruto" }).locator("dd")); + const received = await brl(page.locator(".sheet .fee-card .is-total dd")); + assert.ok(Math.abs(gross - await brl(sellCosts.locator(".fee-summary__amount")) - received) < 0.011, "Valor bruto − custos = Você recebe no Pix"); await page.evaluate(() => { document.querySelector(".sheet").scrollTop = 0; }); await page.screenshot({ path: `${output}/sell-providers-${viewport.width}.png` }); assert.deepEqual(errors, [], "Runtime errors"); diff --git a/apps/stocks/scripts/verify-usdc-ui.mjs b/apps/stocks/scripts/verify-usdc-ui.mjs index 6fa9ef1cb..dbdfcec9b 100644 --- a/apps/stocks/scripts/verify-usdc-ui.mjs +++ b/apps/stocks/scripts/verify-usdc-ui.mjs @@ -14,7 +14,7 @@ try { page.on("pageerror", e => errors.push(e.message)); await page.route(/\/api\/(production|staging)|api\.vortexfinance|api\.relay\.link|api\.coingecko\.com|economia\.awesomeapi/, async r => { forbidden.push(r.request().url()); await r.abort(); }); await page.goto(`${origin}/en/stocks/`,{waitUntil:"networkidle"}); - await page.getByRole("heading", {name:/Big companies/}).waitFor(); + await page.getByRole("heading", {name:/fair fees/, level:1}).waitFor(); assert.equal(await page.locator("html").getAttribute("lang"),"en"); assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth+1),"English landing overflow"); await page.screenshot({path:`${output}/english-landing-${viewport.width}.png`,fullPage:true}); @@ -25,13 +25,14 @@ try { await preview.getByRole("button", {name:"Continue with USDC",exact:true}).click(); await page.getByRole("button",{name:"Continue with Google"}).click(); await page.getByRole("button",{name:"Continue to USDC payment"}).waitFor(); - await page.locator(".provider-costs summary").click(); + await page.locator(".sheet .fee-summary summary").click(); assert.ok(await page.evaluate(() => document.querySelector(".sheet").scrollWidth <= document.querySelector(".sheet").clientWidth + 1), "USDC quote overflows viewport"); - for(const name of ["Relay","Uniswap","Vortex","Networks","ETH reserve"]) assert.equal(await page.locator(".provider-costs").getByText(name,{exact:true}).count(),1); - assert.match(await page.locator('[data-cost-id="product"]').innerText(),/0.00 USDC/); + for(const id of ["swap","bridge","network","vortex"]) assert.equal(await page.locator(`.sheet .fee-summary [data-cost-id="${id}"]`).count(),1,`${id} cost shown once`); + assert.equal(await page.locator(".sheet .reserve-balance").count(),1,"ETH reserve shown apart from the fees"); + await page.locator(".sheet .fee-summary").getByText(/adds no extra fee/).waitFor(); assert.equal(await page.getByRole("button",{name:"Continue to USDC payment"}).isEnabled(),false); await page.screenshot({path:`${output}/usdc-quote-${viewport.width}.png`}); - await page.locator(".provider-costs summary").click(); + await page.locator(".sheet .fee-summary summary").click(); await page.getByRole("checkbox",{name:/I approve this amount/}).check(); await page.getByRole("button",{name:"Continue to USDC payment"}).click(); await page.getByRole("img",{name:"Simulation: no USDC payment address"}).waitFor();