Guard computePnlPercent in usePortfolio so an outlier can't drop positions - #2497
Guard computePnlPercent in usePortfolio so an outlier can't drop positions#24970x-SquidSol wants to merge 1 commit into
Conversation
…tions computePnlPercent throws when pnl*10000/denominator overflows MAX_SAFE_INTEGER (a dust position-initial-margin with large PnL). PositionsDock and ChartPnlBadge wrap it in try/catch -> 0, but usePortfolio's two call sites did not — so the throw propagated to the per-account (v17) / per-market (v12) catch and silently dropped that position, or the whole market's accounts, from the portfolio (capital, PnL, and at-risk count included). Wrap both call sites in try/catch -> 0, matching PositionsDock. - usePortfolio: guard both computePnlPercent sites (single + shared-scan paths) - add a regression test (throws on dust margin + large PnL; guard returns 0; legit values still compute) Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
|
@0x-SquidSol is attempting to deploy a commit to the Khubair Nasir's projects Team on Vercel. A member of the Team first needs to authorize it. |
|
Warning Review limit reached
Next review available in: 16 minutes You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
dcccrypto
left a comment
There was a problem hiding this comment.
Correct, and this is the first PR in this run where my "is it wider than
reported?" sweep comes back empty — the scope is exactly right. Suite:
2922 passed / 0 failed.
All three claims verified
The throw is real. computePnlPercent in the SDK:
if (capital === 0n) return 0;
const scaledPct = pnlTokens * 10000n / capital;
if (scaledPct > BigInt(Number.MAX_SAFE_INTEGER) || scaledPct < BigInt(-Number.MAX_SAFE_INTEGER)) {
throw new Error(`computePnlPercent: scaled result ${scaledPct} exceeds Number.MAX_SAFE_INTEGER — precision loss`);
}(Also worth knowing: the capital === 0n early return means the
account.capital fallback branch can't itself throw on a zero denominator — only
on a dust one.)
"Silently dropped" is accurate, and the wording is doing real work. The v17
per-account catch at :896 logs to console.debug and continues, and the
shared-scan catch at :987 is bare. In both, depositSum / pnlSum /
unrealizedPnlSum accumulate after the position is built — so a throw removes
that account's capital from the portfolio total, not just its row, and its
riskCount contribution with it. A portfolio that quietly under-reports deposits
is worse than one that errors.
"Mirrors PositionsDock" is exact — :272-277 is the same
let roe = 0; try { … } catch { roe = 0 } shape.
Sweep: every other call site was already guarded
I checked all of them, since "one unguarded consumer" is the sort of claim that's
usually off by two:
| site | guarded before this PR? |
|---|---|
ChartPnlBadge.tsx:81 |
yes |
PositionPanel.tsx:357 |
yes |
PositionsDock.tsx:274 |
yes |
OtherMarketPositions.tsx:171,173 |
yes |
usePortfolio.ts:448,449,739,740 |
no — this PR |
So usePortfolio really was the last one, and after this the convention is
uniform. Given four sites independently arrived at the same try/catch → 0
shape, the obvious follow-up is a safePnlPercent() in lib/trading next to
computePositionInitialMargin — five copies of a guard is how the next consumer
ends up without one.
Test doesn't bind the fix — twelfth in the run
I removed both guards, restoring the bug in full, and
portfolio-pnl-percent-guard.test.ts stayed 3/3 green — it exercises the SDK
function's throw/no-throw behaviour rather than usePortfolio.
buildV17Position isn't exported, but fetchPortfolioSnapshot is, and the second
guarded site is inside it. Feeding it one account with dust
positionInitialMargin and large PnL, then asserting the account still appears in
the snapshot and its capital is included in depositSum, binds the fix and pins
the impact that actually matters — the silent omission from the total, which no
assertion currently covers.
What
Wrap
usePortfolio's twocomputePnlPercentcalls in try/catch → 0, matchingPositionsDock/ChartPnlBadge.Why
computePnlPercentthrows whenpnl*10000/denominatoroverflowsMAX_SAFE_INTEGER(a dust position-initial-margin with large PnL).
usePortfolio's two sites wereunguarded, so the throw propagated to the per-account (v17) / per-market (v12) catch
and silently dropped that position — or the whole market's accounts — from the
portfolio (including its capital, PnL, and the at-risk count).
Changes
computePnlPercentsites (the single-position path andthe shared-scan path) → fall back to 0, mirroring PositionsDock.
values still compute a finite percent.
Testing
npx tsc --noEmit— clean.Notes