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-730] Add E2E tests for revshare #2283

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open

Conversation

affanv14
Copy link
Contributor

@affanv14 affanv14 commented Sep 18, 2024

Changelist

Full flow E2E for revshare
Account with >$25M trailing volume does not generate affiliate rev share.
Update e2e test for check for non 0 affiliate revshare being sent back

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

Release Notes

  • New Features

    • Introduced unconditionalRevShareConfig for enhanced revenue sharing configurations.
    • Added addressToUserStats to track user statistics linked to specific addresses.
  • Improvements

    • Enhanced initialization and export processes for revenue share configurations and user statistics.
  • Tests

    • Added comprehensive tests for affiliate revenue sharing functionality in decentralized finance scenarios.

These updates improve the system's ability to manage revenue sharing and user data effectively.

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

linear bot commented Sep 18, 2024

Copy link
Contributor

coderabbitai bot commented Sep 18, 2024

Walkthrough

The pull request introduces significant enhancements to the GenesisState interfaces and structures in the revshare and stats modules. Key modifications include the addition of new properties for revenue sharing configurations and user statistics tracking. These changes involve updates to the encoding and decoding logic, initialization processes, and default values for the GenesisState. The overall aim is to improve the handling of revenue sharing and user statistics within the application.

Changes

File Path Change Summary
indexer/packages/v4-protos/src/codegen/dydxprotocol/revshare/genesis.ts Added unconditionalRevShareConfig to GenesisState, updated encoding/decoding logic, and modified createBaseGenesisState and fromPartial methods.
indexer/packages/v4-protos/src/codegen/dydxprotocol/stats/genesis.ts Introduced addressToUserStats in GenesisState, defined AddressToUserStats interface, and updated encoding/decoding methods and createBaseGenesisState.
proto/dydxprotocol/revshare/genesis.proto Added unconditional_rev_share_config field to GenesisState message.
proto/dydxprotocol/stats/genesis.proto Added address_to_user_stats field and defined AddressToUserStats message.
protocol/app/testdata/default_genesis_state.json Added unconditional_rev_share_config and address_to_user_stats sections.
protocol/scripts/genesis/sample_pregenesis.json Added unconditional_rev_share_config and address_to_user_stats, updated app_version.
protocol/x/revshare/e2e/revshare_place_order_test.go Introduced tests for placing orders with affiliate revenue sharing, covering various scenarios and expected outcomes.
protocol/x/revshare/genesis.go Enhanced InitGenesis and ExportGenesis functions to handle unconditional revenue share configuration parameters.
protocol/x/revshare/types/genesis.go Added UnconditionalRevShareConfig field in GenesisState structure.
protocol/x/stats/genesis.go Added logic to set user statistics for addresses in InitGenesis function.
protocol/x/stats/types/genesis.go Initialized AddressToUserStats in DefaultGenesis function.

Possibly related PRs

Suggested reviewers

  • vincentwschau

Poem

🐰 In the meadow where bunnies play,
New features bloom, bright as the day.
Revenue sharing, stats in a row,
Hop along, watch our system grow!
With every change, we leap with glee,
A better world for you and me! 🌼


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.

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/revshare/e2e/revshare_place_order_test.go (1)

33-188: Comprehensive test coverage for placing orders with affiliate revenue sharing.

The TestPlaceOrderWithAffiliate function provides thorough test coverage for placing orders with affiliate revenue sharing under various scenarios. It covers standard affiliate revenue sharing, affiliate over limit, and combinations of affiliate, unconditional, and market mapper revenue sharing.

The test cases are well-structured, with clear setup, execution, and verification steps. The expected outcomes are validated against actual results, ensuring that the revenue sharing logic operates correctly under different configurations.

Consider splitting the large test function into smaller, more focused test functions for improved readability and maintainability. For example, you could have separate test functions for each scenario or group related scenarios together.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between ba731b0 and 4283fc0.

Files ignored due to path filters (2)
  • protocol/x/revshare/types/genesis.pb.go is excluded by !**/*.pb.go
  • protocol/x/stats/types/genesis.pb.go is excluded by !**/*.pb.go
Files selected for processing (12)
  • indexer/packages/v4-protos/src/codegen/dydxprotocol/revshare/genesis.ts (4 hunks)
  • indexer/packages/v4-protos/src/codegen/dydxprotocol/stats/genesis.ts (4 hunks)
  • proto/dydxprotocol/revshare/genesis.proto (1 hunks)
  • proto/dydxprotocol/stats/genesis.proto (1 hunks)
  • protocol/app/testdata/default_genesis_state.json (2 hunks)
  • protocol/scripts/genesis/sample_pregenesis.json (3 hunks)
  • protocol/testutil/app/app.go (3 hunks)
  • protocol/x/revshare/e2e/revshare_place_order_test.go (1 hunks)
  • protocol/x/revshare/genesis.go (1 hunks)
  • protocol/x/revshare/types/genesis.go (1 hunks)
  • protocol/x/stats/genesis.go (1 hunks)
  • protocol/x/stats/types/genesis.go (1 hunks)
Additional comments not posted (31)
protocol/x/revshare/types/genesis.go (1)

7-9: LGTM!

The initialization of the UnconditionalRevShareConfig field in the GenesisState struct with an empty slice of UnconditionalRevShareConfig_RecipientConfig is a valid approach for defining a default state for this field.

This change provides a structured way to handle recipient configurations for unconditional revenue sharing from the genesis state, which was previously undefined.

protocol/x/stats/types/genesis.go (1)

11-11: LGTM!

Initializing the AddressToUserStats field to an empty slice of pointers to AddressToUserStats in the DefaultGenesis function is a good practice. It ensures that the field is always initialized to a known empty state rather than being left uninitialized, which could lead to nil pointer dereferences.

This change enhances the robustness of the state management during the genesis phase.

proto/dydxprotocol/revshare/genesis.proto (2)

6-6: LGTM!

The import statement is necessary and correctly formatted.


14-15: Approve the new field unconditional_rev_share_config.

The new field unconditional_rev_share_config is a valuable addition to the GenesisState message. It enhances the configuration capabilities of the revenue sharing mechanism by allowing for more granular control over revenue distribution.

The field is appropriately named, typed, and commented. Marking it as non-nullable is a good practice to ensure that the field is always set, preventing potential issues related to missing configuration.

The field number 2 is correctly assigned and does not conflict with the existing field numbers.

protocol/x/stats/genesis.go (1)

16-19: LGTM!

The added loop correctly initializes the user stats for each address provided in the genesis state. This is a useful feature that ensures the user stats are set up correctly at the genesis of the chain.

The implementation looks good and I don't see any issues with the logic or potential negative impact.

proto/dydxprotocol/stats/genesis.proto (4)

5-5: LGTM!

The import statement for cosmos_proto/cosmos.proto is correctly placed and suggests the usage of Cosmos-specific types or annotations in the file.


15-15: LGTM!

The new field address_to_user_stats in the GenesisState message allows storing multiple user stats entries mapped to addresses. The repeated keyword and the field type AddressToUserStats are used appropriately.


18-24: LGTM!

The new message AddressToUserStats is well-defined with appropriate fields:

  • The address field is correctly typed as a string and annotated as a Cosmos address using cosmos_proto.scalar.
  • The user_stats field is of type UserStats, which is likely defined in the imported dydxprotocol/stats/stats.proto file.

The message structure effectively represents a mapping between an address and its associated user stats.


Line range hint 1-24: Overall, the changes look good!

The modifications to the genesis.proto file enhance the stats module's genesis state by introducing the ability to store user stats mapped to addresses. The new AddressToUserStats message provides a clean and appropriate structure for representing this mapping.

The use of the cosmos_proto import and the address annotation ensures compatibility with the Cosmos ecosystem, which is a positive addition.

The changes are well-structured, follow the existing coding style and conventions, and align with the intended purpose of extending the genesis state functionality.

Great job!

Tools
buf

4-4: import "gogoproto/gogo.proto": file does not exist

(COMPILE)

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

17-17: LGTM!

The addition of setting the unconditional revenue share configuration parameters during genesis initialization is correct and aligns with the PR objective.


23-28: LGTM!

The changes to include the unconditional revenue share configuration parameters in the exported genesis state are correct and improve the completeness of the exported state. This aligns with the PR objective.

indexer/packages/v4-protos/src/codegen/dydxprotocol/revshare/genesis.ts (5)

2-2: LGTM!

The import statement is correct and necessary for the subsequent code changes.


8-12: LGTM!

The new property unconditionalRevShareConfig is correctly added to the GenesisState interface with a clear comment. This addition aligns with the PR objective.


17-21: LGTM!

The new property unconditional_rev_share_config is correctly added to the GenesisStateSDKType interface with a clear comment. This addition aligns with the PR objective.


26-27: LGTM!

The unconditionalRevShareConfig property is correctly initialized to undefined in the createBaseGenesisState function, ensuring that the new field is accounted for in the base state creation process.


37-40: LGTM!

The encoding, decoding, and fromPartial methods of the GenesisState are correctly updated to handle the new unconditionalRevShareConfig property. These changes ensure that the new configuration can be set, retrieved, and reconstructed from serialized data consistently with the existing properties.

Also applies to: 57-60, 73-73

indexer/packages/v4-protos/src/codegen/dydxprotocol/stats/genesis.ts (5)

10-10: LGTM!

The addition of the addressToUserStats property to the GenesisState interface is a good way to store user stats associated with specific addresses. The property name and type are appropriate for the intended functionality.


17-18: LGTM!

The addition of the address_to_user_stats property to the GenesisStateSDKType interface correctly mirrors the change made to the GenesisState interface. The property name follows the naming convention for SDK types, and the type accurately represents an array of the SDK type for AddressToUserStats.


19-27: LGTM!

The introduction of the AddressToUserStats interface is a good way to represent user stats associated with a specific address. The address property appropriately stores the address as a string, and the userStats property of type UserStats holds the actual user statistics data. Making the userStats property optional provides flexibility in cases where user stats may not be available for a particular address.


28-35: LGTM!

The introduction of the AddressToUserStatsSDKType interface correctly represents the SDK type for the AddressToUserStats interface. The property names follow the naming convention for SDK types, and the types of the properties accurately correspond to the SDK types of the respective properties in the AddressToUserStats interface.


40-41: LGTM!

Initializing the addressToUserStats property as an empty array in the createBaseGenesisState function is the correct approach. It ensures that the property has a valid default value when creating a new GenesisState instance, and it is consistent with the type of the addressToUserStats property, which is an array of AddressToUserStats.

protocol/app/testdata/default_genesis_state.json (2)

435-437: LGTM! The addition of unconditional_rev_share_config enhances extensibility.

The new unconditional_rev_share_config section with an empty configs array lays the groundwork for future functionality related to unconditional revenue sharing. While no specific configurations are defined at this point, the system is now prepared to handle revenue sharing configurations that can be added later.


481-482: Looks good! The addition of address_to_user_stats enables future user-specific statistics tracking.

The new address_to_user_stats array in the stats section indicates a potential expansion of the statistics tracking functionality. Although the array is currently empty, this change sets the stage for future implementations where user-specific statistics can be associated with addresses, enabling more granular tracking and analysis.

protocol/x/revshare/e2e/revshare_place_order_test.go (2)

190-239: Well-structured helper function for setting up the test environment.

The setupTest function provides a clean and well-structured way to set up the test environment for the TestPlaceOrderWithAffiliate function. It initializes the application state, creates user accounts, and sets up the initial conditions based on the provided parameters.

The function takes initial user state stats, unconditional revenue share config, and market mapper revenue share params as input, allowing for flexibility in configuring the test environment.

The use of a custom genesis document function to update the application state for the affiliate, stats, and revshare modules based on the provided initial conditions is a good approach.


241-312: Clear and well-structured helper function for setting up test orders.

The setupOrders function provides a clear and well-structured way to set up the orders for the TestPlaceOrderWithAffiliate function. It retrieves the CLOB pair from the genesis state, registers an affiliate, and creates buy and sell orders for the test.

The function follows a logical sequence of steps:

  1. Retrieve the first CLOB pair from the default genesis state.
  2. Create a message to register an affiliate and send it as a check transaction.
  3. Advance the block to simulate the passage of time.
  4. Create a buy order for Alice and a sell order for Bob, scaling the order quantities based on the default genesis state.
  5. Create check transactions for both orders.

The function returns the CLOB pair, the created orders, and the corresponding check transactions, providing all the necessary components for the test.

protocol/testutil/app/app.go (3)

52-52: LGTM!

The import statement is syntactically correct and consistent with the alterations list.


211-212: LGTM!

The addition of affiliatestypes.GenesisState to the GenesisStates interface is syntactically correct and consistent with the alterations list.


274-275: LGTM!

The new case statement correctly handles the affiliatestypes.GenesisState type and sets the moduleName accordingly. This change is consistent with the alterations made to the GenesisStates interface.

protocol/scripts/genesis/sample_pregenesis.json (3)

3879-3881: LGTM!

The addition of the unconditional_rev_share_config section with an empty configs array looks good. It provides a placeholder for future unconditional revenue share configurations without impacting the current system.


3923-3923: Provide more details on the address_to_user_stats feature.

The addition of the empty address_to_user_stats array in the stats section looks good. It indicates a new capability to track user statistics by address.

To better understand the impact of this feature, please provide more details on:

  • What specific user statistics will be tracked?
  • How will this data be populated and utilized?
  • Are there any privacy or security considerations to keep in mind?

3987-3987: Document the changes included in this version update.

The app_version has been incremented to 5.2.1-119-g77487f61, indicating various enhancements or bug fixes.

To facilitate a thorough review, please provide more details on:

  • The specific changes and improvements made in this version.
  • How these changes have been tested to ensure they work as expected.
  • Any relevant updates to the documentation.

This will help reviewers better understand the impact of the version update.

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

🧹 Outside diff range and nitpick comments (2)
protocol/x/revshare/e2e/revshare_place_order_test.go (2)

266-266: Explain advancing the block to height 3 before placing orders.

Advancing the context to block 3 before placing orders without a comment may confuse readers about the necessity of this step. Adding a comment to explain why the block is advanced here can improve code readability and maintainability.

Consider adding a comment:

 ctx = tApp.AdvanceToBlock(3, testapp.AdvanceToBlockOptions{})
+// Advance to block 3 to simulate the passage of time before placing orders

290-306: Consistent handling of CheckTx responses for order placements.

When placing orders, the CheckTx responses for aliceCheckTx and bobCheckTx are generated but not explicitly checked for success or failure individually. Although the orders are processed in a loop later, directly asserting the success of each CheckTx can help identify issues with specific orders.

Consider adding assertions:

 aliceCheckTx := testapp.MustMakeCheckTx(
     // existing code
 )
+require.True(t, tApp.CheckTx(aliceCheckTx).IsOK(), "Alice's order CheckTx failed")

 bobCheckTx := testapp.MustMakeCheckTx(
     // existing code
 )
+require.True(t, tApp.CheckTx(bobCheckTx).IsOK(), "Bob's order CheckTx failed")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 14ed93f and 5d53186.

📒 Files selected for processing (3)
  • protocol/app/testdata/default_genesis_state.json (2 hunks)
  • protocol/scripts/genesis/sample_pregenesis.json (3 hunks)
  • protocol/x/revshare/e2e/revshare_place_order_test.go (1 hunks)
🔇 Additional comments not posted (5)
protocol/app/testdata/default_genesis_state.json (2)

462-464: LGTM. Consider adding documentation for the new field.

The addition of unconditional_rev_share_config with an empty configs array is appropriate for the default genesis state. This change aligns with the PR objective of implementing E2E tests for revshare.

To improve maintainability, consider adding a comment or documentation explaining the purpose and potential values of this new field.


508-508: LGTM. Please clarify the relation to revshare E2E tests.

The addition of address_to_user_stats as an empty array is appropriate for the default genesis state. However, it's not immediately clear how this relates to the PR objective of implementing E2E tests for revshare.

Could you please explain how this new field contributes to the revshare E2E tests? If it's not directly related, consider mentioning this addition in the PR description for clarity.

To verify the usage of this new field, let's search for its occurrences in the codebase:

protocol/scripts/genesis/sample_pregenesis.json (2)

3905-3907: New configuration added for unconditional revenue sharing.

A new unconditional_rev_share_config field has been added to the revshare section with an empty configs array. This addition suggests preparation for a feature to configure unconditional revenue sharing, but it's currently not populated.

Consider documenting the purpose and expected future use of this new configuration in a comment or in the project documentation.


3949-3950: New field added for user statistics tracking.

An address_to_user_stats array has been added to the stats section. This empty array likely serves as a placeholder for future user statistics tracking functionality.

Ensure that the implementation of this feature includes proper data privacy considerations and complies with relevant regulations.

protocol/x/revshare/e2e/revshare_place_order_test.go (1)

417-441: Verify the correctness of transaction hashes in TxHashes.

In getExpectedOnchainMessagesInNextBlock, the transaction hashes are constructed manually. Ensure that these hashes accurately represent the transactions processed in the test to prevent mismatches during message verification.

Run the following script to compare the generated transaction hashes with actual transaction hashes:

#!/bin/bash
# Description: Verify that the transaction hashes used in `TxHashes` match the actual transactions.

# Expectation: The hashes should match the transactions created during the test.
# Note: Adjust the paths if necessary based on the repository structure.

# Find the actual transaction hashes from the application's transaction logs or outputs.
# Since this environment doesn't have access to runtime logs, we simulate hash generation.

# Extract the expected transaction hash from the code.
echo "Expected TxHashes from code:"
rg 'TxHashes:\s+\[\]string\{.*\}' -A 5

# Simulate transaction hash calculation (if possible).
# Note: Actual hash calculation may require access to the transaction bytes.

# Placeholder command as actual computation isn't feasible here.
echo "Ensure that the transaction hashes are computed correctly in the test setup."

@@ -4021,7 +4025,7 @@
]
}
},
"app_version": "5.2.1-172-g351fcccd",
"app_version": "5.2.1-129-g14ed93f0",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Unusual app_version Change Detected

The app_version in protocol/scripts/genesis/sample_pregenesis.json was updated to "5.2.1-129-g14ed93f0", which decreases the commit count from "5.2.1-172-g351fcccd". No corresponding commit was found for this change, indicating a potential inconsistency.

  • Location: protocol/scripts/genesis/sample_pregenesis.json
🔗 Analysis chain

Application version updated.

The app_version has been changed from "5.2.1-172-g351fcccd" to "5.2.1-129-g14ed93f0".

This change in version number, particularly the decrease in the commit count (from 172 to 129), is unusual. Let's verify if this is intentional:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check git logs for version changes
git log --oneline | grep -E "5\.2\.1-(172-g351fcccd|129-g14ed93f0)"

Length of output: 69


Script:

#!/bin/bash
# Find all commits that changed the app_version in sample_pregenesis.json
git log -p -S'"app_version"' -- protocol/scripts/genesis/sample_pregenesis.json

Length of output: 138617


Script:

#!/bin/bash
# Search for all occurrences of "app_version" in the codebase
rg '"app_version"'

Length of output: 659

Comment on lines +128 to +188
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// Setup
tApp, ctx, msgSender := setupTest(t, tc.initialUserStateStats,
tc.initialUnconditionalRevShareConfig, tc.initialMarketMapperRevShareParams)

bankKeeper := tApp.App.BankKeeper
carlBankBalance := bankKeeper.GetBalance(ctx, constants.CarlAccAddress, assettypes.AssetUsdc.GetDenom())
aliceBankBalance := bankKeeper.GetBalance(ctx, constants.AliceAccAddress, assettypes.AssetUsdc.GetDenom())
daveBankBalance := bankKeeper.GetBalance(ctx, constants.DaveAccAddress, assettypes.AssetUsdc.GetDenom())
// Setup orders
Clob_0, aliceOrder, bobOrder, aliceCheckTx, bobCheckTx, orders := setupOrders(ctx, tApp)

// Get expected onchain messages
expectedOnchainMessagesInNextBlock := getExpectedOnchainMessagesInNextBlock(
ctx,
Clob_0,
aliceOrder,
bobOrder,
aliceCheckTx.Tx,
bobCheckTx.Tx,
big.NewInt(100000000005000000-tc.expectedTakerFeeQuantums),
big.NewInt(99999999995000000+tc.expectedMakerFeeQuantums),
tc.expectedTakerFeeQuantums,
tc.expectedMakerFeeQuantums,
tc.expectedAffiliateRevShareQuantums,
4,
)

// Place orders
for _, order := range orders {
for _, checkTx := range testapp.MustMakeCheckTxsWithClobMsg(ctx, tApp.App, order) {
resp := tApp.CheckTx(checkTx)
require.Conditionf(t, resp.IsOK, "Expected CheckTx to succeed. Response: %+v", resp)
}
}
// Clear msgSender and advance to next block
msgSender.Clear()
ctx = tApp.AdvanceToBlock(4, testapp.AdvanceToBlockOptions{})

// Check onchain messages
require.ElementsMatch(t, expectedOnchainMessagesInNextBlock, msgSender.GetOnchainMessages())

// Check bank balances
carlBankBalanceAfter := bankKeeper.GetBalance(ctx,
constants.CarlAccAddress,
assettypes.AssetUsdc.GetDenom())
aliceBankBalanceAfter := bankKeeper.GetBalance(ctx,
constants.AliceAccAddress,
assettypes.AssetUsdc.GetDenom())
daveBankBalanceAfter := bankKeeper.GetBalance(ctx,
constants.DaveAccAddress,
assettypes.AssetUsdc.GetDenom())
require.Equal(t, carlBankBalance.Add(sdk.NewCoin(assettypes.AssetUsdc.GetDenom(),
math.NewInt(tc.expectedUnconditionalRevShareQuantums))), carlBankBalanceAfter)
require.Equal(t, aliceBankBalance.Add(sdk.NewCoin(assettypes.AssetUsdc.GetDenom(),
math.NewInt(tc.expectedAffiliateRevShareQuantums))), aliceBankBalanceAfter)
require.Equal(t, daveBankBalance.Add(sdk.NewCoin(assettypes.AssetUsdc.GetDenom(),
math.NewInt(tc.expectedMarketMapperRevShareQuantums))), daveBankBalanceAfter)
})
}
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider adding more test cases for edge conditions.

The current test cases cover several scenarios, but adding more cases for edge conditions (e.g., zero fees, maximum possible values, invalid inputs) can enhance the robustness of the test suite.

Consider adding test cases like:

  • A test case where all revenue shares are active simultaneously with maximum allowable percentages.
  • A test case with zero transaction amounts to test the handling of minimal input.
  • A test case with invalid configurations to ensure proper error handling.

},
&msgRegisterAffiliate,
)
tApp.CheckTx(checkTxMsgRegisterAffiliate)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check the response of CheckTx for error handling.

The response from tApp.CheckTx(checkTxMsgRegisterAffiliate) is not being checked. This may overlook potential errors during the affiliate registration. It's important to assert that the transaction is successful to catch any issues early in the test setup.

Apply this diff to add error checking:

 tApp.CheckTx(checkTxMsgRegisterAffiliate)
+require.True(t, tApp.CheckTx(checkTxMsgRegisterAffiliate).IsOK(), "Affiliate registration failed")

Committable suggestion was skipped due to low confidence.

Comment on lines +60 to +61
TakerNotional: uint64(60_000_000_000_000),
MakerNotional: uint64(60_000_000_000_000),
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Inconsistent Units for TakerNotional and MakerNotional

The TakerNotional and MakerNotional are set to 60_000_000_000_000, which appears to represent 60 trillion. However, the comment mentions a cap of 50 million. This discrepancy suggests that the units may not be consistent, potentially leading to confusion or calculation errors.

  • File: protocol/x/revshare/e2e/revshare_place_order_test.go
  • Lines: 60-61
🔗 Analysis chain

Clarify the units for TakerNotional and MakerNotional.

In the test case "Affiliate over limit", the TakerNotional and MakerNotional are set to 60_000_000_000_000. The comment mentions that the cap is 50 million, but the value seems to represent 60 trillion. Please ensure that the units are consistent (e.g., whether they are in pennies, dollars, or quantums) to avoid confusion and potential calculation errors.

Run the following script to check for consistency in the usage of notional values across the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for all instances where `TakerNotional` and `MakerNotional` are set to large values.

# Expectation: Values should be consistently represented with correct units.
rg --type go 'TakerNotional:\s*uint64\(\d+\)' -A 3

Length of output: 1999


Script:

#!/bin/bash
# Description: Search for all instances where `TakerNotional` and `MakerNotional` are set in Go files to verify unit consistency.

# Searching for `TakerNotional` and `MakerNotional` assignments
rg --type go '(TakerNotional|MakerNotional):\s*uint64\(\d+\)' -A 3

Length of output: 68


Script:

#!/bin/bash
# Description: Search for all instances where `TakerNotional` and `MakerNotional` are set in Go files to verify unit consistency.
# Updated regex to include underscores in numeric literals.

rg --type go '(TakerNotional|MakerNotional):\s*uint64\([0-9_]+\)' -A 3

Length of output: 531

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.

1 participant