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

add megavault withdrawal fee estimation #2242

Merged
merged 5 commits into from
Sep 17, 2024
Merged

add megavault withdrawal fee estimation #2242

merged 5 commits into from
Sep 17, 2024

Conversation

tqin7
Copy link
Contributor

@tqin7 tqin7 commented Sep 12, 2024

Changelist

implement withdrawal fee estimation formula

Test Plan

unit tests

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 functions for calculating skew and spread in vault operations.
    • Added functionality to compute withdrawal slippage based on market conditions and vault leverage.
    • Implemented a utility for determining the minimum of two rational numbers.
  • Bug Fixes

    • Improved error handling for vault-related operations, including withdrawal validations.
  • Tests

    • Added comprehensive unit tests for new functions related to skew, spread, and withdrawal slippage.
  • Documentation

    • Introduced new error messages to enhance user understanding of withdrawal limits.

@tqin7 tqin7 requested a review from a team as a code owner September 12, 2024 01:16
Copy link

linear bot commented Sep 12, 2024

Copy link
Contributor

coderabbitai bot commented Sep 12, 2024

Walkthrough

The changes introduce new functionalities in the vault management system, including mathematical calculations for skew and spread, improved error handling, and enhanced withdrawal slippage assessments. New tests ensure the correctness of these calculations, while additional error definitions bolster validation logic.

Changes

File Path Change Summary
protocol/lib/big_math.go Added function BigRatMin for determining the minimum of two *big.Rat values.
protocol/lib/big_math_test.go Introduced TestBigRatMin to validate the functionality of BigRatMin with various test scenarios.
protocol/lib/vault/utils.go Added functions SkewAntiderivative and SpreadPpm for calculating vault skew and spread.
protocol/lib/vault/utils_test.go Introduced unit tests for SkewAntiderivative and SpreadPpm, covering various scenarios.
protocol/x/vault/keeper/orders.go Enhanced GetVaultClobOrders for improved order retrieval efficiency and clarity.
protocol/x/vault/keeper/vault.go Added functions GetVaultLeverageAndEquity and GetVaultClobPerpAndMarket for calculating leverage and retrieving market data.
protocol/x/vault/keeper/withdraw.go Introduced GetVaultWithdrawalSlippage for calculating slippage during withdrawals.
protocol/x/vault/keeper/withdraw_test.go Added unit tests for GetVaultWithdrawalSlippage, covering various scenarios and error conditions.
protocol/x/vault/types/errors.go Added ErrInvalidWithdrawalPortion and ErrInvalidSharesToWithdraw for validating withdrawal operations.

Suggested labels

indexer

Poem

In the vault where numbers dance,
Skew and spread take their chance.
With tests to guard each little change,
Our code grows strong, no need for range.
A rabbit hops with joy today,
For clearer paths in the vault's ballet! 🐇✨


Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1128b83 and b7456a2.

Files selected for processing (1)
  • protocol/x/vault/keeper/orders.go (5 hunks)
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/vault/keeper/orders.go

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>, 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 generate interesting stats about this repository and render them as a table.
    -- @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 resolve resolve all the CodeRabbit review comments.
  • @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: 1

Outside diff range and nitpick comments (1)
protocol/x/vault/keeper/orders.go (1)

Line range hint 159-338: Refactoring improves code quality, consider further decomposition.

The refactoring efforts in GetVaultClobOrders have significantly improved the code's readability, maintainability, and efficiency. The changes, such as consolidating retrieval operations, improving error handling, and refactoring calculations into separate methods, align with best practices like DRY and SRP.

However, the function still remains quite large and complex. Consider further decomposing it into smaller, more focused functions to enhance readability and maintainability. For example, the order construction logic could be extracted into a separate method.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 6db737c and 6db9974.

Files selected for processing (8)
  • protocol/lib/vault/utils.go (1 hunks)
  • protocol/lib/vault/utils_test.go (1 hunks)
  • protocol/x/vault/keeper/orders.go (5 hunks)
  • protocol/x/vault/keeper/vault.go (3 hunks)
  • protocol/x/vault/keeper/withdraw.go (1 hunks)
  • protocol/x/vault/keeper/withdraw_test.go (1 hunks)
  • protocol/x/vault/types/errors.go (2 hunks)
  • protocol/x/vault/types/expected_keepers.go (1 hunks)
Additional comments not posted (9)
protocol/lib/vault/utils.go (2)

14-38: LGTM!

The SkewAntiderivativePpm function correctly implements the given formula for calculating the skew antiderivative using big integers. The code is clear, readable, and handles large numbers appropriately. The function signature and naming are also suitable for the purpose.

The code changes are approved.


43-51: LGTM!

The SpreadPpm function correctly implements the given formula for calculating the spread using the lib.Max function and the appropriate fields from the QuotingParams and MarketParam structs. The function signature and naming are also suitable for the purpose.

The code changes are approved.

protocol/x/vault/types/expected_keepers.go (1)

49-52: LGTM!

The code changes are approved for the following reasons:

  • The new GetLiquidityTier method follows the standard Go conventions for defining an interface method.
  • The method expands the functionality of the PerpetualsKeeper interface to retrieve liquidity tier information, which aligns with the PR objective of implementing a withdrawal fee estimation formula.
  • The AI-generated summary provides additional context, indicating that the liquidity tier information may be essential for managing liquidity in the context of perpetual contracts.
protocol/x/vault/types/errors.go (1)

123-127: LGTM!

The new error variable ErrInvalidWithdrawalPortion is correctly defined with a unique error code and a descriptive message. It enhances the validation logic for withdrawal operations by clearly specifying the valid range for the withdrawal portion.

The code changes are approved.

protocol/lib/vault/utils_test.go (2)

14-69: LGTM!

The test function TestSkewAntiderivativePpm is well-structured and covers a good range of test cases. The test cases include various scenarios with different skew factors and leverages, including edge cases. The expected values are calculated correctly based on the formula mentioned in the comments. The test function uses the require.Equal assertion to compare the actual and expected values, which is a good practice.

The code changes are approved.


71-118: LGTM!

The test function TestSpreadPpm is well-structured and covers the important scenarios. The test cases cover different scenarios based on the relationship between SpreadMinPpm, SpreadBufferPpm, and MinPriceChangePpm. The expected values are calculated correctly based on the logic mentioned in the test case names. The test function uses the require.Equal assertion to compare the actual and expected values, which is a good practice.

The code changes are approved.

protocol/x/vault/keeper/vault.go (2)

65-97: LGTM!

The GetVaultLeverageAndEquity function is well-implemented and follows good coding practices. It correctly calculates the leverage of a vault based on its open notional and equity, handling the case when the equity is non-positive. The function is well-documented and uses the lib package for base-to-quote conversion and PPM calculation, promoting code reusability and maintainability.


137-178: LGTM!

The GetVaultClobPerpAndMarket function is well-structured and follows good error handling practices. It retrieves the necessary data for a vault in a step-by-step manner, properly handling errors at each step and providing appropriate error messages and context. The function uses the errorsmod package for consistent error management and is well-documented with clear input parameters and return values.

protocol/x/vault/keeper/withdraw_test.go (1)

21-394: LGTM!

The test function is well-structured and covers a good range of test cases. The test cases are well-documented and easy to understand. The test cases cover both success and error scenarios. The test cases use a table-driven approach, which is a good practice for writing tests. The test cases use a test app builder to set up the test environment, which is a good practice for writing tests. The test cases use the require package for assertions, which is a good practice for writing tests.

protocol/x/vault/keeper/withdraw.go Outdated Show resolved Hide resolved
@tqin7 tqin7 force-pushed the tq/tra-592 branch 2 times, most recently from 938f901 to 32e2eff Compare September 12, 2024 12:24
expectedSlippagePpm *big.Int
expectedErr string
}{
"Success: leverage 0, skew 2, spread 0.003, withdraw 10%": {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Add test where leverage ppm gets rounded down to 0?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

wouldn't that be testing leverage calculation instead of withdrawal?

Copy link
Contributor

Choose a reason for hiding this comment

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

Yes, it would be. Is there a test for the leverage calculation where the fact that it's in ppm leads to the some small leverage being rounded down to 0?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

added a test case where leverage * imf gets below 6 decimal places and thus gets rounded up to 1 ppm

Copy link
Contributor

Choose a reason for hiding this comment

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

No test where leverage ppm is 0 despite position size being non-negative?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

changed leverage to rational number

b.Mul(b, bigSkewFactorPpm)
b = lib.BigDivCeil(b, big.NewInt(3))

// normalize a and b.
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Maybe a bit more of a comment on the normalization (ppm * ppm * ppm / 1,000,000,000,000) = (ppm)?

vincentwschau
vincentwschau previously approved these changes Sep 12, 2024
Copy link
Contributor

@vincentwschau vincentwschau left a comment

Choose a reason for hiding this comment

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

LGTM on logic, math matches comments. Should wait for research to do a pass on math.

EDIT: Pending discussion on how withdrawal size is passed into the slippage function.

@vincentwschau vincentwschau dismissed their stale review September 12, 2024 15:57

Withdrawal sizes need work.

// = 0.0765
// slippage = min(0.0765, leverage * imf)
// = min(0.0765, 1.5 * 0.2) = 0.0765
expectedSlippagePpm: big.NewInt(76_500),
Copy link
Contributor

@matthewdowney matthewdowney Sep 13, 2024

Choose a reason for hiding this comment

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

Not sure if this is covered by the min withdrawal amount convo, but I get a different result (7.2%) for this situation:

from decimal import Decimal

def skew_antiderivative(skew_factor, leverage):
    return skew_factor**2 / 3 * leverage**3 + skew_factor * leverage**2


leverage = Decimal('1.5')
skew = Decimal('2')
withdrawer_share = Decimal('0.000001')
half_spread_bps = Decimal('30')

posterior_leverage = (leverage / (1 - withdrawer_share))
integral_a = skew_antiderivative(skew, posterior_leverage)
integral_b = skew_antiderivative(skew, leverage) 
integral = integral_a - integral_b
average_skew = integral / (posterior_leverage - leverage)
fee_bps = half_spread_bps * (average_skew + 1) * leverage

{
    "posterior_leverage": posterior_leverage,
    "integral_a": integral_a,
    "integral_b": integral_b,
    "integral": integral,
    "average_skew": average_skew,
    "fee_bps": fee_bps
}
{'posterior_leverage': Decimal('1.500001500001500001500001500'),
 'integral_a': Decimal('9.000022500040500063000089999'),
 'integral_b': Decimal('8.999999999999999999999999999'),
 'integral': Decimal('0.000022500040500063000090000'),
 'average_skew': Decimal('15.00001200001500001799995500'), # <- this is 15 not 16
 'fee_bps': Decimal('720.0005400006750008099979750')}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

i this case, i think it's because posterior_leverage gets rounded up from 1.5000015 to 1.500002 as we operate with 6 decimal places, resulting in fee being 0.765 instead of 0.750

Comment on lines 27 to 31
func (k Keeper) GetVaultWithdrawalSlippagePpm(
ctx sdk.Context,
vaultId types.VaultId,
sharesToWithdraw *big.Int,
) (*big.Int, error) {
Copy link
Contributor

Choose a reason for hiding this comment

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

non-blocking, I wonder if it would be better to have this be a state-less function instead that takes in quoting params + leverage + total shares + shares to withdraw, rather than fetching from state.
Benefits:

  • tests run a lot faster
  • [vague] can run multiple times w/o fetching state multiple times, perhaps if we change input params
    Cons:
  • more indirection?
  • more code?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

good thought. will keep this in mind when finishing up withdrawal and see if changing this to stateless makes sense

Comment on lines 96 to 101
// 3. average_skew = integral / (posterior_leverage - leverage)
estimatedSlippagePpm.Mul(estimatedSlippagePpm, bigOneMillion)
estimatedSlippagePpm = lib.BigDivCeil(
estimatedSlippagePpm,
posteriorLeveragePpm.Sub(posteriorLeveragePpm, leveragePpm),
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Since posterior_leverage and leverage are often close, as withdrawals get smaller, this denominator loses precision.

Would it be better to treat both leverages as ratios?

Define

  • o open notional (unsigned)
  • e vault equity, such that initial leverage l0 = o / e
  • m the integer number of shares being withdrawn
  • n the integer number of total shares

Then define posterior leverage l1 = l0 / (1 - m/n) = (o/e) / (1 - m/n)

And define change in leverage dl (which is the denominator here):

dl = l1 - l0 = om / e(n - m)

Now average skew s is still s = integral / dl, but since we have dl as a ratio, you can invert it and take:

s = integral / dl = integral * e(n - m) / om

I think this avoids the loss of precision discussed here

Comment on lines 104 to 110
estimatedSlippagePpm.Add(estimatedSlippagePpm, bigOneMillion)
estimatedSlippagePpm.Mul(estimatedSlippagePpm, leveragePpm)
estimatedSlippagePpm = lib.BigIntMulPpm(
estimatedSlippagePpm,
vault.SpreadPpm(&quotingParams, &marketParam),
)
estimatedSlippagePpm = lib.BigDivCeil(estimatedSlippagePpm, bigOneMillion)
Copy link
Contributor

Choose a reason for hiding this comment

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

One additional simplification to postpone division:

slippage = spread * (1 + s) * l0
         = spread * x

where

x = (1 + s) * l0
  = [1 + (integral * e(n - m) / om)] * (o / e)
  = [integral * (n - m) / m] + (o / e)

// = spread * (1 + integral * (n - m) / (ln - l(n - m))) * l
// = spread * (1 + integral * (n - m) / lm) * l
// = spread * (l + integral * (n - m) / m)
func (k Keeper) GetVaultWithdrawalSlippage(
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: Might as well convert back to a big.Int to return ppm slippage here rather than outside of this function?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

i was thinking that returning a rational number can allow parent functions to yield more accurate results (e.g. equity * (1 - slippage) can be more accurate if slippage isn't yet rounded to a big.Int yet)

@tqin7 tqin7 merged commit 4fc6109 into main Sep 17, 2024
22 checks passed
@tqin7 tqin7 deleted the tq/tra-592 branch September 17, 2024 19:17
@coderabbitai coderabbitai bot mentioned this pull request Sep 18, 2024
6 tasks
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.

3 participants