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

[OTE-816] Update Revshare logic for affiliates #2298

Merged
merged 14 commits into from
Sep 24, 2024
Merged

Conversation

affanv14
Copy link
Contributor

@affanv14 affanv14 commented Sep 19, 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

    • Enhanced revenue sharing calculations to include affiliate fee impacts, improving accuracy in revenue distribution.
  • Bug Fixes

    • Adjusted expected balances in fee distribution tests to reflect updated revenue share logic.
  • Refactor

    • Streamlined test cases by removing scenarios related to exceeding net fees, indicating a refined focus in revenue sharing behavior.
    • Simplified the Keeper struct by removing unnecessary dependencies related to revenue sharing.
    • Removed the RevShareKeeper interface and associated parameters from various components, simplifying interactions within the system.

@affanv14 affanv14 requested a review from a team as a code owner September 19, 2024 18:42
Copy link

linear bot commented Sep 19, 2024

Copy link
Contributor

coderabbitai bot commented Sep 19, 2024

Warning

Rate limit exceeded

@teddyding has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 29 minutes and 13 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 098ad3d and e98790b.

Walkthrough

The changes involve significant modifications to the revenue sharing functionality within the protocol. Key alterations include the removal of the app.RevShareKeeper parameter from various function signatures, enhancements to the GetAllRevShares and getAffiliateRevShares methods for improved revenue share calculations, and updates to test cases reflecting these changes, including adjustments to expected balances and the removal of certain invalid scenario tests.

Changes

File Path Change Summary
protocol/app/app.go Removed app.RevShareKeeper parameter from New function call, simplifying the function's signature.
protocol/x/revshare/keeper/revshare.go Modified getAffiliateRevShares to return an additional *big.Int for total fees shared, impacting GetAllRevShares calculations. Updated fee source for revenue shares to REV_SHARE_FEE_SOURCE_NET_PROTOCOL_REVENUE.
protocol/x/revshare/keeper/revshare_test.go Adjusted revenue share configurations with reduced QuoteQuantums for various recipients. Removed test cases for exceeding net fees from market mappers and affiliates, indicating a shift in focus for tests.
protocol/x/subaccounts/keeper/keeper.go Removed revShareKeeper field from Keeper struct and its corresponding parameter from NewKeeper function.
protocol/x/subaccounts/keeper/transfer_test.go Restructured TestDistributeFees to use a new revShare structure for revenue sharing, updating expected balances for accounts involved in fee distribution.
protocol/x/subaccounts/types/expected_keepers.go Removed RevShareKeeper interface, eliminating its associated method.
protocol/testutil/keeper/clob.go Removed revShareKeeper parameter from NewClobKeepersTestContextWithUninitializedMemStore function call.
protocol/testutil/keeper/listing.go Removed revShareKeeper parameter from ListingKeepers function call.
protocol/testutil/keeper/sending.go Removed revShareKeeper parameter from SendingKeepersWithSubaccountsKeeper function call.
protocol/testutil/keeper/subaccounts.go Removed revShareKeeper parameter from SubaccountsKeepers and createSubaccountsKeeper functions.

Possibly related PRs

Suggested labels

revshare, feature:indexer/affiliates

Suggested reviewers

  • teddyding

Poem

🐰 In the fields where numbers play,
Revenue shares find their way.
Affiliates dance, fees align,
With new logic, all is fine.
Hopping forth, we celebrate,
Changes sweet, oh, what a fate! 🌟


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 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 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.

@@ -856,52 +856,6 @@ func TestKeeper_GetAllRevShares_Invalid(t *testing.T) {
require.NoError(t, err)
},
},
{
name: "Total fees shared exceeds net fees from market mapper and affiliates",
Copy link
Contributor Author

Choose a reason for hiding this comment

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

These tests wont work anymore

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

Outside diff range and nitpick comments (2)
protocol/x/revshare/keeper/revshare.go (2)

Line range hint 227-251: Update unit tests to cover changes in getAffiliateRevShares

The function getAffiliateRevShares now returns an additional *big.Int representing affiliateFeesShared. Ensure that unit tests are updated or added to cover this new return value and to verify the correctness of affiliateFeesShared in various scenarios.


227-227: Document the new return value in getAffiliateRevShares

Update the function comment for getAffiliateRevShares to include information about the new *big.Int return value affiliateFeesShared. This helps maintain clarity for future maintainers.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between cee80fc and 2060d21.

Files selected for processing (3)
  • protocol/x/revshare/keeper/revshare.go (3 hunks)
  • protocol/x/revshare/keeper/revshare_test.go (8 hunks)
  • protocol/x/subaccounts/keeper/transfer_test.go (1 hunks)
Additional comments not posted (5)
protocol/x/revshare/keeper/revshare_test.go (2)

Line range hint 337-364: LGTM!

The changes in the test cases consistently reduce the expected QuoteQuantums for various recipients and fee sources. This suggests a deliberate adjustment in the revenue share calculation, potentially to align with updated business requirements or to optimize the distribution of fees among the participants.

The reductions appear to be proportional across the test cases, maintaining the overall integrity of the revenue share logic. The updated values should be verified against the intended revenue share model to ensure accuracy.


Line range hint 848-860: Verify the reason for removing the test cases.

The test cases that specifically checked for exceeding net fees from market mappers and affiliates have been removed. This suggests a change in the validation logic or requirements related to these entities.

Please confirm the following:

  1. Is the validation for exceeding net fees from market mappers and affiliates still necessary? If not, please provide the rationale for removing these test cases.
  2. Are there any alternative mechanisms in place to validate the fee distribution for market mappers and affiliates?

Ensuring comprehensive test coverage is crucial for maintaining the integrity of the revenue share system. If the removed test cases are no longer relevant, please consider adding comments to document the reasons for their removal.

protocol/x/subaccounts/keeper/transfer_test.go (1)

1503-1506: LGTM!

The updated expected balances for the fee module account, market mapper account, affiliate account, and unconditional rev share account are calculated correctly based on the respective revenue share percentages.

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

184-184: Ensure getMarketMapperRevShare handles updated net fees correctly

Passing the adjusted netFeesSubAffiliateFeesShared to getMarketMapperRevShare is appropriate. Verify that getMarketMapperRevShare correctly handles cases where the net fees might be reduced due to affiliate fee sharing.


Line range hint 227-251: Ensure all callers handle the new return value from getAffiliateRevShares

With the addition of the new return value *big.Int, verify that all callers of getAffiliateRevShares have been updated to handle the extra return parameter to prevent potential runtime errors.

Run the following script to identify all usages of getAffiliateRevShares:

Verification successful

To ensure a comprehensive verification, we need to perform two additional checks. First, let's search for any other potential usages of the function, and then we'll examine the context around the function call we found.


Changes to getAffiliateRevShares have been correctly implemented

The verification process has confirmed that the new return value from getAffiliateRevShares is being properly handled in its only usage within the codebase. The function call correctly assigns three variables, including the new affiliateFeesShared return value, which is then used in subsequent calculations. No other calls to this function were found in the codebase, so no further updates are necessary.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all usages of `getAffiliateRevShares` to ensure they are handling the new return value.

# Search for the function calls in the Go codebase.
rg --type go --fixed-strings 'getAffiliateRevShares(' -A 2

Length of output: 550


Script:

#!/bin/bash
# Search for any mentions of 'getAffiliateRevShares' in the entire codebase
rg --type go 'getAffiliateRevShares'

# Show more context around the function call we found
rg --type go --fixed-strings 'getAffiliateRevShares(' -B 5 -A 10

Length of output: 2723

Comment on lines 174 to 179
affiliateRevShares, affiliateFeesShared, err := k.getAffiliateRevShares(ctx, fill, affiliatesWhitelistMap)
if err != nil {
return types.RevSharesForFill{}, err
}

unconditionalRevShares, err := k.getUnconditionalRevShares(ctx, netFees)
netFeesSubAffiliateFeesShared := big.NewInt(0).Sub(netFees, affiliateFeesShared)
unconditionalRevShares, err := k.getUnconditionalRevShares(ctx, netFeesSubAffiliateFeesShared)
Copy link
Contributor

Choose a reason for hiding this comment

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

Verify that netFeesSubAffiliateFeesShared is non-negative after subtraction

Subtracting affiliateFeesShared from netFees may result in netFeesSubAffiliateFeesShared becoming negative if affiliateFeesShared exceeds netFees. This could lead to unexpected behavior in subsequent revenue share calculations.

Consider adding a check to ensure netFeesSubAffiliateFeesShared is not negative, or handle scenarios where it could be zero or negative appropriately.

}

takerAffiliateAddr, feeSharePpm, exists, err := k.affiliatesKeeper.GetTakerFeeShare(
ctx, takerAddr, affiliatesWhitelistMap)
if err != nil {
return nil, err
return nil, big.NewInt(0), err
Copy link
Contributor

Choose a reason for hiding this comment

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

Return nil for affiliateFeesShared when an error occurs

In the error case at line 237, consider returning nil for affiliateFeesShared instead of big.NewInt(0). This makes it clear that the value is invalid due to the error, aligning with common Go practices.

Apply this diff to adjust the return value:

-return nil, big.NewInt(0), err
+return nil, nil, err
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
return nil, big.NewInt(0), err
return nil, nil, err

@@ -171,17 +171,17 @@ func (k Keeper) GetAllRevShares(
makerFees := fill.MakerFeeQuoteQuantums
Copy link
Contributor

@teddyding teddyding Sep 19, 2024

Choose a reason for hiding this comment

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

Let's also change REV_SHARE_FEE_SOURCE_NET_FEE to REV_SHARE_FEE_SOURCE_NET_PROTOCOL_REVENUE to disambiguate

NET_FEE could be understood as taker fee minus rebates


totalFeesShared := big.NewInt(0)
takerFees := fill.TakerFeeQuoteQuantums
makerFees := fill.MakerFeeQuoteQuantums
netFees := big.NewInt(0).Add(takerFees, makerFees)

affiliateRevShares, err := k.getAffiliateRevShares(ctx, fill, affiliatesWhitelistMap)
affiliateRevShares, affiliateFeesShared, err := k.getAffiliateRevShares(ctx, fill, affiliatesWhitelistMap)
if err != nil {
return types.RevSharesForFill{}, err
Copy link
Contributor

Choose a reason for hiding this comment

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

Comment on caller function persistMatchedOrders:

Instead propagating error returned from GetAllRevShares (which would ultimately fail the match transaction), it's better to just pass in empty RevSharesForFill to DistributeFees. This way if any rev share calculation encounters issue, the chain will continue to be able to process matches (without rev share).

Order matching + rev share both working > Only order matching working > Order matching not working

Copy link
Contributor Author

Choose a reason for hiding this comment

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

sounds good. I'll add some error logs to catch in case it fails

Copy link
Contributor

Choose a reason for hiding this comment

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

Did we do this in this PR? Or plan to do in another one?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is done in the PR . Check here. Also updated tests in revshare_test.go

Copy link
Contributor

@teddyding teddyding Sep 24, 2024

Choose a reason for hiding this comment

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

Oh, the original comment was suggesting that we keep GetAllRevShares behavior as this but handle error differently in persistMatchedOrders, since it's the caller responsibility to determine what to do with the returned error from GetAllRevShares

Changing GetAllRevShares behavior works too but we are changing the signature/expectation of the function (e.g. it doesn't make sense to have this function return error anymore, it's always nil)

We should either:

  • Keep GetAllRevShares as is, and just log out error (don't propogate errors further up) in persistMatchedOrders.
  • Fully change signature of GetAllRevShares so it doesn't return errors anymore, maybe even rename it to GetAllValidRevShares

The first seems slightly cleaner to me since we just need one error log instead of multiple

if err != nil {
return types.RevSharesForFill{}, err
}

unconditionalRevShares, err := k.getUnconditionalRevShares(ctx, netFees)
netFeesSubAffiliateFeesShared := big.NewInt(0).Sub(netFees, affiliateFeesShared)
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
netFeesSubAffiliateFeesShared := big.NewInt(0).Sub(netFees, affiliateFeesShared)
netFeesSubAffiliateFeesShared := new(big.Int).Sub(
netFees,
affiliateFeesShared,
)

@@ -1500,10 +1500,10 @@ func TestDistributeFees(t *testing.T) {
MonthlyRollingTakerVolumeQuantums: 1_000_000,
},
expectedSubaccountsModuleAccBalance: big.NewInt(100), // 600 - 500
expectedFeeModuleAccBalance: big.NewInt(2888), // 2500 + 500 - 50
expectedMarketMapperAccBalance: big.NewInt(50), // 10% of 500
expectedFeeModuleAccBalance: big.NewInt(2892), // 2500 + 500 - 108
Copy link
Contributor

Choose a reason for hiding this comment

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

Realized that we aren't purely testing DistributeFees function in here, but it's more of an e2e test on affiliate + rev share + distribute fees. This isn't the best practice - should have a function that exclusively tests DistributeFees, which doesn't rely on affiliatesKeeper or revshareKeeper. (We should also remove delete the revShareKeeper on subaccountsKeeper

@@ -332,23 +332,23 @@ func TestKeeper_GetAllRevShares_Valid(t *testing.T) {
},
Copy link
Contributor

Choose a reason for hiding this comment

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

For my understanding, how did we set up the tier for Bob in this test case? Didn't find anything related in the setUp()

Copy link
Contributor Author

Choose a reason for hiding this comment

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

bob address has coins already setup here for staking. This just puts bob at the max tier

Copy link
Contributor

Choose a reason for hiding this comment

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

I see, could we document in the unit test? Not very obvious to reader

@@ -420,33 +420,33 @@ func TestKeeper_GetAllRevShares_Valid(t *testing.T) {
},
Copy link
Contributor

Choose a reason for hiding this comment

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

Comment on line 411: negative unconditional and market mapper doesn't make sense - did you mean maker fee is 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.

yeah.. my b

RevShareType: types.REV_SHARE_TYPE_UNCONDITIONAL,
QuoteQuantums: big.NewInt(1_600_000),
QuoteQuantums: big.NewInt(1_300_000),
Copy link
Contributor

@teddyding teddyding Sep 20, 2024

Choose a reason for hiding this comment

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

At least for one of the test cases, could we add comment on math behind these expected values? For example,

						QuoteQuantums:     big.NewInt(1_300_000), // (10 - 2 - 10 * 0.15) * 20% = 1.3

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

Outside diff range and nitpick comments (1)
protocol/x/subaccounts/keeper/transfer_test.go (1)

1512-1513: Consider adding comments for clarity.

The expected balances for the market mapper and affiliate have been updated. To improve readability and maintainability, consider adding comments explaining how these values are calculated based on the new revenue sharing model.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3f21cf6 and f162535.

Files selected for processing (3)
  • protocol/x/revshare/keeper/revshare.go (7 hunks)
  • protocol/x/revshare/keeper/revshare_test.go (10 hunks)
  • protocol/x/subaccounts/keeper/transfer_test.go (13 hunks)
Files skipped from review as they are similar to previous changes (2)
  • protocol/x/revshare/keeper/revshare.go
  • protocol/x/revshare/keeper/revshare_test.go
Additional comments not posted (2)
protocol/x/subaccounts/keeper/transfer_test.go (2)

1510-1511: Verify the fee distribution calculation.

The expected fee module balance has been updated from 2950 to 2892. Please ensure that this new value is correct and consistent with the updated revenue sharing model. Consider adding a comment explaining the calculation for better clarity.

#!/bin/bash
# Verify the fee distribution calculation in other test cases
rg --type go "expectedFeeModuleAccBalance.*big.NewInt\([0-9]+\)" protocol/x/subaccounts/keeper/transfer_test.go

1520-1558: Review the new revenue sharing structure.

A new revShare field has been added with detailed revenue sharing information. This is a significant change that introduces more complexity to the test case. Please ensure that:

  1. The RevSharesForFill struct is correctly populated.
  2. The AffiliateRevShare values are consistent with the expected affiliate balance.
  3. The FeeSourceToQuoteQuantums and FeeSourceToRevSharePpm maps are correctly set up.
  4. The AllRevShares slice contains all the expected revenue shares.

Additionally, consider adding comments to explain the reasoning behind these specific values and how they relate to the expected balances.

setRevenueShare: true,
revShareExpiration: 100,
},
"success - market mapper rev share expired": {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Removing this since its an e2e test. Added an equivalent test in revshare_test.go

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The test in revshare_test.go broke - looks like there was already an existing test which was commented out

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

Outside diff range and nitpick comments (2)
protocol/x/revshare/keeper/revshare_test.go (2)

661-661: Simplify the expression for setting expired timestamp.

The expression ctx.BlockTime().Unix() + -1 can be simplified to ctx.BlockTime().Unix() - 1 for better readability.

Apply this diff to simplify the expression:

- ExpirationTs: uint64(ctx.BlockTime().Unix() + -1),
+ ExpirationTs: uint64(ctx.BlockTime().Unix() - 1),

Line range hint 762-762: Correct the ProductId assignment in the fill struct.

In the fill struct, ProductId is assigned marketId instead of perpetualId. This may lead to incorrect product identification during tests.

Apply this diff to fix the assignment:

- ProductId:                         marketId,
+ ProductId:                         perpetualId,
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f162535 and ab729a3.

Files selected for processing (9)
  • protocol/app/app.go (0 hunks)
  • protocol/testutil/keeper/clob.go (0 hunks)
  • protocol/testutil/keeper/listing.go (0 hunks)
  • protocol/testutil/keeper/sending.go (0 hunks)
  • protocol/testutil/keeper/subaccounts.go (0 hunks)
  • protocol/x/revshare/keeper/revshare_test.go (11 hunks)
  • protocol/x/subaccounts/keeper/keeper.go (1 hunks)
  • protocol/x/subaccounts/keeper/transfer_test.go (12 hunks)
  • protocol/x/subaccounts/types/expected_keepers.go (0 hunks)
Files not reviewed due to no reviewable changes (6)
  • protocol/app/app.go
  • protocol/testutil/keeper/clob.go
  • protocol/testutil/keeper/listing.go
  • protocol/testutil/keeper/sending.go
  • protocol/testutil/keeper/subaccounts.go
  • protocol/x/subaccounts/types/expected_keepers.go
Files skipped from review as they are similar to previous changes (1)
  • protocol/x/subaccounts/keeper/transfer_test.go
Additional comments not posted (6)
protocol/x/subaccounts/keeper/keeper.go (4)

Line range hint 1-62: Summary of review findings and next steps

  1. There is an inconsistency between the AI-generated summary and the provided code regarding the removal of revShareKeeper. This needs to be clarified.

  2. The current implementation of the Keeper struct and NewKeeper function appears to be consistent and functional. However, we need clarification on how the revenue sharing logic for affiliates is now being handled.

  3. The remaining functions (GetIndexerEventManager, Logger, and InitializeForGenesis) seem unchanged and should continue to function correctly.

Next steps:
a) Clarify the actual changes made to the revenue sharing logic for affiliates.
b) Verify that all NewKeeper function calls throughout the codebase are consistent with its current implementation.
c) Perform a general code health check, including running relevant tests and usage verification.
d) Update the PR description to accurately reflect the changes made in this file.

Please address these points and run the suggested verification scripts to ensure the consistency and correctness of the changes.


Line range hint 51-62: Remaining functions look good, consider a general code health check

The GetIndexerEventManager, Logger, and InitializeForGenesis functions appear to be unchanged and should continue to function correctly. However, given the changes to the Keeper struct and NewKeeper function, it would be prudent to perform a general code health check.

Consider running the following checks:

  1. Ensure all tests related to these functions are passing:
go test ./protocol/x/subaccounts/... -run "TestGetIndexerEventManager|TestLogger|TestInitializeForGenesis"
  1. Verify that these functions are still being used correctly throughout the codebase:
rg --type go -e 'GetIndexerEventManager\(\)' -e 'Logger\(' -e 'InitializeForGenesis\(' protocol/

Please review the results of these checks to ensure the overall health of the subaccounts module.


Line range hint 31-49: NewKeeper function implementation is consistent, but usage verification needed

The current implementation of the NewKeeper function is consistent with the Keeper struct definition. However, given the mentioned removal of the revShareKeeper parameter, we should verify that all calls to NewKeeper throughout the codebase have been updated accordingly.

To ensure that all usages of NewKeeper are consistent with its current signature, please run the following script:

#!/bin/bash
# Description: Check for NewKeeper function calls in the codebase

echo "Searching for NewKeeper function calls:"
rg --type go 'NewKeeper\s*\(' protocol/

# Expected results:
# All NewKeeper function calls should match the current signature without the revShareKeeper parameter.
# Any mismatches should be investigated and updated.

Please review the script output to confirm that all NewKeeper calls are consistent with the current implementation.


Line range hint 19-29: Keeper struct implementation looks good, but clarification needed

The current implementation of the Keeper struct appears to be well-structured and consistent. However, given the PR title "[OTE-816] Update Revshare logic for affiliates" and the mentioned removal of the revShareKeeper field, we need clarification on how the revenue sharing functionality for affiliates is now being handled.

Could you please provide information on:

  1. How the revenue sharing logic for affiliates is implemented without the revShareKeeper?
  2. Are there any other files or modules that now handle this functionality?

To help with this, you can run the following script to search for relevant code:

Please review the script output and provide the necessary clarification.

Verification successful

Verified Removal of revShareKeeper

The removal of the revShareKeeper field from the Keeper struct in protocol/x/subaccounts/keeper/keeper.go is appropriate. Revenue sharing functionality is now managed by the RevShareKeeper in the app/app.go module, ensuring centralized handling without impacting the subaccounts module.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for revenue sharing or affiliate-related code

echo "Searching for revenue sharing or affiliate-related code:"
rg --type go -i '(revshare|revenue.?shar|affiliate)' protocol/x/subaccounts/

Length of output: 5313

protocol/x/revshare/keeper/revshare_test.go (2)

426-426: Add explanation for expected QuoteQuantums values.

Please include comments that explain the calculations behind the expected QuoteQuantums values. This will enhance the readability and maintainability of the test cases by making the expected results clearer.


893-895: Declare the err variable to prevent compilation errors.

In the setup function, the variable err is used without prior declaration. This will cause a compilation error. Use := to declare and assign err when calling SetMarketMapperRevenueShareParams.

Apply this diff to fix the problem:

- err = keeper.SetMarketMapperRevenueShareParams(ctx, types.MarketMapperRevenueShareParams{
+ err := keeper.SetMarketMapperRevenueShareParams(ctx, types.MarketMapperRevenueShareParams{
    Address:         constants.AliceAccAddress.String(),
    RevenueSharePpm: 950_000, // 95%
    ValidDays:       1,
})

Likely invalid or redundant comment.

return types.RevSharesForFill{}, nil
}

if netFeesSubAffiliateFeesShared.Sign() <= 0 {
Copy link
Contributor

Choose a reason for hiding this comment

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

Nit: move to immediately below line 129

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 962942e and 098ad3d.

Files selected for processing (3)
  • protocol/x/clob/keeper/process_single_match.go (2 hunks)
  • protocol/x/revshare/keeper/revshare.go (6 hunks)
  • protocol/x/revshare/keeper/revshare_test.go (12 hunks)
Files skipped from review as they are similar to previous changes (2)
  • protocol/x/revshare/keeper/revshare.go
  • protocol/x/revshare/keeper/revshare_test.go

Comment on lines +468 to +471
if err != nil {
revSharesForFill = revsharetypes.RevSharesForFill{}
log.ErrorLog(ctx, "error getting rev shares for fill", "error", err)
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider revising the error handling strategy for GetAllRevShares

The addition of error handling for GetAllRevShares is a good practice. However, the current implementation might mask potential issues:

  1. The function continues execution with an empty revSharesForFill struct when an error occurs.
  2. The error is logged but not propagated, which could lead to silent failures in revenue sharing calculations.

Consider the following suggestions:

  1. Evaluate whether continuing with an empty revSharesForFill is appropriate in all scenarios.
  2. Consider propagating the error or adding a mechanism to flag that revenue sharing couldn't be calculated.
  3. Add a comment explaining the rationale behind this error handling approach for future maintainers.

Here's a potential alternative implementation:

 revSharesForFill, err := k.revshareKeeper.GetAllRevShares(ctx, fillForProcess, affiliatesWhitelistMap)
 if err != nil {
-    revSharesForFill = revsharetypes.RevSharesForFill{}
-    log.ErrorLog(ctx, "error getting rev shares for fill", "error", err)
+    // Log the error
+    log.ErrorLog(ctx, "error getting rev shares for fill", "error", err)
+    // Consider whether to return the error or continue with a flag
+    return takerUpdateResult, makerUpdateResult, affiliateRevSharesQuoteQuantums, 
+        fmt.Errorf("failed to get rev shares: %w", err)
 }

This approach would propagate the error, allowing the caller to decide how to handle it.

Committable suggestion was skipped due to low confidence.

}
netFeesSubAffiliateFeesShared := new(big.Int).Sub(netFees, affiliateFeesShared)
if netFeesSubAffiliateFeesShared.Sign() <= 0 {
log.ErrorLog(ctx, "net fees sub affiliate fees shared is less than or equal to 0")
return types.RevSharesForFill{}, nil
return types.RevSharesForFill{}, err
Copy link
Contributor

Choose a reason for hiding this comment

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

What err are we returning here?

@affanv14 affanv14 force-pushed the affan/update-revshare branch from 84a8cdb to 53b26b2 Compare September 24, 2024 01:38
@affanv14 affanv14 merged commit 1659f93 into main Sep 24, 2024
21 of 22 checks passed
@affanv14 affanv14 deleted the affan/update-revshare branch September 24, 2024 02:39
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