Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/stocks/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
7 changes: 4 additions & 3 deletions apps/stocks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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.

Expand Down
22 changes: 11 additions & 11 deletions apps/stocks/scripts/verify-pilot-ui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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` });
Expand All @@ -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");
Expand Down
11 changes: 6 additions & 5 deletions apps/stocks/scripts/verify-usdc-ui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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});
Expand All @@ -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();
Expand Down
61 changes: 61 additions & 0 deletions apps/stocks/src/components/FeeSummary.jsx
Original file line number Diff line number Diff line change
@@ -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 <details className="fee-summary">
<summary>
<span className="fee-summary__label">{title}, {sell ? deducted : included}</span>
<span className="fee-summary__value">
<span className="fee-summary__amount">{money(model.amount)}{percent && <small> ({percent})</small>}</span>
<span className="fee-summary__toggle"><span className="fee-summary__show">{t("Ver detalhes", "Show details")}</span><span className="fee-summary__hide">{t("Ocultar detalhes", "Hide details")}</span></span>
</span>
</summary>
<div className="fee-summary__body">
{model.groups.map(group => <section className="fee-summary__group" key={group.id} data-fee-group={group.id}>
<h3><span>{groups[group.id]}</span><span>{money(group.amount)}</span></h3>
{group.items.length === 1 ? <p className="fee-summary__note" data-cost-id={group.items[0].id}>{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")}</>}</p> : <dl>{group.items.map(item => <div key={item.id} data-cost-id={item.id}>
<dt>{items[item.id][0]} <small>{items[item.id][1]}{item.includedIn === "rate" && <> · {t("já refletido no preço", "already reflected in the price")}</>}</small></dt>
<dd>{money(item.amount)}</dd>
</div>)}</dl>}
</section>)}
<p className="fee-summary__note">{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.`)}</p>
{!model.complete && <p className="fee-summary__note" role="note">{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.")}</p>}
{model.hasPriceEffects && <p className="fee-summary__note">{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.")}</p>}
{Number.isFinite(Number(subsidy?.amountFiat)) && Number(subsidy?.amountFiat) > 0 && <p className="fee-summary__note" data-cost-id="subsidy">{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.")}</p>}
{illustrative && <p className="fee-summary__note">{t("Valores ilustrativos, não tarifas atuais dos provedores.", "Illustrative amounts, not current provider tariffs.")}</p>}
</div>
</details>;
}

export function ReserveBalance({ amount, currency = "BRL", locale = "pt-BR" }) {
if (!(amount > 0)) return null;
const en = locale === "en";
return <div className="reserve-balance" data-cost-id="reserve">
<p><b>{en ? "Balance for future network fees" : "Saldo para futuras taxas de rede"}</b><small>{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."}<br />{en ? "Held as ETH on Robinhood Chain." : "Reservado como ETH na Robinhood Chain."}</small></p>
<strong>{formatCostAmount(amount, currency, locale)}</strong>
</div>;
}
Loading
Loading