fix(card): force collateral-only routing on lock/cancel - #2570
Conversation
…zation header CapacitorHttp's Android GET proxy (_capacitor_http_interceptor_) stalls under load, timing out every in-flight request after 10s (PEANUT-UI-R44): ~400 timeouts/user on Android vs ~3 on web/iOS over 14d, GETs only, in correlated bursts. Requests now go direct from the webview, same path as web. - auth: token moves from the CapacitorHttp cookie jar to @capacitor/preferences (survives webview storage eviction, unlike localStorage — PEANUT-UI-QTQ), hydrated into an in-memory cache and sent as Authorization. authReady() gates callApi and direct fetchWithSentry call sites against cold-start races. - login: the ZeroDev SDK consumes /passkeys/*/verify responses internally, so a window.fetch wrapper captures the body token on native. /users/me sliding refresh keeps it current via the existing setAuthToken path. - old binaries keep working: server still accepts the jwt-token cookie and hasNativeSession falls back to the legacy jar. Existing native sessions are not migrated — testers log in once after updating. - fetchWithSentry: idempotent requests (GET/HEAD) get one silent retry on timeout before surfacing. - canary: one-shot startup probe reports direct-fetch viability to Sentry (message:"direct-fetch canary", tags outcome/transport) so the transport switch is validated fleet-wide via OTA before the binary rolls out.
@capacitor/device requires the next native binary release; JS falls back to navigator.language on older binaries.
Hoist the lazy viem require in peanut-claim.utils (viem is already statically imported there) and scope the rule off for Jest test files, where require() after jest.mock()/resetModules() is intentional.
Remove dead imports/declarations, use bare catch where the binding was unused, and _-prefix signature-bound params and kept hook results. Also ignore ios/ and build/ (generated) in eslint.
Replace raw <a> internal-route anchors with <Link> (client-side navigation) across LandingPage components and the dev debug page.
- src/i18n/app: locale config + resolveLocale normalizer, catalogs (en/es-419/pt-BR), deep-merge loader so missing keys render English, runtime locale store (Preferences/Device on native, cookie on web), AppIntlProvider with hydration-safe English-first state - provider wired into ClientProviders; native splash gated on the startup locale being painted (2s timeout guard) - loadingStates union converted to a const array + key mapping - jest: transform ESM-only intl packages (pnpm-aware ignore pattern) Marketing i18n (src/i18n/*.json) untouched.
/settings/language screen with the supported locales, reached from a new Profile row showing the active language. Live re-render on switch, persisted via Preferences (native) / cookie (web).
The OPEN-status badge fix was picked up by 1eb7c3c ("fix(lint): resolve no-unused-vars") along with that commit's lint sweep. It is unrelated to localization and is being reviewed on its own branch against main (peanut-ui#2430), so remove it here to keep the two changes separable. Pure removal — no behaviour change beyond reverting to main's badge logic.
Step titles/descriptions keyed by screenId (removed from ISetupStep), all Setup views, wrapper, and (setup) pages on useTranslations. es-419 + pt-BR drafts included.
Home screen, activation CTAs, carousel, perk/welcome modals, tab bar, desktop sidebar and top navbar. TopNavbar maps pathname to typed navigation.* keys, replacing the pathTitles util.
ExchangeRateWidget (marketing-shared) takes an optional labels prop with English defaults; product callers pass translated labels.
Limits warning-card items now carry a kind discriminator so render sites can map them to translated copy; qr-pay uses it.
The warning card rendered raw English item text for the withdraw and add-money callers while qr-pay mapped the kind discriminator at its own render site. Resolve copy inside the card instead, so every flow gets it, and drop the duplicated mapping from qr-pay. Passkey troubleshooting steps and warnings become ids resolved against setup.passkey.help.*, so the modal's content is translated, not just its chrome.
The min/max cashout branches assigned the placeholder slugs 'offramp_lt_minimum'/'offramp_mt_maximum', which ErrorAlert rendered verbatim — users saw the raw slug. Assign real messages with the limit formatted as currency. Also return on the over-maximum branch: it set the error and then kept going, fetching a route and letting the flow continue past the limit, unlike the under-minimum branch.
validatePin returns reason codes instead of English copy so the util stays copy-free; CardPinSetupFlow maps them to messages. CardCountryConfirmScreen feeds the active locale into Intl.DisplayNames (was hardcoded to en), so country names follow the UI language.
Drop the vestigial capitalize class on the feed's type label: it existed to case raw enum values (getActionText returned the type verbatim), but the catalog now supplies cased copy, and CSS title-casing mangles multi-word labels in every locale. cardDeclineReason and the bank-account label util return codes now, with the copy resolved at the render site.
Drop the capitalize class on the badge-unlocked label for the same reason as the transaction feed: it title-cased translated copy. Remove invites.consts.ts — it held only display copy, and its last consumer now reads the setup-flow waitlist key so the two gates can't drift.
sumsub-reject-labels.consts.ts becomes a copy-free code registry; the 62 reject labels move to the kyc namespace and resolve at the render site, with unknown codes collapsing to FALLBACK as before. recover-funds no longer prints a raw loadingState or raw token amounts, and the KYC screens format dates through the active locale instead of a hardcoded en-US.
Marketing-shared components under Global/ keep their English and take copy as props instead: they render inside the app intl context, but the marketing site resolves its language from the URL, so a shared component would show the app locale on a marketing page. Fix UserCard.getTitle reading fullName/username while only depending on type, which rendered a stale name after a rename.
Extraction silently rewrote ' to the typographic form in 32 places, changing English copy that ships today (e.g. the balance-warning modal's "you're the only one who can access your funds"). Straighten them all so en matches source and reads consistently; the translated catalogs are unaffected. Also wrap the useSumsubKycFlow test in an intl provider — the hook now calls useTranslations and the suite never had one.
friendly-error.utils.tsx becomes copy-free: ErrorHandler is replaced by friendlyError(), returning a code or backend-provided text, resolved to a message by the new useFriendlyError hook. Backend copy (rain collateral, stale-card re-enable with its dynamic retry hint) passes through untranslated. Three sites compared the rendered error string against a constant to gate UI; those now compare the error CODE, so the gate survives translation.
src/features/payments was missed by every earlier pass — a lint probe caught it. Extends the existing payment namespace (no payments dupe); contributor and receipt counts use ICU plurals, the 'on <chain>' label reuses the shared tokenSelector.onChain rich-text key. Also covers the KYC status drawer, sumsub load-error, and amount-input balance label.
Scopes react/jsx-no-literals to the translated surface so new hardcoded JSX strings fail lint. Excludes tests, the /dev catalog, and marketing- shared Global components; allowlists non-copy glyphs (card masks, %, decorative emoji). Extraction stragglers the guard surfaced are also handled: the beta/demo banners and the transaction 'Enjoy Peanut!' title.
useSendMoney calls useTranslations, and it runs inside ContextProvider (via TokenContextProvider → useWallet), which was mounted ABOVE the intl provider — so every route 500'd with a missing-context error. Unit tests each wrap their subject in a provider, so only a full-app render caught it. Move AppIntlProvider to wrap ContextProvider (still inside PeanutProvider, which needs no translations).
'Video element not available' was shown to users when the video element lost the mount race. Say what it means to them instead. Adds a ClientProviders provider-order test: it walks the real element tree rather than rendering it, so the AppIntlProvider-wraps-ContextProvider contract is checked without mocking the wallet and kernel stack.
Everything except no-explicit-any and no-restricted-imports. Most of these
turned out to be malformed eslint-disable directives rather than the code
defects the rule names suggested.
react-hooks/exhaustive-deps (PerkClaimModal, 2): the disable comments used an
em-dash before the description instead of ESLint's `--` separator, so ESLint
parsed the whole string as a rule name. The suppressions were not suppressing
anything and both exhaustive-deps warnings were firing. Both effects are
deliberately mount-only, so the separator is fixed and the reasoning kept.
react/no-unknown-property (6): `<style jsx global>` is styled-jsx, a Next
built-in, not an invalid DOM attribute. Taught the rule via `ignore` in the
config — two files under Card/share-asset had already been hand-disabling it,
so those disables are now redundant and removed.
import/first (5), jsx-a11y/alt-text (1): both rules are unregistered here (the
config uses import-x, and jsx-a11y is not installed), so these directives only
produced "rule not found" errors. Removed; the Jest-ordering rationale is kept
as a plain comment. The alt-text site is a next/image test mock, not a real
accessibility defect.
react/display-name (1): named the forwardRef render function in a Card mock.
no-empty-object-type (1): ILinkDetails.rawOnchainDepositInfo `{}` ->
Record<string, unknown>; the field is declared but read nowhere.
Also removed 7 dead disable directives for rules that are off in tests
(no-require-imports) or no longer exist (no-var-requires).
eslint: 441 -> 424 errors, 157 -> 148 warnings. typecheck, jest (142 suites /
1974 tests) and prettier all green.
Rewrites all 55 bare `from '@/interfaces'` imports to the file that actually
owns the symbol. The barrel only re-exported ./interfaces and
./wallet.interfaces, so this was uniform except useAccountSetup.ts, which is
the one consumer of WalletProviderType. src/interfaces/index.ts had no
remaining referrers and is deleted.
Also removed a jest.mock('@/interfaces') in withdraw-states.test.tsx. The deep
imports made it dead (it no longer intercepted anything), and it was redundant
regardless: it stubbed AccountType with four members whose values match the
real enum exactly, while shadowing the other three (EVM_ADDRESS,
PEANUT_WALLET, MANTECA). The suite passes against the real enum.
eslint: 424 -> 368 errors. typecheck 0, jest 142 suites / 1974 tests green.
Rewrites all 45 bare `from '@/assets'` imports. The root barrel re-exported ten
category sub-barrels, so a single named import pulled the whole asset graph in.
Most symbols resolve to a leaf file (the sub-barrels are pure
`export { default as X } from './x.svg'` re-exports), so those become direct
default imports — which is already the dominant convention in this codebase.
The exceptions are the computed consts in assets/mascot and assets/cards
(PeanutWhistling = pick(webp, gif), APPLE_WALLET_STEPS); those are defined in
their category index rather than re-exported, so the index is the owning file
and they keep a named import from '@/assets/mascot'.
eslint: 368 -> 323 errors. typecheck 0, jest 142 suites / 1974 tests green.
…ched view New code must lint clean: type the Button mock and drop the any-spread in the useWallet mock. The touched view's '@/context' barrel import is swapped for the specific loadingStates.context file (same module instance, restricted-imports rule).
Two more transitions could still eat a submit-time error: a momentarily-unavailable balance cleared every error (now releases only the gate's own message; an emptied amount still clears all - that IS user input), and editing the amount left a stale failure on screen (now released back to the gate, which re-flags a genuine shortfall on the new amount). Regression tests for both.
…lowed fix(send-link): keep submit-time errors visible through balance polls
…prompt
Clipboard.read() on scanner open fires before getUserMedia (camera start
deliberately sleeps 200ms on iOS), so the iOS 'Allow Paste' alert lands
first and blocks the camera permission dialog — getUserMedia never
settles and the 5s watchdog reports a false NotAllowedError ('Camera
start timed out'). Camera only opened on the second attempt, once iOS
remembered the paste grant for the session.
Reverts the pre-read shortcut from 32454bb. The explicit 'Click to
paste' button keeps the paste path on a real user gesture, which is
where the OS prompt belongs.
…-read Reintroduces the clipboard shortcut removed in #2520 with a platform split that can't race the camera permission dialog: - Android native: unchanged from pre-revert — read at open, preview the copied EVM address in a one-tap chip (only side effect is the system paste toast). - iOS native: a new app-local ClipboardDetect plugin exposes UIPasteboard.hasStrings — metadata only, so no iOS 16+ 'Allow Paste' alert. When true, a generic 'Use copied address' chip appears; the real Clipboard.read() runs on the chip tap, a user gesture, with the camera already live. Older binaries (OTA'd JS) resolve hasStrings to false and simply show no chip. - Web/PWA: no pre-read; the explicit 'Click to paste' stays the fallback. Needs an iOS binary release to activate the chip (new native plugin, registered via AppViewController per Capacitor's app-local plugin flow).
… pin the platform split with tests Review findings on the chip rework: a payment-routing failure inside handleUsePasteChip landed in the clipboard catch and toasted 'Could not access clipboard' (hiding the chip), and an empty clipboard on the chip path used different copy than the 'Click to paste' path for the same condition. Split the onScan await out of the clipboard try and reuse handlePaste's empty-clipboard mapping. New component test pins the load-bearing claim of the platform split: Clipboard.read() never fires at scanner open off Android-native (the PEANUT-UI-PYW paste-prompt race), iOS reads only on chip tap, Android keeps the read-at-open preview.
…and guarded-scan helpers Review follow-up (kush): the onScan-inside-clipboard-try misreport fixed on the chip path still lived in handlePaste, the empty/error toast mapping was duplicated across both handlers, and the Android chip called onScan with no guard at all (unhandled rejection, no user feedback). One readClipboardText helper + one scanValue wrapper now serve all three tap paths; tests pin the two newly guarded ones.
…-preread fix(qr-scanner): stop clipboard paste-prompt racing the camera; platform-gate the copied-address chip
…ch-timeouts chore(fetch): back-merge #2533 (context-aware fetch timeouts) into dev
# Conflicts: # pnpm-lock.yaml # src/app/(mobile-ui)/add-money/page.tsx # src/app/(mobile-ui)/notifications/page.tsx # src/app/(mobile-ui)/withdraw/crypto/page.tsx # src/app/(mobile-ui)/withdraw/page.tsx # src/app/ClientProviders.tsx # src/components/Card/ApplicationStatusScreen.tsx # src/components/Card/PhysicalCardScreen.tsx # src/components/Card/YourCardScreen.tsx # src/components/Global/GeneralRecipientInput/index.tsx # src/components/Global/QRScanner/index.tsx # src/components/Home/ActivationCTAs.tsx # src/components/Kyc/KycVerificationInProgressModal.tsx # src/components/Send/link/views/Initial.link.send.view.tsx # src/components/TransactionDetails/TransactionDetailsReceipt.tsx # src/components/TransactionDetails/provider-rows/CardPaymentRows.tsx # src/components/TransactionDetails/transaction-details.utils.ts # src/components/Withdraw/views/Initial.withdraw.view.tsx # src/utils/__tests__/general.utils.test.ts
Localization (en / es-419 / pt-BR) + zero ESLint errors
The Android, iOS and demo-mode runbooks were consolidated into mono at engineering/native/ so there is one source of truth. The copies here had already drifted and now state wrong facts (Capgo deploy triggers, a secret name that no longer exists, the wrong Sumsub plugin package), so a reader landing on them gets misled. Kept as pointers rather than deleted because three files in the release pipeline still reference these paths. Paths are repo-relative, not github.com URLs, so they also resolve for readers who only have a partial copy of mono.
# Conflicts: # src/content # src/utils/auth-token.ts
chore: back-merge main into dev (keeps the CSP fix)
Lock/cancel sign a withdrawal whose purpose is draining Rain collateral back to the wallet, but since cb302d3 removed the smartBalance:0n input, routing fell through to live-balance strategy selection: any user whose wallet USDC covered their spending power routed smart-only, tripped the modals' own strategy check, and could neither lock nor cancel ('Unexpected withdrawal strategy', prod, 3 users affected). Also fail closed when the card overview hasn't loaded: undefined read as zero spending power, silently skipping the withdrawal and getting the action rejected server-side ('Withdrawal signature required').
Adversarial mutation run showed CancelCardModal's zero-power skip path (> 0n guard) had no test counterpart to LockCardModal's, so a guard- shape regression on the cancel side would ship green.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Important Review skippedAuto reviews are disabled on base/target branches other than the default branch. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Comment |
Code-analysis diffPainscore total: 6656.05 → 6656.66 (+0.61) 🆕 New findings (6)
✅ Resolved (6)
|
🧪 UI test report — ✅ all greenSuites
📊 Coverage (unit)
⏱ 10 slowest test cases
|
|
Superseded by #2571 — same fix rebased onto |
What broke (prod)
Locking or cancelling a card fails with "Unexpected withdrawal strategy — please contact support" whenever the user's smart-wallet USDC ≥ their card spending power. The card stays
ACTIVE; the user burns a passkey tap and cannot secure or close their card. No money at risk — the signed UserOp is never broadcast.Reported via Crisp on 2026-07-24 (bug bounty paid). 3 prod users are currently blocked, including one with $25k wallet / $2k collateral; 235 distinct users routed
smart-onlyin the last 6 weeks and were transiently exposed (auto-balance keeps wallets swept near-empty, which is why the standing count is low).Root cause — regression trail
The lock/cancel withdrawal exists to drain Rain collateral back to the wallet, so it must always route
collateral-only:2eb1da396(2026-05-08): forced this by passingsmartBalance: 0ntosignSpend.cb302d35a(2026-06-16): removed thesmartBalanceinput repo-wide and deleted the0nline from both modals without replacement — routing fell through tocomputeSpendStrategy, which returnssmart-onlywhenever the live wallet balance covers the amount. Both modals then reject their own artifact and throw.ca79b66a7: addedforceStrategy: 'collateral-only'for exactly this need, but wired it only intouseReturnExcessCollateral.A stale comment ("smart=0n eliminates the smart-only and mixed branches") kept describing the deleted parameter, which is why later reviews missed it.
The fix (frontend-only, backend unchanged)
LockCardModal/CancelCardModal: passforceStrategy: 'collateral-only'tosignSpend— same pattern asuseReturnExcessCollateral. Replaced the stale comment with one stating the actual constraint. Theartifact.strategy !== 'collateral-only'throw stays: unreachable at runtime now, but load-bearing for TS narrowing to therainWithdrawalvariant.rainCentsToUsdcUnits(undefined)→0n, so an unresolveduseRainCardOverviewsilently skipped the withdrawal and the backend rejected with "Withdrawal signature required to return collateral before this action" (2 users, 07-09 and 07-13). Both modals now throw a friendly retry message (new i18n keycard.errors.cardDetailsLoading, all 3 locales) instead of signing nothing.Tests
New
src/components/Card/__tests__/LockCardModal.test.tsxcovering both modals (6 tests):signSpendis called withforceStrategy: 'collateral-only'(exact-args assertion — this is the one that catches the nextSignSpendBundleInputrefactor; the regression already happened once).The suite was mutation-tested pre-merge: 6 line-level mutants (drop
forceStrategy×2, drop the overview guard ×2,> 0n→>= 0n×2) all killed by exactly the intended assertion. The existinguseSignSpendBundle.test.tsxforced-routing contract covers the layer this suite mocks.Gate: typecheck clean, full jest suite green, prettier clean.
Known residual (pre-existing, deliberately not touched)
A loaded overview with
balance: nullbut real positive Rain spending power would still read as0nand hit the server-side rejection. Not covered becausebalance: nullnormally means no collateral contract — extending the guard to!overview.balancewould block legitimate no-collateral cancels. Needs a backend-truth check if it ever shows up in prod.Verification after deploy
PostHog:
card_withdraw_attemptedwithflow=sign-onlymust never reportstrategy=smart-onlyagain;card_lock_failedwith "Unexpected withdrawal strategy" must stop. Then reply to the affected users' tickets.Screenshots