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

[chore] Move perpetuals/keeper helper functions to perpetuals/lib #1678

Merged
merged 2 commits into from
Jun 13, 2024

Conversation

BrendanChou
Copy link
Contributor

@BrendanChou BrendanChou commented Jun 12, 2024

Changelist

Move x/perpetuals/keeper/perpetual.go helper functions to x/perpeptuals/lib for clarity. This is the first step in refactoring some of the margining functions for performance.

Test Plan

  • Added new units tests (and benchmarks) for these functions which did not have unit tests before

Summary by CodeRabbit

  • Refactor

    • Moved functions related to net notional, margin requirements, and settlement calculations to a new package for better modularity.
  • Tests

    • Added benchmarking and testing functions for settlement, net notional, and margin requirement calculations.
  • Style

    • Reordered and cleaned up import statements in test files.

Copy link
Contributor

coderabbitai bot commented Jun 12, 2024

Walkthrough

The recent changes involve refactoring and modularizing code related to perpetual contract calculations. Key functions for net notional, margin requirements, and settlement calculations have been moved from the Keeper struct to a new package, perplib. This refactor enhances code organization and reusability. Additionally, corresponding tests and benchmarks have been added to ensure the accuracy and performance of these calculations.

Changes

Files/Paths Change Summaries
protocol/daemons/liquidation/client/sub_task_runner.go Replaced references to perpkeeper with perplib for functions related to net notional and margin requirements in CheckSubaccountCollateralization.
protocol/x/perpetuals/keeper/perpetual.go Moved functions for net notional, margin requirements, and settlement calculations to perplib.
protocol/x/perpetuals/keeper/perpetual_test.go Reordered import statements and removed unused imports.
protocol/x/perpetuals/lib/lib.go Introduced new functions for calculating settlement amounts, net notionals, and margin requirements in perplib.
protocol/x/perpetuals/lib/lib_test.go Added benchmarking and testing functions for settlement, net notional, and margin requirement calculations.
protocol/x/subaccounts/keeper/subaccount.go Updated import from perpkeeper to perplib and adjusted function calls accordingly.

Poem

In the land of code, where logic thrives,
Refactors bloom, and new packages arrive.
Perplib now holds the calculations dear,
Making our perpetuals crystal clear.
With tests and benchmarks, we ensure the might,
Of every quantum, margin, and net notional right.
🐇✨


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.

@BrendanChou BrendanChou changed the title Move perpetuals lib functions to their own pacakge [chore] Move perpetuals lib functions to their own pacakge Jun 12, 2024
@BrendanChou BrendanChou changed the title [chore] Move perpetuals lib functions to their own pacakge [chore] Move perpetuals/keeper helper functions to perpetuals/lib Jun 12, 2024
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 b431e04 and 74b5c63.

Files selected for processing (6)
  • protocol/daemons/liquidation/client/sub_task_runner.go (3 hunks)
  • protocol/x/perpetuals/keeper/perpetual.go (5 hunks)
  • protocol/x/perpetuals/keeper/perpetual_test.go (2 hunks)
  • protocol/x/perpetuals/lib/lib.go (1 hunks)
  • protocol/x/perpetuals/lib/lib_test.go (1 hunks)
  • protocol/x/subaccounts/keeper/subaccount.go (2 hunks)
Files skipped from review due to trivial changes (1)
  • protocol/x/perpetuals/keeper/perpetual_test.go
Additional context used
golangci-lint
protocol/daemons/liquidation/client/sub_task_runner.go

28-28: undefined: Client (typecheck)


42-42: undefined: Client (typecheck)


108-108: undefined: Client (typecheck)


127-127: undefined: newContextWithQueryBlockHeight (typecheck)

protocol/x/perpetuals/keeper/perpetual.go

37-37: undefined: Keeper (typecheck)


49-49: undefined: Keeper (typecheck)


65-65: undefined: Keeper (typecheck)

Additional comments not posted (16)
protocol/x/perpetuals/lib/lib.go (2)

11-36: The function GetSettlementPpmWithPerpetual is well-implemented with clear logic handling the settlement calculation based on the perpetual's funding index and the provided index. The use of big.Int for high precision arithmetic is appropriate here. Good use of early return when indexDelta is zero to optimize performance.


38-58: The function GetNetNotionalInQuoteQuantums correctly converts base quantums to quote quantums using the BaseToQuoteQuantums function. It handles the conversion based on market price and atomic resolution, which is crucial for financial calculations. The function is concise and maintains readability.

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

16-29: The benchmark BenchmarkGetSettlementPpmWithPerpetual is correctly set up to measure the performance of the GetSettlementPpmWithPerpetual function. It uses a variety of inputs to simulate different scenarios.


31-96: The unit tests for GetSettlementPpmWithPerpetual cover a variety of cases including zero, positive, and negative index deltas. The use of table-driven tests enhances the readability and maintainability of the test code. Good use of the require.Equal to assert expected outcomes.


98-116: The benchmark BenchmarkGetNetNotionalInQuoteQuantums is set up properly. It tests the function under a heavy load to ensure performance is maintained.


118-164: The tests for GetNetNotionalInQuoteQuantums are comprehensive, covering scenarios with zero, positive, and negative quantums. These tests ensure that the function behaves correctly across different market conditions.


166-190: The benchmark BenchmarkGetMarginRequirementsInQuoteQuantums is well-constructed, testing the function with a large number of iterations to assess its performance under stress.


192-278: The tests for GetMarginRequirementsInQuoteQuantums are thorough, covering various scenarios including different levels of open interest. The use of custom types and helper functions like big_testutil.MustFirst is noted for ensuring the correctness of big integer operations.

protocol/daemons/liquidation/client/sub_task_runner.go (1)

Line range hint 347-360: The integration of perplib functions GetNetNotionalInQuoteQuantums and GetMarginRequirementsInQuoteQuantums in the liquidation logic is correctly implemented. These changes are part of the refactoring to use the newly separated library functions. Ensure that all references to these functions are updated across the entire codebase.

Verification successful

The search results confirm that the functions GetNetNotionalInQuoteQuantums and GetMarginRequirementsInQuoteQuantums are correctly referenced in the codebase, including the sub_task_runner.go file. The integration of these functions appears consistent with the new library usage.

  • protocol/x/perpetuals/keeper/perpetual.go
  • protocol/daemons/liquidation/client/sub_task_runner.go
Scripts executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Description: Verify all function calls to `GetNetNotionalInQuoteQuantums` and `GetMarginRequirementsInQuoteQuantums` match the new library usage.

# Test: Search for the function usage. Expect: Only occurrences of the new library usage.
rg --type python $'GetNetNotionalInQuoteQuantums|GetMarginRequirementsInQuoteQuantums'

Length of output: 118



Script:

#!/bin/bash
# Description: Verify all function calls to `GetNetNotionalInQuoteQuantums` and `GetMarginRequirementsInQuoteQuantums` match the new library usage.

# Test: Search for the function usage. Expect: Only occurrences of the new library usage.
rg --type go 'GetNetNotionalInQuoteQuantums|GetMarginRequirementsInQuoteQuantums'

Length of output: 1779

protocol/x/subaccounts/keeper/subaccount.go (2)

25-25: The import of perplib aligns with the PR's objective to use functions from the new perplib package. Ensure that all functions previously accessed through perpkeeper are now correctly accessed through perplib.


491-491: The replacement of the old function with perplib.GetSettlementPpmWithPerpetual is consistent with the PR's goals. Verify that this new function integrates seamlessly with the existing system and that all dependent functionalities are updated accordingly.

protocol/x/perpetuals/keeper/perpetual.go (5)

31-31: Ensure the new import alias perplib is consistently used across the file for accessing functions from the perplib package.


Line range hint 37-37: The static analysis tool has flagged the Keeper type as undefined. This is likely a false positive, as the Keeper type should be defined in another part of the codebase or an imported package. Verify that the Keeper type is correctly defined and accessible in this context.

Also applies to: 49-49, 65-65


821-821: The function GetNetNotionalInQuoteQuantums has been correctly updated to use the new library. Ensure that all calls to this function are updated to handle any new parameters or changes in behavior.


926-926: The function GetMarginRequirementsInQuoteQuantums has been moved to the new library and is being correctly referenced here. Review all usages to ensure they are updated accordingly.

Verification successful

The function GetMarginRequirementsInQuoteQuantums has been correctly referenced in the new library across the codebase.

  • protocol/x/perpetuals/lib/lib_test.go
  • protocol/x/perpetuals/lib/lib.go
  • protocol/x/perpetuals/keeper/perpetual.go
  • protocol/daemons/liquidation/client/sub_task_runner.go
Scripts executed

The following scripts were executed for the analysis:


Script:

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

# Test: Search for the function usage. Expect: Only occurances of the new signature.
rg --type python $'GetMarginRequirementsInQuoteQuantums'

Length of output: 86



Script:

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

# Test: Search for the function usage. Expect: Only occurrences of the new signature.
rg --type go 'GetMarginRequirementsInQuoteQuantums'

Length of output: 903


961-961: The function GetSettlementPpmWithPerpetual has been moved to the new library. This change should be reflected wherever the function is called. Verify that the new function signature and behavior are correctly integrated.

Comment on lines +60 to +106
// GetMarginRequirementsInQuoteQuantums returns initial and maintenance margin requirements
// in quote quantums, given the position size in base quantums.
func GetMarginRequirementsInQuoteQuantums(
perpetual types.Perpetual,
marketPrice pricestypes.MarketPrice,
liquidityTier types.LiquidityTier,
bigQuantums *big.Int,
) (
bigInitialMarginQuoteQuantums *big.Int,
bigMaintenanceMarginQuoteQuantums *big.Int,
) {
// Always consider the magnitude of the position regardless of whether it is long/short.
bigAbsQuantums := new(big.Int).Abs(bigQuantums)

// Calculate the notional value of the position in quote quantums.
bigQuoteQuantums := lib.BaseToQuoteQuantums(
bigAbsQuantums,
perpetual.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)
// Calculate the perpetual's open interest in quote quantums.
openInterestQuoteQuantums := lib.BaseToQuoteQuantums(
perpetual.OpenInterest.BigInt(), // OpenInterest is represented as base quantums.
perpetual.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)

// Initial margin requirement quote quantums = size in quote quantums * initial margin PPM.
bigBaseInitialMarginQuoteQuantums := liquidityTier.GetInitialMarginQuoteQuantums(
bigQuoteQuantums,
big.NewInt(0), // pass in 0 as open interest to get base IMR.
)
// Maintenance margin requirement quote quantums = IM in quote quantums * maintenance fraction PPM.
bigMaintenanceMarginQuoteQuantums = lib.BigMulPpm(
bigBaseInitialMarginQuoteQuantums,
lib.BigU(liquidityTier.MaintenanceFractionPpm),
true,
)

bigInitialMarginQuoteQuantums = liquidityTier.GetInitialMarginQuoteQuantums(
bigQuoteQuantums,
openInterestQuoteQuantums, // pass in current OI to get scaled IMR.
)
return bigInitialMarginQuoteQuantums, bigMaintenanceMarginQuoteQuantums
}
Copy link
Contributor

Choose a reason for hiding this comment

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

The GetMarginRequirementsInQuoteQuantums function is comprehensive and handles both initial and maintenance margin calculations. It correctly considers the absolute value of quantums to ensure that the direction of the position does not affect the margin requirements. The use of helper functions like BaseToQuoteQuantums and BigMulPpm helps maintain modularity and reusability. However, consider adding more comments to explain the logic, especially around the calculations involving open interest caps.

Consider adding detailed comments to explain the logic behind the calculations, especially how the open interest affects the margin requirements.

@BrendanChou BrendanChou merged commit 87a919e into main Jun 13, 2024
19 checks passed
@BrendanChou BrendanChou deleted the bc/perpetuals/lib branch June 13, 2024 14:10
mergify bot pushed a commit that referenced this pull request Jun 26, 2024
…#1678)

(cherry picked from commit 87a919e)

# Conflicts:
#	protocol/x/perpetuals/keeper/perpetual.go
@teddyding
Copy link
Contributor

@Mergifyio backport release/protocol/v5.1.x

Copy link
Contributor

mergify bot commented Jun 27, 2024

backport release/protocol/v5.1.x

✅ Backports have been created

teddyding pushed a commit that referenced this pull request Jun 27, 2024
…#1678)

(cherry picked from commit 87a919e)

# Conflicts:
#	protocol/x/perpetuals/keeper/perpetual.go
teddyding added a commit that referenced this pull request Jun 27, 2024
… (backport #1678) (#1791)

Co-authored-by: Brendan Chou <[email protected]>
Co-authored-by: Teddy Ding <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

Successfully merging this pull request may close these issues.

2 participants