Skip to content

Guard computePnlPercent in usePortfolio so an outlier can't drop positions - #2497

Open
0x-SquidSol wants to merge 1 commit into
dcccrypto:playgroundfrom
0x-SquidSol:fix/portfolio-pnl-percent-guard
Open

Guard computePnlPercent in usePortfolio so an outlier can't drop positions#2497
0x-SquidSol wants to merge 1 commit into
dcccrypto:playgroundfrom
0x-SquidSol:fix/portfolio-pnl-percent-guard

Conversation

@0x-SquidSol

Copy link
Copy Markdown
Contributor

What

Wrap usePortfolio's two computePnlPercent calls in try/catch → 0, matching
PositionsDock / ChartPnlBadge.

Why

computePnlPercent throws when pnl*10000/denominator overflows MAX_SAFE_INTEGER
(a dust position-initial-margin with large PnL). usePortfolio's two sites were
unguarded, 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

  • usePortfolio: guard both computePnlPercent sites (the single-position path and
    the shared-scan path) → fall back to 0, mirroring PositionsDock.
  • regression test: throws on dust margin + large PnL; the guard returns 0; legit
    values still compute a finite percent.

Testing

  • npx tsc --noEmit — clean.
  • New test + Portfolio/usePortfolio suites — 5 files, 39 tests, all pass.

Notes

  • Frontend + devnet scope; no program/keeper/mainnet changes.

…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
0x-SquidSol requested a review from dcccrypto as a code owner August 5, 2026 20:19
@vercel

vercel Bot commented Aug 5, 2026

Copy link
Copy Markdown

@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.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@0x-SquidSol, you've reached your PR review limit, so we couldn't start this review.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 9f7044e8-1abc-4494-a3d6-7b395f6e15b1

📥 Commits

Reviewing files that changed from the base of the PR and between f2a3bbe and 9894756.

📒 Files selected for processing (2)
  • app/__tests__/hooks/portfolio-pnl-percent-guard.test.ts
  • app/hooks/usePortfolio.ts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dcccrypto dcccrypto left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants