From 743222e59689c442b1ca73dab226e604539fc79e Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 16 Nov 2026 18:30:27 +0100 Subject: [PATCH 1/3] fix(frontend): ask pix or usdc before the stocks pix steps With both methods open, a signed-in user's Comprar and Vender opened the Pix flow, which offered USDC only as a small secondary option. A USDC tester continued on Pix and ended up in the Pix identity check, which a Base USDC order does not need. Both flows now start on an explicit Pix-or-USDC choice, as Gold's picker does, unless the user already chose Pix in the preview or is resuming an operation. --- apps/stocks/CLAUDE.md | 2 +- apps/stocks/src/flows/BuyFlow.jsx | 16 +++++----- apps/stocks/src/flows/SellFlow.jsx | 16 +++++----- apps/stocks/src/flows/parts.jsx | 14 +++++++++ apps/stocks/tests/flow-ui.test.mjs | 50 ++++++++++++++++++++++++++++++ 5 files changed, 81 insertions(+), 17 deletions(-) diff --git a/apps/stocks/CLAUDE.md b/apps/stocks/CLAUDE.md index 4fb49e73d..222332a8e 100644 --- a/apps/stocks/CLAUDE.md +++ b/apps/stocks/CLAUDE.md @@ -123,7 +123,7 @@ the sibling of `apps/gold`. shows provider rows, Vortex as the only own revenue fee and an explicit zero Stocks 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. +- **Base USDC:** English `/en/stocks/` and the Brazil USDC choice ship in all builds. With USDC checkout on, the Brazil buy and sell flows open on a Pix-or-USDC choice (`MethodStep` in `parts.jsx`, as Gold's picker), so a USDC order never reaches the Pix-only KYC, Pix key or Pix payment steps; a Pix amount carried from the preview or a resumed operation skips it. 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. - **Maintenance:** the live adapter reads existing public `/v1/maintenance/status` before registration, start and each new wallet broadcast. `PixStep` also polls while visible and invalidates a clear result on banking-app/background transitions. Unknown, paused, disabled and expired states hide diff --git a/apps/stocks/src/flows/BuyFlow.jsx b/apps/stocks/src/flows/BuyFlow.jsx index 0a2961a49..5ac4b92d7 100644 --- a/apps/stocks/src/flows/BuyFlow.jsx +++ b/apps/stocks/src/flows/BuyFlow.jsx @@ -1,5 +1,5 @@ // Buy flow: Gold's TransactionFlow state machine over the ramp adapter. -// amount -> (code) -> prepare: availability, quote, price guard, readiness -> (kyc) -> confirm +// (method: Pix, or leave for the USDC checkout) -> amount -> (code) -> prepare: availability, quote, price guard, readiness -> (kyc) -> confirm // confirm -> re-quote if it expires within 15 s, else register -> pix -> start -> processing // processing -> success | issue; resume: getRamp -> success | issue | pix | processing | code import { useEffect, useRef, useState } from "react"; @@ -17,13 +17,13 @@ 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 { 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 { FlowIssue, FlowProgress, GuardCard, KYC_IN_REVIEW_PT, KycStep, MethodStep, OtpStep, POLL_RESTART_MS, ProcessingSteps, QuoteTimer, SuccessSeal, TokenSummary, Waiting, errorMessage, needsCode, unavailableMessage } from "./parts.jsx"; import { PixStep } from "./PixStep.jsx"; const PROGRESS = ["Valor", "Segurança", "Revisão", "Pix"]; -const PROGRESS_INDEX = { amount: 0, otp: 1, kyc: 1, confirm: 2, pix: 3 }; +const PROGRESS_INDEX = { method: 0, amount: 0, otp: 1, kyc: 1, confirm: 2, pix: 3 }; -function AmountStep({ token, price, amount, setAmount, onNext, busy, error, onPayUsdc }) { +function AmountStep({ token, price, amount, setAmount, onNext, busy, error }) { const valid = validBuyAmount(amount); const estimate = valid ? estimateTokensForBrl(amount, price?.brl) : null; const now = new Date(); @@ -32,7 +32,6 @@ function AmountStep({ token, price, amount, setAmount, onNext, busy, error, onPa return (
- {onPayUsdc &&
Pix · BrasilEm reais, pelo seu banco
}
@@ -93,7 +92,7 @@ export default function BuyFlow({ token, auth, runtime, market, flags, resume: r const [resume, setResume] = useState(resumed); // null again once the resumed operation is given up const wallet = auth.address; const privyDid = auth.user?.privyDid; - const [step, setStep] = useState(resume ? "resuming" : "amount"); + const [step, setStep] = useState(resume ? "resuming" : onPayUsdc && initialAmount == null && !demoQuote ? "method" : "amount"); const [amount, setAmount] = useState(validBuyAmount(initialAmount) ? String(initialAmount) : String(DEFAULT_BUY)); const [email, setEmail] = useState(auth.user?.email || ""); const [otp, setOtp] = useState(""); @@ -277,7 +276,8 @@ export default function BuyFlow({ token, auth, runtime, market, flags, resume: r return ( : null}> - {step === "amount" && } + {step === "method" && setStep("amount")} onUsdc={onPayUsdc} />} + {step === "amount" && } {step === "otp" && } {step === "kyc" && { setNotice(""); setStep("confirm"); }} />} {step === "confirm" && quote && } @@ -306,7 +306,7 @@ export default function BuyFlow({ token, auth, runtime, market, flags, resume: r )} {step === "issue" && } {operationId && step !== "success" &&

Código da operação: {operationId}

} - {["otp", "kyc", "confirm"].includes(step) && !busy && !ramp &&
} + {(["otp", "kyc", "confirm"].includes(step) || (step === "amount" && onPayUsdc)) && !busy && !ramp &&
} {step === "amount" &&

}
); diff --git a/apps/stocks/src/flows/SellFlow.jsx b/apps/stocks/src/flows/SellFlow.jsx index a8e2c31ba..417873f35 100644 --- a/apps/stocks/src/flows/SellFlow.jsx +++ b/apps/stocks/src/flows/SellFlow.jsx @@ -1,5 +1,5 @@ // Sell flow: Gold's SellFlow over the ramp adapter. -// amount (tokens + Pix key) -> (code) -> prepare: availability, wallet on Robinhood Chain, balance +// (method: Pix, or leave for the USDC checkout) -> amount (tokens + Pix key) -> (code) -> prepare: availability, wallet on Robinhood Chain, balance // and ETH, quote, price guard, readiness -> (kyc) -> review -> register + sign -> start -> processing // sign (resume): resumeSell -> start; processing -> success | issue import { useEffect, useRef, useState } from "react"; @@ -18,10 +18,10 @@ import { checkQuotePrice } from "../lib/price-guard.js"; import { freshPauseReason } from "../lib/ramp-contract.js"; import { quoteNeedsRefresh, stepAfterCode, validSellAmount } from "../lib/purchase-options.js"; import { formatTokenAmount, formatTokensPt, maxSellAmount, tokensToWei } from "../lib/token.js"; -import { FlowIssue, FlowProgress, GuardCard, KYC_IN_REVIEW_PT, KycStep, OtpStep, POLL_RESTART_MS, ProcessingSteps, QuoteTimer, StepIntro, SuccessSeal, TokenSummary, Waiting, errorMessage, needsCode, unavailableMessage } from "./parts.jsx"; +import { FlowIssue, FlowProgress, GuardCard, KYC_IN_REVIEW_PT, KycStep, MethodStep, OtpStep, POLL_RESTART_MS, ProcessingSteps, QuoteTimer, StepIntro, SuccessSeal, TokenSummary, Waiting, errorMessage, needsCode, unavailableMessage } from "./parts.jsx"; const PROGRESS = ["Quantidade", "Segurança", "Revisão", "Confirmação"]; -const PROGRESS_INDEX = { amount: 0, otp: 1, kyc: 1, review: 2, sign: 3 }; +const PROGRESS_INDEX = { method: 0, amount: 0, otp: 1, kyc: 1, review: 2, sign: 3 }; const toInput = (decimal) => String(decimal).replace(".", ","); @@ -41,7 +41,7 @@ function WalletAddress({ address }) { ); } -function AmountStep({ token, price, raw, amount, setAmount, pixKey, setPixKey, onNext, busy, error, onSellUsdc }) { +function AmountStep({ token, price, raw, amount, setAmount, pixKey, setPixKey, onNext, busy, error }) { const valid = validSellAmount(amount, raw) && pixKey.trim().length >= 5; let estimate = null; try { estimate = price?.brl && tokensToWei(amount) > 0n ? Number(String(amount).replace(",", ".")) * price.brl : null; } catch { estimate = null; } @@ -50,7 +50,6 @@ function AmountStep({ token, price, raw, amount, setAmount, pixKey, setPixKey, o return (
- {onSellUsdc && }
@@ -114,7 +113,7 @@ export default function SellFlow({ token, auth, runtime, market, flags, holdingR const { adapter, verification } = runtime; const wallet = auth.address; const privyDid = auth.user?.privyDid; - const [step, setStep] = useState(resume ? "resuming" : "amount"); + const [step, setStep] = useState(resume ? "resuming" : onSellUsdc && !demoReserveUsed ? "method" : "amount"); const [raw, setRaw] = useState(() => BigInt(holdingRaw || 0n)); const [amount, setAmount] = useState(() => (demoReserveUsed ? toInput(maxSellAmount(holdingRaw || 0n)) : "")); const [pixKey, setPixKey] = useState(() => (demoReserveUsed ? auth.user?.email || "" : "")); @@ -306,7 +305,8 @@ export default function SellFlow({ token, auth, runtime, market, flags, holdingR return ( : null}> - {step === "amount" && } + {step === "method" && setStep("amount")} onUsdc={onSellUsdc} />} + {step === "amount" && } {step === "otp" && } {step === "kyc" && { setNotice(""); setStep("review"); }} />} {step === "review" && quote && } @@ -342,7 +342,7 @@ export default function SellFlow({ token, auth, runtime, market, flags, holdingR )} {step === "issue" && { setError(""); run(loadExisting); } : null} onClose={onClose} />} {operationId && step !== "success" &&

Código da operação: {operationId}

} - {["otp", "kyc", "review"].includes(step) && !busy && !ramp &&
} + {(["otp", "kyc", "review"].includes(step) || (step === "amount" && onSellUsdc)) && !busy && !ramp &&
}
); } diff --git a/apps/stocks/src/flows/parts.jsx b/apps/stocks/src/flows/parts.jsx index cb43327f7..f7b8fcfdc 100644 --- a/apps/stocks/src/flows/parts.jsx +++ b/apps/stocks/src/flows/parts.jsx @@ -84,6 +84,20 @@ export function StepIntro({ icon: Icon, title, children }) { return
  • {title}{children}
; } +/** Pix or Base USDC, chosen before any Pix step (as Gold does): the Pix-only identity check never meets a USDC order. */ +export function MethodStep({ direction, onPix, onUsdc }) { + const buy = direction === "BUY"; + return ( +
+

{buy ? "Como deseja pagar?" : "Como deseja receber?"}

+
+ + +
+
+ ); +} + export function OtpStep({ email, setEmail, otp, setOtp, sent, onSend, onVerify, busy, error, demoCode }) { return (
diff --git a/apps/stocks/tests/flow-ui.test.mjs b/apps/stocks/tests/flow-ui.test.mjs index 49f60d0bf..36d680945 100644 --- a/apps/stocks/tests/flow-ui.test.mjs +++ b/apps/stocks/tests/flow-ui.test.mjs @@ -125,6 +125,38 @@ test("a sell with no KYC started opens the form", () => harness(async (s) => { assert.match(s.text(), KYC_FORM); })); +// With USDC checkout on, the Pix flow is never the default: a USDC order must not reach the Pix KYC. +const PIX_BUY = "Pix · Brasil Em reais, pelo seu banco"; +const USDC_BUY = "USDC · Base Da sua carteira ou exchange"; + +test("with USDC on, a buy asks Pix or USDC before any Pix step", () => harness(async (s) => { + let usdc = 0; + await s.render(createElement(BuyFlow, { ...fixtures(notReady("not_started")), onPayUsdc: () => { usdc += 1; } })); + assert.match(s.text(), /Como deseja pagar\?/); + assert.doesNotMatch(s.text(), /Quanto deseja investir\?/); + await s.click(USDC_BUY); + assert.equal(usdc, 1); + await s.click(PIX_BUY); + assert.match(s.text(), /Quanto deseja investir\?/); + await s.click("Voltar"); + assert.match(s.text(), /Como deseja pagar\?/); + await s.click(PIX_BUY); + await s.click("Continuar"); + assert.match(s.text(), KYC_FORM, "Pix keeps its KYC"); +})); + +test("with USDC on, a sell asks Pix or USDC before the Pix key", () => harness(async (s) => { + let usdc = 0; + await s.render(createElement(SellFlow, { ...fixtures(notReady("not_started")), holdingRaw: 10n ** 18n, onSellUsdc: () => { usdc += 1; } })); + assert.match(s.text(), /Como deseja receber\?/); + assert.equal(document.querySelector("#sell-amount"), null); + await s.click("USDC · Base Na sua carteira, na rede Base"); + assert.equal(usdc, 1); + await s.click("Pix · Brasil Em reais, na sua chave Pix"); + await sellAmount(s); + assert.match(s.text(), KYC_FORM, "Pix keeps its KYC"); +})); + // kyc.demo fills the form, so these reach the submit with no files and no Avenia window. function kycWith(submit) { const calls = { uploads: 0, submit: 0, poll: 0 }; @@ -587,10 +619,13 @@ const openBuyAmount = async (s, config) => { test("signed in, the buy offers USDC only outside a live build, and a saved USDC choice opens nothing live", () => withFetch(noNetwork, async () => { await harness(async (s) => { await openBuyAmount(s, DEMO); + await s.click("Voltar"); + assert.match(s.text(), /Como deseja pagar\?/); assert.match(s.text(), /USDC · Base/); }); await harness(async (s) => { await openBuyAmount(s, LIVE); + assert.ok(!s.has("Voltar"), "no method step to go back to"); assert.doesNotMatch(s.text(), /USDC · Base/); }); await harness(async (s) => { @@ -616,6 +651,21 @@ test("signed in with Pix off and USDC on, the stock page opens the USDC buy", () } finally { window.location.hash = "#/"; } }))); +// Regression: with both open, "Comprar" went straight to the Pix amount, and on to the Pix KYC. +test("signed in with Pix and USDC on, the stock page's Comprar asks how to pay and USDC opens the USDC buy", () => withFetch(noNetwork, () => harness(async (s) => { + const buyReady = () => [...document.querySelectorAll("button")].some((button) => button.textContent.trim() === "Comprar" && !button.disabled); + try { + window.location.hash = "#/acao/NVDA"; + await renderApp(s, DEMO, true); + for (let i = 0; i < 2000 && !buyReady(); i += 1) await s.wait(); + await s.click("Comprar"); + await untilText(s, /Como deseja pagar\?/); + assert.doesNotMatch(s.text(), /Quanto deseja investir\?/); + await s.click(USDC_BUY); + await untilText(s, /Comprar NVDA · USDC|Buy NVDA with USDC/); + } finally { window.location.hash = "#/"; } +}))); + test("a resumed record for a token this build no longer bundles still opens its operation", () => withFetch(noNetwork, () => harness(async (s) => { createRampStores({ simulated: true }).activeRamp.save({ rampId: "sim-delisted", walletAddress: WALLET, rampType: "BUY", stage: "registered", symbol: "DELISTED", inputAmount: 500, outputAmount: "0.5", createdAt: Date.now(), simulated: true }); try { From 0a1b8e60ede3eb90d33b8285903f45e43d197a0e Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 16 Nov 2026 20:24:00 +0100 Subject: [PATCH 2/3] fix(frontend): offer usdc in the stocks method step only where it is open The backend opens each Base USDC direction apart from Pix, but the Pix flows offered USDC whenever the checkout flag was on. With only USDC buys open, a seller could pick USDC and only learn after entering an amount that the route was unavailable. App now reads the live USDC listing once per runtime and passes the USDC handler to the buy or sell flow only when that direction is listed for the token (usdcOpen). An unread or failed listing offers Pix only; the simulated checkout stays open. LiveUsdcFlow still re-checks before every quote. --- apps/stocks/CLAUDE.md | 2 +- apps/stocks/src/App.jsx | 16 +++++++++++++--- apps/stocks/src/lib/detail-actions.js | 12 ++++++++++++ apps/stocks/tests/detail-actions.test.mjs | 13 ++++++++++++- 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/apps/stocks/CLAUDE.md b/apps/stocks/CLAUDE.md index 222332a8e..247742db9 100644 --- a/apps/stocks/CLAUDE.md +++ b/apps/stocks/CLAUDE.md @@ -123,7 +123,7 @@ the sibling of `apps/gold`. shows provider rows, Vortex as the only own revenue fee and an explicit zero Stocks 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. With USDC checkout on, the Brazil buy and sell flows open on a Pix-or-USDC choice (`MethodStep` in `parts.jsx`, as Gold's picker), so a USDC order never reaches the Pix-only KYC, Pix key or Pix payment steps; a Pix amount carried from the preview or a resumed operation skips it. 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. +- **Base USDC:** English `/en/stocks/` and the Brazil USDC choice ship in all builds. With USDC checkout on, the Brazil buy and sell flows open on a Pix-or-USDC choice (`MethodStep` in `parts.jsx`, as Gold's picker), so a USDC order never reaches the Pix-only KYC, Pix key or Pix payment steps; a Pix amount carried from the preview or a resumed operation skips it, and a live build offers USDC there only in a direction its USDC listing opens (`usdcOpen` in `detail-actions.js`). 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. - **Maintenance:** the live adapter reads existing public `/v1/maintenance/status` before registration, start and each new wallet broadcast. `PixStep` also polls while visible and invalidates a clear result on banking-app/background transitions. Unknown, paused, disabled and expired states hide diff --git a/apps/stocks/src/App.jsx b/apps/stocks/src/App.jsx index bfafd098b..712790dab 100644 --- a/apps/stocks/src/App.jsx +++ b/apps/stocks/src/App.jsx @@ -12,7 +12,7 @@ import { DEMO_USER } from "./DemoAuth.js"; import { WelcomeSheet } from "./components/Welcome.jsx"; import { useAvailability, useMarket, useNow, useOnline, usePendingRampRead, usePortfolio, useRuntime } from "./hooks.js"; import { DEMO_TOOLS, USDC_CHECKOUT } from "./lib/config.js"; -import { flowFor } from "./lib/detail-actions.js"; +import { flowFor, usdcOpen } from "./lib/detail-actions.js"; import { localHistoryRows, mergeHistory, ownedHistoryRows } from "./lib/history.js"; import { homeHash, parseHash, stockHash } from "./lib/routes.js"; import { findStock } from "./lib/stocks.js"; @@ -64,6 +64,16 @@ export function App({ auth, config }) { const [version, setVersion] = useState(0); const [serverRows, setServerRows] = useState(null); const [demoPlan, setDemoPlan] = useState(null); + // The live USDC listing: a Pix flow offers USDC (its method step) only where that direction is open. + // ponytail: read once per runtime; LiveUsdcFlow re-reads it before every quote, so a stale "open" still stops there. + const [usdcListing, setUsdcListing] = useState(null); + useEffect(() => { + if (!usdcCheckout || runtime?.usdc?.simulated !== false) return undefined; + let alive = true; + runtime.usdc.adapter.getAvailability().then((map) => { if (alive) setUsdcListing(map); }, () => {}); + return () => { alive = false; }; + }, [runtime, usdcCheckout]); + const offersUsdc = (symbol, direction) => usdcOpen({ checkout: usdcCheckout, live: runtime?.usdc?.simulated === false, listing: usdcListing, symbol, direction }); const intent = useRef(null); const welcome = useMemo(() => createWelcomeStore(), []); const refreshLocal = useCallback(() => setVersion((value) => value + 1), []); @@ -252,8 +262,8 @@ export function App({ auth, config }) { ? ( setModal(null)} />}> {modal.type === "usdc" ? : modal.type === "buy" - ? setModal({ type: "usdc", symbol: flowToken.symbol }) : undefined} /> - : setModal({ type: "usdc", symbol: flowToken.symbol, direction: "SELL" }) : undefined} resume={modal.resume ?? null} demoReserveUsed={modal.demoReserveUsed === true} onClose={closeFlow} onSettled={onSettled} />} + ? setModal({ type: "usdc", symbol: flowToken.symbol }) : undefined} /> + : setModal({ type: "usdc", symbol: flowToken.symbol, direction: "SELL" }) : undefined} resume={modal.resume ?? null} demoReserveUsed={modal.demoReserveUsed === true} onClose={closeFlow} onSettled={onSettled} />} ) : setModal(null)} error={runtimeError} />)} diff --git a/apps/stocks/src/lib/detail-actions.js b/apps/stocks/src/lib/detail-actions.js index af3bdc964..7a5bfd6c3 100644 --- a/apps/stocks/src/lib/detail-actions.js +++ b/apps/stocks/src/lib/detail-actions.js @@ -58,3 +58,15 @@ export function flowFor(request, pending) { if (pending.paymentMethod === "usdc") return { type: "usdc", symbol: pending.symbol || request.symbol, resume: pending }; return { type: pending.rampType === "SELL" ? "sell" : "buy", symbol: pending.symbol || request.symbol, resume: pending }; } + +/** + * Whether a Pix buy or sell also offers Base USDC (its method step). The backend opens each USDC + * direction apart from Pix (STOCKS_USDC_ENABLED_DIRECTIONS), so a live checkout needs that + * direction in its own listing; an unread or failed listing offers Pix only. The simulated checkout + * has no listing and is always open. + * @param {{ checkout:boolean, live:boolean, listing:Record|null, symbol:string, direction:"BUY"|"SELL" }} args + */ +export function usdcOpen({ checkout, live, listing, symbol, direction }) { + if (!checkout) return false; + return !live || Boolean(listing?.[symbol]?.[direction === "SELL" ? "sell" : "buy"]); +} diff --git a/apps/stocks/tests/detail-actions.test.mjs b/apps/stocks/tests/detail-actions.test.mjs index 66ed41153..d74d8f3b3 100644 --- a/apps/stocks/tests/detail-actions.test.mjs +++ b/apps/stocks/tests/detail-actions.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { detailActions, flowFor } from "../src/lib/detail-actions.js"; +import { detailActions, flowFor, usdcOpen } from "../src/lib/detail-actions.js"; import { uniformAvailability } from "../src/lib/ramp-contract.js"; import { STOCK_TOKENS } from "../src/lib/stocks.js"; @@ -95,3 +95,14 @@ test("signed in with Pix closed: USDC on Base stays open unless the issuer pause const halted = detailActions({ auth: signedIn, availability: paused, comingSoon: false, holding, symbol: "NVDA", usdc: true }); assert.deepEqual([halted.buy.disabled, halted.sell.disabled, halted.buy.usdc], [true, true, undefined]); }); + +test("a Pix flow offers USDC only in a direction the live USDC listing opens", () => { + const buyOnly = { NVDA: { buy: true, sell: false, reason: null } }; + const ask = (args) => usdcOpen({ checkout: true, live: true, listing: buyOnly, symbol: "NVDA", direction: "BUY", ...args }); + assert.equal(ask({}), true); + assert.equal(ask({ direction: "SELL" }), false, "USDC sell closed on the backend"); + assert.equal(ask({ symbol: "TSLA" }), false, "not listed"); + assert.equal(ask({ listing: null }), false, "unread or failed listing: Pix only"); + assert.equal(ask({ checkout: false }), false); + assert.equal(ask({ live: false, listing: null, direction: "SELL" }), true, "the simulated checkout has no listing"); +}); From 661c22b8d60cd72138f7b05b41b2905d9c7b7e83 Mon Sep 17 00:00:00 2001 From: Marcel Ebert Date: Mon, 16 Nov 2026 20:24:04 +0100 Subject: [PATCH 3/3] fix(frontend): label the stocks payout choice and test the method step paths The sell method step announced its group as "Forma de pagamento" under the heading "Como deseja receber?"; it is now "Forma de recebimento". Tests now cover going back from the sell amount to the choice, and that a resumed Pix operation and the buy-quote and sell-reserve-used demo links skip it. The stock-page regression test asserts that "Comprar" became enabled before clicking it, so a pending operation left by another test fails with a clear message. --- apps/stocks/src/flows/parts.jsx | 2 +- apps/stocks/tests/flow-ui.test.mjs | 23 +++++++++++++++++++++++ 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/apps/stocks/src/flows/parts.jsx b/apps/stocks/src/flows/parts.jsx index f7b8fcfdc..6f0c2ac5e 100644 --- a/apps/stocks/src/flows/parts.jsx +++ b/apps/stocks/src/flows/parts.jsx @@ -90,7 +90,7 @@ export function MethodStep({ direction, onPix, onUsdc }) { return (

{buy ? "Como deseja pagar?" : "Como deseja receber?"}

-
+
diff --git a/apps/stocks/tests/flow-ui.test.mjs b/apps/stocks/tests/flow-ui.test.mjs index 36d680945..76496b510 100644 --- a/apps/stocks/tests/flow-ui.test.mjs +++ b/apps/stocks/tests/flow-ui.test.mjs @@ -149,10 +149,14 @@ test("with USDC on, a sell asks Pix or USDC before the Pix key", () => harness(a let usdc = 0; await s.render(createElement(SellFlow, { ...fixtures(notReady("not_started")), holdingRaw: 10n ** 18n, onSellUsdc: () => { usdc += 1; } })); assert.match(s.text(), /Como deseja receber\?/); + assert.ok(document.querySelector('[role="group"][aria-label="Forma de recebimento"]'), "a payout, not a payment"); assert.equal(document.querySelector("#sell-amount"), null); await s.click("USDC · Base Na sua carteira, na rede Base"); assert.equal(usdc, 1); await s.click("Pix · Brasil Em reais, na sua chave Pix"); + await s.click("Voltar"); + assert.match(s.text(), /Como deseja receber\?/); + await s.click("Pix · Brasil Em reais, na sua chave Pix"); await sellAmount(s); assert.match(s.text(), KYC_FORM, "Pix keeps its KYC"); })); @@ -222,6 +226,24 @@ function resumed({ ramp, stage = "registered", adapter = {}, verification }) { } const initial = (overrides = {}) => ({ id: "ramp-1", currentPhase: "initial", classification: "awaiting_payment", brlAmount: "500", tokenAmount: "0.5", depositQrCode: "pix-code-fake-test-only", startDeadline: Date.now() + 600_000, ...overrides }); +test("with USDC on, a resumed Pix operation and the demo deep links skip the method step", async () => { + await harness(async (s) => { + const { props } = resumed({ ramp: initial() }); + await s.render(createElement(BuyFlow, { ...props, onPayUsdc: () => {} })); + await s.wait(); + assert.match(s.text(), /Código da operação/); + assert.doesNotMatch(s.text(), /Como deseja pagar\?/, "a resumed Pix operation never offers USDC"); + }); + await harness(async (s) => { + await s.render(createElement(BuyFlow, { ...fixtures(approved), demoQuote: true, onPayUsdc: () => {} })); + assert.doesNotMatch(s.text(), /Como deseja pagar\?/, "buy-quote"); + }); + await harness(async (s) => { + await s.render(createElement(SellFlow, { ...fixtures(approved), holdingRaw: 10n ** 18n, demoReserveUsed: true, onSellUsdc: () => {} })); + assert.doesNotMatch(s.text(), /Como deseja receber\?/, "sell-reserve-used"); + }); +}); + test("an expired Pix says a paid one continues, and offers a way out that goes back to the amount", () => harness(async (s) => { const { calls, props } = resumed({ ramp: initial({ startDeadline: Date.now() - 1_000 }) }); await s.render(createElement(BuyFlow, props)); @@ -658,6 +680,7 @@ test("signed in with Pix and USDC on, the stock page's Comprar asks how to pay a window.location.hash = "#/acao/NVDA"; await renderApp(s, DEMO, true); for (let i = 0; i < 2000 && !buyReady(); i += 1) await s.wait(); + assert.ok(buyReady(), "the stock page's Comprar is enabled (no earlier operation left pending)"); await s.click("Comprar"); await untilText(s, /Como deseja pagar\?/); assert.doesNotMatch(s.text(), /Quanto deseja investir\?/);