Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[CT-988] Include position quote balance in nc and mmr calculations #1869

Merged
merged 4 commits into from
Jul 9, 2024

Conversation

jayy04
Copy link
Contributor

@jayy04 jayy04 commented Jul 8, 2024

Changelist

[Describe or list the changes made in this PR]

Test Plan

[Describe how this PR was tested (if applicable)]

Author/Reviewer Checklist

  • If this PR has changes that result in a different app state given the same prior state and transaction list, manually add the state-breaking label.
  • If the PR has breaking postgres changes to the indexer add the indexer-postgres-breaking label.
  • If this PR isn't state-breaking but has changes that modify behavior in PrepareProposal or ProcessProposal, manually add the label proposal-breaking.
  • If this PR is one of many that implement a specific feature, manually label them all feature:[feature-name].
  • If you wish to for mergify-bot to automatically create a PR to backport your change to a release branch, manually add the label backport/[branch-name].
  • Manually add any of the following labels: refactor, chore, bug.

Summary by CodeRabbit

  • New Features
    • Introduced a method to retrieve the perpetual position quote balance for better risk calculations.
    • Added functionality to calculate and update asset positions using quote balances from perpetual positions.

Copy link

linear bot commented Jul 8, 2024

Copy link
Contributor

coderabbitai bot commented Jul 8, 2024

Walkthrough

This update introduces enhancements to the risk calculation process, improvements to perpetual positions handling in the ClOB (Central Limit Order Book), and adjustments to subaccount risk assessments. Key changes include renaming and refactoring functions, adding new test cases, and integrating additional logic for handling quote balances in perpetual positions.

Changes

Files Change Summary
protocol/x/clob/keeper/liquidations.go Updated GetBankruptcyPriceInQuoteQuantums and GetFillablePrice to use GetPositionNetNotionalValueAndMarginRequirements instead of GetNetCollateralAndMarginRequirements.
protocol/x/perpetuals/lib/lib.go, lib_test.go Renamed GetNetCollateralAndMarginRequirements, added a new variation, and updated tests with new parameter quoteBalance.
protocol/x/subaccounts/lib/updates.go, types/position_size.go Added and used GetQuoteBalance() method in PerpetualPosition for more accurate risk calculation in subaccounts.
protocol/indexer/events/subaccount_update.go Introduced logic for updating asset positions based on quote balances with new function AddQuoteBalanceFromPerpetualPositions.

Sequence Diagram(s)

Here's a high-level sequence diagram illustrating the changes to the GetBankruptcyPriceInQuoteQuantums function sequence flow.

sequenceDiagram
    participant Keeper
    participant ClOBModule
    participant PerpLib

    Keeper->>+ClOBModule: Call GetBankruptcyPriceInQuoteQuantums
    ClOBModule->>+PerpLib: Call GetPositionNetNotionalValueAndMarginRequirements for riskPosOld
    PerpLib-->>-ClOBModule: Return riskPosOld
    ClOBModule->>+PerpLib: Call GetPositionNetNotionalValueAndMarginRequirements for riskPosNew
    PerpLib-->>-ClOBModule: Return riskPosNew
    ClOBModule-->>-Keeper: Return Bankruptcy Price in Quote Quantums
Loading

Poem

In code's vast and tangled lands,
New paths emerge where logic stands.
With quote balances and risks anew,
Our subaccounts find clarity too.
Perpetual flows in elegant prose,
Here's to progress - onwards it goes! 🐇✨


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration 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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5b62cfa and 6ad2aea.

Files selected for processing (5)
  • protocol/x/clob/keeper/liquidations.go (2 hunks)
  • protocol/x/perpetuals/lib/lib.go (2 hunks)
  • protocol/x/perpetuals/lib/lib_test.go (2 hunks)
  • protocol/x/subaccounts/lib/updates.go (1 hunks)
  • protocol/x/subaccounts/types/position_size.go (1 hunks)
Additional comments not posted (7)
protocol/x/perpetuals/lib/lib.go (2)

Line range hint 39-65:
LGTM!

The renaming of the method aligns with its functionality. The implementation is correct.


67-86: LGTM!

The method correctly calls GetPositionNetNotionalValueAndMarginRequirements and includes additional calculations for the quote balance.

protocol/x/subaccounts/lib/updates.go (1)

366-367: LGTM!

The method correctly includes pos.GetQuoteBalance() for risk calculation, aligning with the PR objectives.

protocol/x/perpetuals/lib/lib_test.go (1)

Line range hint 162-220:
LGTM!

The test cases comprehensively cover various scenarios with different quoteBalance values.

protocol/x/clob/keeper/liquidations.go (3)

454-454: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to GetPositionNetNotionalValueAndMarginRequirements match the new usage.

Verification successful

Verification Successful!

The function GetPositionNetNotionalValueAndMarginRequirements is used correctly across the codebase.

  • protocol/x/perpetuals/lib/lib.go
  • protocol/x/clob/keeper/liquidations.go
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `GetPositionNetNotionalValueAndMarginRequirements` match the new usage.

# Test: Search for the function usage. Expect: Only occurrences of the new function name.
rg --type go $'GetPositionNetNotionalValueAndMarginRequirements'

Length of output: 716


Script:

#!/bin/bash
# Fetch lines around each occurrence of `GetPositionNetNotionalValueAndMarginRequirements` for detailed inspection.

# Fetch lines in `protocol/x/perpetuals/lib/lib.go`
rg --type go --context 5 'GetPositionNetNotionalValueAndMarginRequirements' protocol/x/perpetuals/lib/lib.go

# Fetch lines in `protocol/x/clob/keeper/liquidations.go`
rg --type go --context 5 'GetPositionNetNotionalValueAndMarginRequirements' protocol/x/clob/keeper/liquidations.go

Length of output: 1660


544-544: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to GetPositionNetNotionalValueAndMarginRequirements match the new usage.

Verification successful

Verified: The function GetPositionNetNotionalValueAndMarginRequirements is used consistently and correctly across the codebase.

  • protocol/x/perpetuals/lib/lib.go: Definition and usage verified.
  • protocol/x/clob/keeper/liquidations.go: Usage verified.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `GetPositionNetNotionalValueAndMarginRequirements` match the new usage.

# Test: Search for the function usage. Expect: Only occurrences of the new function name.
rg --type go $'GetPositionNetNotionalValueAndMarginRequirements'

Length of output: 716


Script:

#!/bin/bash
# Description: Fetch the context around each occurrence of `GetPositionNetNotionalValueAndMarginRequirements` for verification.

# Fetch context around the definition and usage in lib.go
rg --type go --context 5 'GetPositionNetNotionalValueAndMarginRequirements' protocol/x/perpetuals/lib/lib.go

# Fetch context around the usage in liquidations.go
rg --type go --context 5 'GetPositionNetNotionalValueAndMarginRequirements' protocol/x/clob/keeper/liquidations.go

Length of output: 1660


460-460: LGTM! But verify the function usage in the codebase.

The code changes are approved.

However, ensure that all function calls to GetPositionNetNotionalValueAndMarginRequirements match the new usage.

Verification successful

Verified: Function usage is consistent

All function calls to GetPositionNetNotionalValueAndMarginRequirements in protocol/x/clob/keeper/liquidations.go match the expected parameters as defined in protocol/x/perpetuals/lib/lib.go.

  • protocol/x/clob/keeper/liquidations.go: Lines 460-460
  • protocol/x/clob/keeper/liquidations.go: Other occurrences
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify all function calls to `GetPositionNetNotionalValueAndMarginRequirements` match the new usage.

# Test: Search for the function usage. Expect: Only occurrences of the new function name.
rg --type go $'GetPositionNetNotionalValueAndMarginRequirements'

Length of output: 716


Script:

#!/bin/bash
# Extract the function definition from protocol/x/perpetuals/lib/lib.go
ast-grep --lang go --pattern $'func GetPositionNetNotionalValueAndMarginRequirements($_, $_) {
  $$$
}' | head -n 20

# Extract the three occurrences in protocol/x/clob/keeper/liquidations.go
rg -A 5 'GetPositionNetNotionalValueAndMarginRequirements' protocol/x/clob/keeper/liquidations.go

Length of output: 638


Script:

#!/bin/bash
# Extract the function definition from protocol/x/perpetuals/lib/lib.go
ast-grep --lang go --pattern $'func GetPositionNetNotionalValueAndMarginRequirements($_, $_) {
  $$$
}'

Length of output: 104


Script:

#!/bin/bash
# Search for the function definition in protocol/x/perpetuals/lib/lib.go
rg 'func GetPositionNetNotionalValueAndMarginRequirements' protocol/x/perpetuals/lib/lib.go -A 10

Length of output: 369

Comment on lines 95 to 102
// Get the perpetual position quote balance in big.Int.
func (m *PerpetualPosition) GetQuoteBalance() *big.Int {
if m == nil {
return new(big.Int)
}

return m.QuoteBalance.BigInt()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider returning nil in case of a nil receiver.

Returning nil instead of a new big.Int can better indicate the absence of a PerpetualPosition.

-	if m == nil {
-		return new(big.Int)
+	if m == nil {
+		return nil
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Get the perpetual position quote balance in big.Int.
func (m *PerpetualPosition) GetQuoteBalance() *big.Int {
if m == nil {
return new(big.Int)
}
return m.QuoteBalance.BigInt()
}
// Get the perpetual position quote balance in big.Int.
func (m *PerpetualPosition) GetQuoteBalance() *big.Int {
if m == nil {
return nil
}
return m.QuoteBalance.BigInt()
}

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6ad2aea and eeb7da6.

Files selected for processing (1)
  • protocol/x/subaccounts/lib/updates.go (2 hunks)
Files skipped from review due to trivial changes (1)
  • protocol/x/subaccounts/lib/updates.go

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between eeb7da6 and 2784d6a.

Files selected for processing (1)
  • protocol/x/subaccounts/types/position_size.go (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/subaccounts/types/position_size.go

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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 2784d6a and 59b15da.

Files selected for processing (1)
  • protocol/indexer/events/subaccount_update.go (2 hunks)
Additional comments not posted (2)
protocol/indexer/events/subaccount_update.go (2)

4-9: Imports look good.

The new imports for math/big, assettypes, and salib are necessary for the added functionalities.


28-35: LGTM! Ensure integration with the rest of the codebase.

The updated logic in NewSubaccountUpdateEvent correctly uses AddQuoteBalanceFromPerpetualPositions for updating asset positions.

Please verify that this change integrates correctly with the rest of the codebase and that all relevant parts of the application are updated accordingly.

Comment on lines +37 to +59
func AddQuoteBalanceFromPerpetualPositions(
perpetualPositions []*satypes.PerpetualPosition,
assetPositions []*satypes.AssetPosition,
) []*satypes.AssetPosition {
quoteBalance := new(big.Int)
for _, position := range perpetualPositions {
quoteBalance.Add(quoteBalance, position.GetQuoteBalance())
}

if quoteBalance.Sign() == 0 {
return assetPositions
}

// Add the quote balance to asset positions.
return salib.CalculateUpdatedAssetPositions(
assetPositions,
[]satypes.AssetUpdate{
{
AssetId: assettypes.AssetUsdc.Id,
BigQuantumsDelta: quoteBalance,
},
},
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider simplifying the logic for handling quote balances.

The function AddQuoteBalanceFromPerpetualPositions can be simplified by directly returning the updated asset positions without checking if quoteBalance is zero.

func AddQuoteBalanceFromPerpetualPositions(
	perpetualPositions []*satypes.PerpetualPosition,
	assetPositions []*satypes.AssetPosition,
) []*satypes.AssetPosition {
	quoteBalance := new(big.Int)
	for _, position := range perpetualPositions {
		quoteBalance.Add(quoteBalance, position.GetQuoteBalance())
	}

	// Simplify by directly returning updated asset positions
	return salib.CalculateUpdatedAssetPositions(
		assetPositions,
		[]satypes.AssetUpdate{
			{
				AssetId:          assettypes.AssetUsdc.Id,
				BigQuantumsDelta: quoteBalance,
			},
		},
	)
}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func AddQuoteBalanceFromPerpetualPositions(
perpetualPositions []*satypes.PerpetualPosition,
assetPositions []*satypes.AssetPosition,
) []*satypes.AssetPosition {
quoteBalance := new(big.Int)
for _, position := range perpetualPositions {
quoteBalance.Add(quoteBalance, position.GetQuoteBalance())
}
if quoteBalance.Sign() == 0 {
return assetPositions
}
// Add the quote balance to asset positions.
return salib.CalculateUpdatedAssetPositions(
assetPositions,
[]satypes.AssetUpdate{
{
AssetId: assettypes.AssetUsdc.Id,
BigQuantumsDelta: quoteBalance,
},
},
)
func AddQuoteBalanceFromPerpetualPositions(
perpetualPositions []*satypes.PerpetualPosition,
assetPositions []*satypes.AssetPosition,
) []*satypes.AssetPosition {
quoteBalance := new(big.Int)
for _, position := range perpetualPositions {
quoteBalance.Add(quoteBalance, position.GetQuoteBalance())
}
// Simplify by directly returning updated asset positions
return salib.CalculateUpdatedAssetPositions(
assetPositions,
[]satypes.AssetUpdate{
{
AssetId: assettypes.AssetUsdc.Id,
BigQuantumsDelta: quoteBalance,
},
},
)
}

@jayy04 jayy04 merged commit 3161af0 into main Jul 9, 2024
18 checks passed
@jayy04 jayy04 deleted the jy/include-qb branch July 9, 2024 20:02
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

Successfully merging this pull request may close these issues.

2 participants