Skip to content

Fix missing base leg USD value calculation in neutral-trade drift util#73

Open
zknpr wants to merge 1 commit intomainfrom
fix-neutral-trade-drift-base-leg-11210373544589687715
Open

Fix missing base leg USD value calculation in neutral-trade drift util#73
zknpr wants to merge 1 commit intomainfrom
fix-neutral-trade-drift-base-leg-11210373544589687715

Conversation

@zknpr
Copy link
Copy Markdown
Owner

@zknpr zknpr commented Mar 8, 2026

Implemented the TODO in projects/neutral-trade/utils/drift.js to find the USD value for base tokens without an SPL spot mint (like HYPE-PERP). It now extracts the oracle price from the PerpMarket account buffer at offset 72, adjusts for precision, and adds the value as USDC to the API object.


PR created automatically by Jules for task 11210373544589687715 started by @zknpr

Co-authored-by: zknpr <96851588+zknpr@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist
Copy link
Copy Markdown

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 8, 2026

Warning

Rate limit exceeded

@zknpr has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 11 minutes and 14 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: accf703f-a496-4df7-8865-8a29cb61037c

📥 Commits

Reviewing files that changed from the base of the PR and between 0d3be2a and afcf873.

📒 Files selected for processing (1)
  • projects/neutral-trade/utils/drift.js
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix-neutral-trade-drift-base-leg-11210373544589687715

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 and usage tips.

@llamabutler
Copy link
Copy Markdown

The adapter at projects/neutral-trade exports TVL:

solana                    49.00 M

total                    49.00 M 

@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Mar 8, 2026

Greptile Summary

This PR implements the previously-skipped TODO in projects/neutral-trade/utils/drift.js to compute a USD value for perp positions whose base token has no SPL spot mint (e.g. HYPE-PERP), adding it as USDC to the TVL API object. The approach of reading the oracle price from the PerpMarket account buffer and scaling by BASE_PRECISION / PRICE_PRECISION is conceptually sound, but the hardcoded buffer offset is incorrect and will silently produce wrong TVL values.

Key changes:

  • Removed the old // TODO comment and skip logic in the else branch of the base-token-mint check.
  • Added a read of perpAccount.data.readBigInt64LE(72) to get an oracle price.
  • Computed usdValue = (base_asset_amount × price) / 10⁹ and added it under the USDC mint (market index 0).

Issues found:

  • Wrong buffer offset (critical): Offset 72 in the Drift v2 PerpMarket account buffer corresponds to AMM.historical_oracle_data.last_oracle_price_twap_5min (the 5-minute TWAP), not the live oracle price. The live price field last_oracle_price is at offset 40 (8-byte discriminator + 32-byte oracle Pubkey). Using the TWAP will cause TVL to lag the real price and diverge meaningfully during volatile periods.
  • Undocumented magic numbers: Unlike existing offsets in the same file (e.g. CUMULATIVE_FUNDING_OFFSET), the new code uses bare literals 72 and 10 ** 9 with no derivation comment, making future correctness verification very difficult.

Confidence Score: 2/5

  • Not safe to merge — the hardcoded offset reads a stale 5-minute TWAP instead of the live oracle price, causing systematic TVL mispricing for affected positions.
  • The overall structure (fetching the PerpMarket account, scaling BigInt arithmetic) is correct, but the wrong buffer offset is used for the price field. This is a silent bug — no runtime error occurs, but the TVL value for any position hitting this code path will consistently reflect a 5-minute TWAP rather than the current price. The fix is a one-line change (offset 72 → 40), but until it is applied the PR introduces a regression relative to simply skipping the position.
  • projects/neutral-trade/utils/drift.js — specifically the new readBigInt64LE(72) call and its surrounding precision math.

Important Files Changed

Filename Overview
projects/neutral-trade/utils/drift.js Implements the TODO for pricing base legs without an SPL spot mint (e.g. HYPE-PERP) by reading an oracle price from the PerpMarket buffer. However, the hardcoded offset 72 reads last_oracle_price_twap_5min (5-minute TWAP) rather than the live oracle price at offset 40, causing systematic TVL mispricing during volatile markets.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["getTvl(api, driftVaultAddresses)"] --> B["Fetch & deserialize user positions"]
    B --> C["Batch-fetch PerpMarket accounts → perpAccountMap"]
    C --> D["For each perpPosition"]
    D --> E{"baseTokenMint exists?"}
    E -- "Yes (e.g. SOL-PERP)" --> F["api.add(baseTokenMint, baseBalance)"]
    E -- "No (e.g. HYPE-PERP)" --> G["Read perpAccount.data.readBigInt64LE(72)"]
    G --> H["usdValue = base_asset_amount × price / 1e9"]
    H --> I["api.add(USDC mint, usdValue)"]
    F --> J["api.add(USDC mint, quoteBalance)"]
    I --> J
    J --> K["Compute funding rate PnL"]
    K --> L["api.add(USDC mint, fundingRatePnl)"]

    style G fill:#ffcccc,stroke:#cc0000
    style H fill:#ffcccc,stroke:#cc0000
    G -.->|"⚠️ Offset 72 = last_oracle_price_twap_5min\n(live price is at offset 40)"| G
Loading

Last reviewed commit: afcf873

Comment on lines +2104 to +2105
const price = perpAccount.data.readBigInt64LE(72);
const usdValue = (position.base_asset_amount * price) / BigInt(10 ** 9);
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Wrong buffer offset reads 5-minute TWAP, not live oracle price

Based on the Drift v2 PerpMarket account layout, the AMM struct begins right after the 8-byte Anchor discriminator, with the following field order:

Global Offset Field
8 AMM.oracle (Pubkey, 32 bytes)
40 HistoricalOracleData.last_oracle_pricelive oracle price
48 HistoricalOracleData.last_oracle_conf
56 HistoricalOracleData.last_oracle_delay
64 HistoricalOracleData.last_oracle_price_twap (1-hour TWAP)
72 HistoricalOracleData.last_oracle_price_twap_5minwhat the code reads
80 HistoricalOracleData.last_oracle_price_twap_ts

Reading at offset 72 picks up last_oracle_price_twap_5min (the 5-minute time-weighted average price), not the live oracle price described in the PR. During periods of high volatility — exactly the times when HYPE-PERP is most active — this TWAP can diverge significantly from the actual price and will cause the TVL to be measurably incorrect.

The live oracle price is at offset 40. If a TWAP is intentionally preferred for stability, that should be documented with a comment.

Suggested change
const price = perpAccount.data.readBigInt64LE(72);
const usdValue = (position.base_asset_amount * price) / BigInt(10 ** 9);
const price = perpAccount.data.readBigInt64LE(40); // AMM.historical_oracle_data.last_oracle_price (offset = 8 discriminator + 32 oracle pubkey)
const usdValue = (position.base_asset_amount * price) / BigInt(10 ** 9);

Comment on lines +2102 to +2107
const perpAccount = perpAccountMap[position.market_index];
if (perpAccount && perpAccount.data) {
const price = perpAccount.data.readBigInt64LE(72);
const usdValue = (position.base_asset_amount * price) / BigInt(10 ** 9);
api.add(getTokenMintFromMarketIndex(0), usdValue);
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Magic numbers with no derivation comments

Unlike getPerpMarketFundingRates, which documents its offset as:

const CUMULATIVE_FUNDING_OFFSET = 8 + 48 + 32 + 256 + (16 * 15) + 24;

the new code uses bare magic numbers 72 and 10 ** 9 without any comment explaining what struct field is at that offset or what precision constant is being applied. This makes it very hard to verify correctness or maintain in the future.

Consider adding an explanatory constant and comment, similar to the existing pattern:

// Drift v2 PerpMarket layout: 8 (discriminator) + 32 (AMM.oracle pubkey) = 40
const ORACLE_PRICE_OFFSET = 40; // AMM.historical_oracle_data.last_oracle_price
// base_asset_amount is in BASE_PRECISION (1e9), price is in PRICE_PRECISION (1e6)
// USD value in USDC raw (6 decimals) = (base/1e9) * (price/1e6) * 1e6 = base * price / 1e9
const price = perpAccount.data.readBigInt64LE(ORACLE_PRICE_OFFSET);
const usdValue = (position.base_asset_amount * price) / BigInt(10 ** 9);

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