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
2 changes: 1 addition & 1 deletion apps/stocks/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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, 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
Expand Down
16 changes: 13 additions & 3 deletions apps/stocks/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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), []);
Expand Down Expand Up @@ -252,8 +262,8 @@ export function App({ auth, config }) {
? (
<Suspense fallback={<FlowLoading onClose={() => setModal(null)} />}>
{modal.type === "usdc" ? <UsdcFlow key={modal.resume?.rampId || flowToken.symbol} token={flowToken} auth={auth} runtime={runtime} market={market} direction={modal.resume?.rampType || modal.direction || "BUY"} resume={modal.resume} initialAmount={modal.initialAmount} onClose={closeFlow} onSettled={onSettled} /> : modal.type === "buy"
? <BuyFlow key={modal.resume?.rampId || flowToken.symbol} token={flowToken} auth={auth} runtime={runtime} market={market} flags={portfolio.flags} resume={modal.resume ?? null} initialAmount={modal.initialAmount} demoQuote={modal.demoQuote === true} onClose={closeFlow} onSettled={onSettled} onPayUsdc={usdcCheckout ? () => setModal({ type: "usdc", symbol: flowToken.symbol }) : undefined} />
: <SellFlow key={modal.resume?.rampId || flowToken.symbol} token={flowToken} auth={auth} runtime={runtime} market={market} flags={portfolio.flags} holdingRaw={holding?.raw ?? 0n} onSellUsdc={usdcCheckout ? () => setModal({ type: "usdc", symbol: flowToken.symbol, direction: "SELL" }) : undefined} resume={modal.resume ?? null} demoReserveUsed={modal.demoReserveUsed === true} onClose={closeFlow} onSettled={onSettled} />}
? <BuyFlow key={modal.resume?.rampId || flowToken.symbol} token={flowToken} auth={auth} runtime={runtime} market={market} flags={portfolio.flags} resume={modal.resume ?? null} initialAmount={modal.initialAmount} demoQuote={modal.demoQuote === true} onClose={closeFlow} onSettled={onSettled} onPayUsdc={offersUsdc(flowToken.symbol, "BUY") ? () => setModal({ type: "usdc", symbol: flowToken.symbol }) : undefined} />
: <SellFlow key={modal.resume?.rampId || flowToken.symbol} token={flowToken} auth={auth} runtime={runtime} market={market} flags={portfolio.flags} holdingRaw={holding?.raw ?? 0n} onSellUsdc={offersUsdc(flowToken.symbol, "SELL") ? () => setModal({ type: "usdc", symbol: flowToken.symbol, direction: "SELL" }) : undefined} resume={modal.resume ?? null} demoReserveUsed={modal.demoReserveUsed === true} onClose={closeFlow} onSettled={onSettled} />}
</Suspense>
)
: <FlowLoading onClose={() => setModal(null)} error={runtimeError} />)}
Expand Down
16 changes: 8 additions & 8 deletions apps/stocks/src/flows/BuyFlow.jsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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();
Expand All @@ -32,7 +32,6 @@ function AmountStep({ token, price, amount, setAmount, onNext, busy, error, onPa
return (
<div className="flow-section">
<TokenSummary token={token} price={price} />
{onPayUsdc && <div className="payment-methods" role="group" aria-label="Forma de pagamento"><div className="payment-choice" aria-current="true"><b>Pix · Brasil</b><span>Em reais, pelo seu banco</span></div><button type="button" className="payment-choice" onClick={onPayUsdc}><b>USDC · Base</b><span>Wallet ou exchange · English checkout</span></button></div>}
<div>
<label className="field-label" htmlFor="buy-amount">Quanto deseja investir?</label>
<div className="amount-input">
Expand Down Expand Up @@ -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("");
Expand Down Expand Up @@ -277,7 +276,8 @@ export default function BuyFlow({ token, auth, runtime, market, flags, resume: r

return (
<Modal title={title} onClose={onClose} wide closeDisabled={closeDisabled} stepKey={step} headerExtra={progress != null ? <FlowProgress labels={PROGRESS} current={progress} /> : null}>
{step === "amount" && <AmountStep token={token} price={price} amount={amount} setAmount={setAmount} onNext={continueFromAmount} busy={busy} error={error} onPayUsdc={onPayUsdc} />}
{step === "method" && <MethodStep direction="BUY" onPix={() => setStep("amount")} onUsdc={onPayUsdc} />}
{step === "amount" && <AmountStep token={token} price={price} amount={amount} setAmount={setAmount} onNext={continueFromAmount} busy={busy} error={error} />}
{step === "otp" && <OtpStep email={email} setEmail={setEmail} otp={otp} setOtp={setOtp} sent={otpSent} onSend={sendOtp} onVerify={verifyOtp} busy={busy} error={error} demoCode={verification.demoCode} />}
{step === "kyc" && <KycStep kyc={runtime.kyc} quote={quote} email={email} initialName={auth.user?.name} onApproved={() => { setNotice(""); setStep("confirm"); }} />}
{step === "confirm" && quote && <ConfirmStep key={quote.id} token={token} quote={quote} guard={guard} reference={reference} multiplierWei={multiplierWei} onConfirm={generatePix} onRefresh={refreshQuote} busy={busy} error={error} notice={notice} />}
Expand Down Expand Up @@ -306,7 +306,7 @@ export default function BuyFlow({ token, auth, runtime, market, flags, resume: r
)}
{step === "issue" && <FlowIssue message={error} onRetry={ramp?.classification === "failure" ? null : retry} onClose={onClose} />}
{operationId && step !== "success" && <p className="op-ref">Código da operação: <code>{operationId}</code></p>}
{["otp", "kyc", "confirm"].includes(step) && !busy && !ramp && <div className="flow-foot" style={{ marginTop: 8 }}><button className="back-button" type="button" onClick={() => { setError(""); setStep("amount"); }}><ArrowLeft size={16} aria-hidden="true" /> Voltar</button></div>}
{(["otp", "kyc", "confirm"].includes(step) || (step === "amount" && onPayUsdc)) && !busy && !ramp && <div className="flow-foot" style={{ marginTop: 8 }}><button className="back-button" type="button" onClick={() => { setError(""); setStep(step === "amount" ? "method" : "amount"); }}><ArrowLeft size={16} aria-hidden="true" /> Voltar</button></div>}
{step === "amount" && <p className="legal-note" style={{ marginTop: 16 }}><Info size={14} aria-hidden="true" style={{ display: "inline", verticalAlign: "-2px" }} /> Você recebe um Stock Token, não a ação. O custo total aparece antes do Pix.</p>}
</Modal>
);
Expand Down
16 changes: 8 additions & 8 deletions apps/stocks/src/flows/SellFlow.jsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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(".", ",");

Expand All @@ -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; }
Expand All @@ -50,7 +50,6 @@ function AmountStep({ token, price, raw, amount, setAmount, pixKey, setPixKey, o
return (
<div className="flow-section">
<TokenSummary token={token} price={price} />
{onSellUsdc && <button className="btn btn--secondary btn--full" onClick={onSellUsdc}>Receber USDC na Base em vez de Pix</button>}
<div>
<label className="field-label" htmlFor="sell-amount">Quantos tokens deseja vender?</label>
<div className="amount-input amount-input--tokens">
Expand Down Expand Up @@ -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 || "" : ""));
Expand Down Expand Up @@ -306,7 +305,8 @@ export default function SellFlow({ token, auth, runtime, market, flags, holdingR

return (
<Modal title={title} onClose={onClose} wide closeDisabled={closeDisabled} stepKey={step} headerExtra={progress != null ? <FlowProgress labels={PROGRESS} current={progress} /> : null}>
{step === "amount" && <AmountStep token={token} price={price} raw={raw} amount={amount} setAmount={setAmount} pixKey={pixKey} setPixKey={setPixKey} onNext={continueFromAmount} onSellUsdc={onSellUsdc} busy={busy} error={error} />}
{step === "method" && <MethodStep direction="SELL" onPix={() => setStep("amount")} onUsdc={onSellUsdc} />}
{step === "amount" && <AmountStep token={token} price={price} raw={raw} amount={amount} setAmount={setAmount} pixKey={pixKey} setPixKey={setPixKey} onNext={continueFromAmount} busy={busy} error={error} />}
{step === "otp" && <OtpStep email={email} setEmail={setEmail} otp={otp} setOtp={setOtp} sent={otpSent} onSend={sendOtp} onVerify={verifyOtp} busy={busy} error={error} demoCode={verification.demoCode} />}
{step === "kyc" && <KycStep kyc={runtime.kyc} quote={quote} email={email} initialName={auth.user?.name} onApproved={() => { setNotice(""); setStep("review"); }} />}
{step === "review" && quote && <ReviewStep key={quote.id} token={token} quote={quote} guard={guard} reference={reference} pixKey={pixKey} ethWei={ethWei} requiredWei={requiredWei} address={wallet} onConfirm={execute} onRefresh={refresh} busy={busy} error={error} notice={notice} />}
Expand Down Expand Up @@ -342,7 +342,7 @@ export default function SellFlow({ token, auth, runtime, market, flags, holdingR
)}
{step === "issue" && <FlowIssue message={error} onRetry={resume && errorCode !== "SELL_EXPIRED" ? () => { setError(""); run(loadExisting); } : null} onClose={onClose} />}
{operationId && step !== "success" && <p className="op-ref">Código da operação: <code>{operationId}</code></p>}
{["otp", "kyc", "review"].includes(step) && !busy && !ramp && <div className="flow-foot" style={{ marginTop: 8 }}><button className="back-button" type="button" onClick={() => { setError(""); setStep("amount"); }}><ArrowLeft size={16} aria-hidden="true" /> Voltar</button></div>}
{(["otp", "kyc", "review"].includes(step) || (step === "amount" && onSellUsdc)) && !busy && !ramp && <div className="flow-foot" style={{ marginTop: 8 }}><button className="back-button" type="button" onClick={() => { setError(""); setStep(step === "amount" ? "method" : "amount"); }}><ArrowLeft size={16} aria-hidden="true" /> Voltar</button></div>}
</Modal>
);
}
14 changes: 14 additions & 0 deletions apps/stocks/src/flows/parts.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,20 @@ export function StepIntro({ icon: Icon, title, children }) {
return <ul className="points"><li><span><Icon size={22} aria-hidden="true" /></span><div><b>{title}</b><small>{children}</small></div></li></ul>;
}

/** 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 (
<div className="flow-section">
<h3>{buy ? "Como deseja pagar?" : "Como deseja receber?"}</h3>
<div className="payment-methods" role="group" aria-label={buy ? "Forma de pagamento" : "Forma de recebimento"}>
<button type="button" className="payment-choice" onClick={onPix}><b>Pix · Brasil</b> <span>{buy ? "Em reais, pelo seu banco" : "Em reais, na sua chave Pix"}</span></button>
<button type="button" className="payment-choice" onClick={onUsdc}><b>USDC · Base</b> <span>{buy ? "Da sua carteira ou exchange" : "Na sua carteira, na rede Base"}</span></button>
</div>
</div>
);
}

export function OtpStep({ email, setEmail, otp, setOtp, sent, onSend, onVerify, busy, error, demoCode }) {
return (
<div className="flow-section">
Expand Down
Loading
Loading