Skip to content
This repository was archived by the owner on Dec 5, 2025. It is now read-only.

Add function to calculate liquidation price offchain [PFT-2474]#99

Merged
sudeepb02 merged 2 commits intodevelopfrom
feat/offchain-liq-price
Apr 2, 2025
Merged

Add function to calculate liquidation price offchain [PFT-2474]#99
sudeepb02 merged 2 commits intodevelopfrom
feat/offchain-liq-price

Conversation

@sudeepb02
Copy link
Contributor

@sudeepb02 sudeepb02 commented Apr 2, 2025

Summary by CodeRabbit

  • New Features
    • Introduced an enhanced liquidation price calculation that improves trading risk assessments by factoring in available margin, margin buffer, position size, and market price.
  • Tests
    • Added a test suite to validate the functionality of the new liquidation price calculation, covering various scenarios and edge cases.
  • Chores
    • Updated package version from 2.2.10 to 2.2.11.

@notion-workspace
Copy link

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

Walkthrough

The pull request introduces a new method calculateLiquidationPriceOffchain to the Perps class in src/perps/index.ts, which calculates the liquidation price based on parameters such as available margin and position size. This method calls a corresponding function in src/perps/offchain.ts, which implements the calculation logic and handles edge cases. Additionally, a new test suite in test/perps/offchain.test.ts has been created to validate the functionality under various scenarios. The package version has also been incremented from 2.2.10 to 2.2.11.

Changes

File(s) Change Summary
src/perps/index.ts
src/perps/offchain.ts
Added new method calculateLiquidationPriceOffchain in the Perps class and a corresponding function in offchain.ts to calculate liquidation prices based on provided parameters.
test/perps/offchain.test.ts Introduced a new test file to validate the calculateLiquidationPriceOffchain function, covering scenarios for zero position size, long positions, short positions, and cases with zero available margin.
package.json Updated package version from "2.2.10" to "2.2.11".

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Perps
    participant Offchain
    Client->>Perps: calculateLiquidationPriceOffchain(params)
    Perps->>Offchain: calculateLiquidationPriceOffchain(params)
    Offchain-->>Perps: return calculated liquidationPrice
    Perps-->>Client: return liquidationPrice
Loading

Poem

I hop in fields of code so bright,
Calculating prices in the soft moonlight.
My logic burrows deep, resolute and fair,
Liquidation paths clear in the cool night air.
🐇 With every hop, I debug without a care!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 915891d and 87735b4.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/perps/offchain.ts (1)

82-84: Consider using strict equality comparison.

The code currently uses == for comparison, but it's generally a best practice in TypeScript/JavaScript to use === for strict equality comparison to avoid unexpected type coercions.

-  if (formattedPositionSize == 0) return formattedMarketPrice;
-  if (availableMarginInUsd == 0) return 0;
+  if (formattedPositionSize === 0) return formattedMarketPrice;
+  if (availableMarginInUsd === 0) return 0;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ebfc6a2 and 915891d.

📒 Files selected for processing (3)
  • src/perps/index.ts (2 hunks)
  • src/perps/offchain.ts (1 hunks)
  • test/perps/offchain.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Definitions (2)
src/perps/index.ts (1)
src/perps/offchain.ts (1)
  • calculateLiquidationPriceOffchain (71-96)
test/perps/offchain.test.ts (1)
src/perps/offchain.ts (1)
  • calculateLiquidationPriceOffchain (71-96)
🔇 Additional comments (8)
src/perps/index.ts (2)

11-11: LGTM: Import added correctly.

The import for calculateLiquidationPriceOffchain has been correctly added to the imports from './offchain'.


82-100: LGTM: Well-structured method implementation.

The implementation follows the established pattern in the class, serving as a clean wrapper around the imported function. The method has a proper comment and clearly passes all parameters to the underlying function.

test/perps/offchain.test.ts (4)

5-13: LGTM: Edge case well tested.

This test correctly verifies that when position size is 0, the function returns the market price (2000), which is the expected behavior for this edge case.


15-23: LGTM: Correct calculation for long position.

The test correctly verifies the liquidation price calculation for a long position:

  • lossPerToken = Math.abs((20 - 100) / 1) = 80
  • liquidationPrice = 2000 - 80 = 1920

Using toBeCloseTo() is appropriate for floating-point comparisons.


35-43: LGTM: Edge case well tested.

This test correctly verifies that when available margin is 0, the function returns 0, which is the expected behavior for this edge case.


25-33:

Details

❓ Verification inconclusive

Verify the calculation for short positions.

The test logic seems correct mathematically:

  • lossPerToken = Math.abs((20 - 1000) / -1) = 980
  • liquidationPrice = 2000 + 980 = 2980

However, please verify if the business logic is correct. Is it expected that when marginBufferInUsd (20) is much less than availableMarginInUsd (1000), the liquidation price would be significantly higher than the market price for a short position?


🏁 Script executed:

#!/bin/bash
# Search for other instances of liquidation price calculations for short positions
rg -A 5 -B 5 "liquidation.*price.*short" --type ts

Length of output: 744


Subject: Verify Consistency of Short Position Liquidation Price Calculation

The current test snippet calculates the liquidation price for a short position as 2980—with the math showing a loss per token of 980 added to the market price (2000 + 980). However, another context within the same file expects a liquidation price of 1920. Please verify whether the business logic should yield 2980 or 1920 for short positions and update the tests accordingly.

  • Confirm the intended formula for calculating the liquidation price for short positions.
  • Ensure that all tests in test/perps/offchain.test.ts consistently reflect the correct expected value.
src/perps/offchain.ts (2)

63-70: LGTM: Well-documented function.

The JSDoc comments are clear and descriptive, providing good documentation for the function parameters and return value.


86-93:

Details

❓ Verification inconclusive

Verify the liquidation price calculation logic.

The calculation for lossPerToken uses the formula:
Math.abs((marginBufferInUsd - availableMarginInUsd) / formattedPositionSize)

For a short position where marginBufferInUsd is less than availableMarginInUsd (as in the test), this will result in a large positive number, making the liquidation price significantly higher than the market price.

Please verify this aligns with the expected business logic for liquidation prices for short positions.


🏁 Script executed:

#!/bin/bash
# Search for other implementations or documentation of liquidation price calculations
rg "liquidation.*price" --type ts -A 5 -B 5

Length of output: 2827


Liquidation Price Calculation Logic – Please Confirm Business Logic Alignment

The current implementation calculates the loss per token as follows:

const lossPerToken = Math.abs((marginBufferInUsd - availableMarginInUsd) / formattedPositionSize);

let liquidationPrice;
if (formattedPositionSize > 0) {
  liquidationPrice = formattedMarketPrice - lossPerToken;
} else {
  liquidationPrice = formattedMarketPrice + lossPerToken;
}

Our investigation found that the tests in test/perps/offchain.test.ts verify the logic for long positions—for example, with inputs (availableMarginInUsd: 100, marginBufferInUsd: 20, formattedPositionSize: 1, formattedMarketPrice: 2000), the liquidation price comes out to be approximately 1920. For short positions, the same formula (when applied with, say, (availableMarginInUsd: 1000, marginBufferInUsd: 20, formattedPositionSize: -1, formattedMarketPrice: 2000)) produces a liquidation price significantly higher than the market price (i.e. 2000 + 980 = 2980).

Please confirm that this behavior—subtracting the loss per token from the market price for long positions and adding it for short positions—aligns with the intended business logic, especially given that a short position with a smaller margin buffer than available margin results in a much higher liquidation threshold.

@sudeepb02 sudeepb02 merged commit f13c0d4 into develop Apr 2, 2025
2 checks passed
@sudeepb02 sudeepb02 deleted the feat/offchain-liq-price branch April 2, 2025 09:41
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants