Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[CT-1262] add e2e tests for permissioned keys success cases #2479

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

jayy04
Copy link
Contributor

@jayy04 jayy04 commented Oct 8, 2024

Changelist

[Describe or list the changes made in this PR]

Test Plan

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

Author/Reviewer Checklist

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

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced an AuthenticatorManager for enhanced account management and authentication.
    • Added a new long-term order for trading, expanding trading strategies.
    • New test cases for successful order placements using permissioned keys.
  • Bug Fixes

    • Improved transaction processing logic by restructuring ante decorators for clarity and maintainability.
  • Tests

    • Enhanced test coverage for circuit breaker and permissioned key functionalities.

@jayy04 jayy04 requested a review from a team as a code owner October 8, 2024 14:24
Copy link

linear bot commented Oct 8, 2024

Copy link
Contributor

coderabbitai bot commented Oct 8, 2024

Walkthrough

This pull request introduces significant changes to the transaction processing logic within the application. Key modifications include restructuring the NewAnteHandler function and the lockingAnteHandler to utilize sdk.ChainAnteDecorators, enhancing the organization of ante decorators. The App struct is updated to include an AuthenticatorManager and an AccountPlusKeeper, improving account management. Additionally, a new long-term order for Bob is defined, and the CircuitBreakerDecorator is modified to streamline its handler types. New tests are added to validate the functionality of permissioned keys in the order placement process.

Changes

File Path Change Summary
protocol/app/ante.go Restructured NewAnteHandler and lockingAnteHandler to use sdk.ChainAnteDecorators, removing direct calls to setPubKey and sigGasConsume. Updated method signatures and internal logic.
protocol/app/app.go Added AuthenticatorManager and AccountPlusKeeper to App struct, modifying initialization logic for account management.
protocol/testutil/constants/stateful_orders.go Introduced a new long-term order for Bob, expanding trading strategies without modifying existing orders.
protocol/x/accountplus/ante/circuit_breaker.go Updated CircuitBreakerDecorator fields from sdk.AnteDecorator to sdk.AnteHandler. Modified constructor and method signatures to align with new handler types.
protocol/x/accountplus/ante/circuit_breaker_test.go Changed the instantiation of CircuitBreakerDecorator in tests to use sdk.ChainAnteDecorators, adjusted context priority checks, and maintained existing test scenarios.
protocol/x/clob/e2e/permissioned_keys_test.go Added TestPlaceOrder_PermissionedKeys_Success to validate successful order placements using permissioned keys, covering various scenarios such as order placement and removal upon key removal.

Possibly related PRs

Suggested labels

feature:optimistic_execution

Suggested reviewers

  • teddyding

Poem

In the fields where rabbits play,
New handlers hop in bright array.
With keys and orders, all in line,
Our code now dances, oh so fine!
So let us cheer, with joyful thump,
For changes made, we proudly jump! 🐇✨


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.

Base automatically changed from jy/ct-1262 to main October 8, 2024 14:25
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/clob/e2e/permissioned_keys_test.go (2)

666-666: Add a Comment for the New Test Function

Consider adding a comment above the new test function TestPlaceOrder_PermissionedKeys_Success to describe its purpose. This enhances code readability and helps future maintainers understand the test scenarios covered.

Apply this diff to add the comment:

+// TestPlaceOrder_PermissionedKeys_Success tests successful order placements using permissioned keys.
 func TestPlaceOrder_PermissionedKeys_Success(t *testing.T) {

1379-1382: Avoid Using panic in Test Code

Using panic(err) in test code can halt the entire test suite on failure. Instead, use require.NoError(t, err) to fail the specific test case gracefully without affecting others.

Apply this diff to replace panic with require.NoError:

 bytes, err := tApp.App.TxConfig().TxEncoder()(tx)
-if err != nil {
-    panic(err)
-}
+require.NoError(t, err, "Failed to encode transaction")
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 34c1ea2 and 04816be.

📒 Files selected for processing (6)
  • protocol/app/ante.go (1 hunks)
  • protocol/app/app.go (1 hunks)
  • protocol/testutil/constants/stateful_orders.go (1 hunks)
  • protocol/x/accountplus/ante/circuit_breaker.go (2 hunks)
  • protocol/x/accountplus/ante/circuit_breaker_test.go (1 hunks)
  • protocol/x/clob/e2e/permissioned_keys_test.go (1 hunks)
🧰 Additional context used
🔇 Additional comments (13)
protocol/x/accountplus/ante/circuit_breaker.go (3)

21-22: LGTM! Verify function calls in codebase.

The parameter type changes from sdk.AnteDecorator to sdk.AnteHandler in the NewCircuitBreakerDecorator function are consistent with the struct field modifications. This ensures type consistency when creating new instances of CircuitBreakerDecorator.

To ensure this change doesn't introduce any issues, please run the following script to check for any calls to NewCircuitBreakerDecorator in the codebase:

#!/bin/bash
# Description: Check for calls to NewCircuitBreakerDecorator

# Test: Search for NewCircuitBreakerDecorator function calls
rg --type go 'NewCircuitBreakerDecorator\('

47-47: LGTM! Verify correct behavior of AnteHandle method.

The changes to the AnteHandle method are consistent with the type changes from sdk.AnteDecorator to sdk.AnteHandler. The removal of the next parameter and the inclusion of the simulate parameter in both method calls align with the new handler type's expected signature.

To ensure this change doesn't introduce any unexpected behavior, please run the following script to check for any tests related to the AnteHandle method:

#!/bin/bash
# Description: Check for tests related to AnteHandle method

# Test: Search for test functions that might be testing AnteHandle
rg --type go 'func.*Test.*AnteHandle'

Additionally, please ensure that the simulate parameter is being used correctly in both the authenticator and original ante handler flows.

Also applies to: 51-51


14-15: Overall changes look good. Ensure comprehensive update across codebase.

The modifications to CircuitBreakerDecorator and its associated methods consistently update the ante handler types from sdk.AnteDecorator to sdk.AnteHandler. This change simplifies the interface and aligns with the SDK's AnteHandler type, which is a positive improvement.

To ensure a smooth transition:

  1. Update all relevant parts of the application that interact with CircuitBreakerDecorator.
  2. Modify any existing tests to reflect these changes.
  3. Update documentation to reflect the new method signatures and usage patterns.
  4. Consider running integration tests to verify that the changes don't introduce any unexpected behavior in the transaction processing flow.

Run the following script to identify potential areas that might need updates:

#!/bin/bash
# Description: Identify potential areas needing updates due to AnteDecorator changes

# Test 1: Search for AnteDecorator usages
echo "Searching for AnteDecorator usages:"
rg --type go 'AnteDecorator'

# Test 2: Search for CircuitBreakerDecorator usages
echo "Searching for CircuitBreakerDecorator usages:"
rg --type go 'CircuitBreakerDecorator'

# Test 3: Search for NewCircuitBreakerDecorator usages
echo "Searching for NewCircuitBreakerDecorator usages:"
rg --type go 'NewCircuitBreakerDecorator'

# Test 4: Search for AnteHandle method usages
echo "Searching for AnteHandle method usages:"
rg --type go '\.AnteHandle\('

Review the output of this script to identify any areas of the codebase that might need updates to align with the new changes.

Also applies to: 21-22, 47-47, 51-51

protocol/x/accountplus/ante/circuit_breaker_test.go (3)

Line range hint 86-94: LGTM: New AnteHandle method enhances test capabilities

The addition of the AnteHandle method to MockAnteDecorator is a positive change. It allows for more nuanced testing of the CircuitBreaker's behavior by simulating different decorator responses based on the Called field.

This enhancement will provide more comprehensive test coverage for the CircuitBreaker functionality.


Line range hint 1-194: Overall assessment: Improved test structure with potential for wider impact

The changes to this test file, particularly in the TestCircuitBreakerAnte function and the addition of the AnteHandle method to MockAnteDecorator, represent an improvement in the test structure and capabilities. The use of sdk.ChainAnteDecorators aligns the test more closely with SDK patterns, while the new mock method allows for more nuanced testing.

However, these changes, especially the modification to the decorator chaining, could potentially impact the behavior of the CircuitBreaker or how it's tested. To ensure the integrity of the tests:

  1. Verify that all test cases still pass and behave as expected.
  2. Consider adding additional test cases that specifically target the new chaining behavior.
  3. Review any other tests or code that may rely on the previous CircuitBreaker instantiation method to ensure consistency across the codebase.

To assist in this verification, please run the following script:

#!/bin/bash
# Description: Run the CircuitBreaker tests and check for any failures or unexpected behaviors

# Test: Run the CircuitBreaker tests
go test -v ./protocol/x/accountplus/ante -run TestCircuitBreakerAnte

# Additional check: Look for any other files that might be affected by the changes
rg --type go "CircuitBreakerDecorator" ./protocol

Review the test results and any files highlighted by the script to ensure full compatibility with the changes.


154-155: Verify the impact of chaining ante decorators

The modification to wrap mockTestAuthenticator and mockTestClassic with sdk.ChainAnteDecorators changes how these decorators are chained together. While this change aligns with the SDK's decorator chaining pattern, it's important to ensure that this doesn't alter the expected behavior of the CircuitBreaker.

To confirm that this change doesn't introduce any unintended side effects, please run the following verification script:

If the script returns results, review those occurrences to ensure consistency across all tests.

✅ Verification successful

No other tests rely on the previous decorator chaining method

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the CircuitBreaker behavior remains consistent with the new decorator chaining.

# Test: Check if there are any other tests relying on the previous decorator chaining method
rg --type go "NewCircuitBreakerDecorator\s*\(" ./protocol/x/accountplus/ante

Length of output: 1181

protocol/testutil/constants/stateful_orders.go (1)

297-308: New long-term order added for Bob with ClobPairId 1

The new order LongTermOrder_Bob_Num0_Id0_Clob1_Buy25_Price30_GTBT10 has been added, which is similar to existing orders but uses ClobPairId 1 instead of 0. This addition expands the test coverage to include orders for different CLOB pairs.

A few observations:

  1. The order is consistent with the naming convention used for other long-term orders.
  2. It uses the same SubaccountId (Bob_Num0) and ClientId (0) as some existing Bob orders, which is fine for testing purposes.
  3. The order parameters (Side, Quantums, Subticks, GoodTilBlockTime) are within the range of values used in other test orders.

This addition will allow for more comprehensive testing of the system's behavior with multiple CLOB pairs.

To ensure consistency and completeness, let's verify if there are other orders for ClobPairId 1:

protocol/app/ante.go (2)

127-133: Good refactoring: Chaining NewAuthenticatorDecorator with sdk.ChainAnteDecorators

The introduction of sdk.ChainAnteDecorators to chain the NewAuthenticatorDecorator enhances code clarity and maintainability by simplifying the ante decorator chain.


135-141: Streamlined ante handlers using sdk.ChainAnteDecorators

Chaining SetPubKeyDecorator, SigGasConsumeDecorator, and SigVerificationDecorator with sdk.ChainAnteDecorators simplifies the ante handler logic and improves readability.

protocol/x/clob/e2e/permissioned_keys_test.go (3)

670-670: Verify Usage of Alice's Public Key in Authenticator Config

The SignatureVerification authenticator is configured with constants.AlicePrivateKey.PubKey().Bytes(). Verify that using Alice's public key here is intentional and aligns with the test scenarios. This ensures that only transactions signed by Alice's private key are accepted.


848-848: Confirm Account Number and Sequence Number for Alice

In this test case, the transaction is signed using Alice's private key, but AccountNum is set to []uint64{1} and SeqNum is []uint64{0}. Ensure that these values correspond to Alice's account. If Alice's account number is 0, the AccountNum should be updated to reflect this.

Apply this diff if an update is needed:

 Fees:       constants.TestFeeCoins_5Cents,
 Gas:        0,
-AccountNum: []uint64{1},
+AccountNum: []uint64{0},
 SeqNum:     []uint64{0},
 // Sign using Alice's private key.
 Signers: []cryptotypes.PrivKey{constants.AlicePrivateKey},

1395-1400: Check for Empty Expected Log Messages

In the assertion for the response log, require.Contains is used with msg.ExpectedLog, which might be empty in some test cases. Consider adding a check to ensure that ExpectedLog is not empty before using it in the assertion to avoid misleading test results.

Apply this diff to add the check:

+if msg.ExpectedLog != "" {
     require.Contains(
         t,
         resp.Log,
         msg.ExpectedLog,
         "Response log was not as expected",
     )
+}
protocol/app/app.go (1)

1115-1136: LGTM: Initialization of AuthenticatorManager and AccountPlusKeeper

The initialization of the AuthenticatorManager and the AccountPlusKeeper is correctly implemented. The code is clear and aligns with best practices.

Comment on lines +14 to +15
authenticatorAnteHandlerFlow sdk.AnteHandler
originalAnteHandlerFlow sdk.AnteHandler
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

Action Required: Address Remaining sdk.AnteDecorator Usages

The recent changes in circuit_breaker.go simplify the interface by transitioning from sdk.AnteDecorator to sdk.AnteHandler. However, the following files still utilize sdk.AnteDecorator:

  • protocol/x/clob/ante/rate_limit.go
  • protocol/x/clob/ante/clob.go
  • protocol/x/accountplus/ante/circuit_breaker_test.go
  • protocol/mocks/AnteDecorator.go
  • protocol/app/ante.go
  • Multiple test files within protocol/app/ante/

To ensure full consistency and prevent potential integration issues, please update these usages to sdk.AnteHandler where appropriate.

🔗 Analysis chain

LGTM! Verify impact on codebase.

The change from sdk.AnteDecorator to sdk.AnteHandler for both authenticatorAnteHandlerFlow and originalAnteHandlerFlow fields simplifies the interface and aligns with the modifications in the rest of the file. This is a good improvement in terms of code clarity and consistency.

To ensure this change doesn't introduce any issues, please run the following script to check for any remaining usages of sdk.AnteDecorator in the codebase:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for remaining usages of sdk.AnteDecorator

# Test: Search for sdk.AnteDecorator usages
rg --type go 'sdk\.AnteDecorator'

Length of output: 10145

Comment on lines +1414 to +1416
_, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}
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

Handle Possible Errors from GetOrderFillAmount

The error returned by GetOrderFillAmount is currently ignored. To ensure test accuracy and prevent false positives, it's important to check and handle this error.

Apply this diff to handle the error:

 for orderId, expectedFillAmount := range tc.expectedOrderFillAmounts {
-    _, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
+    _, fillAmount, err := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
+    require.NoError(t, err, "Failed to get fill amount for order %v", orderId)
     require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
 }
📝 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
_, fillAmount, _ := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}
_, fillAmount, err := tApp.App.ClobKeeper.GetOrderFillAmount(ctx, orderId)
require.NoError(t, err, "Failed to get fill amount for order %v", orderId)
require.Equal(t, expectedFillAmount, fillAmount.ToUint64())
}

Comment on lines +668 to +684
{
Type: "SignatureVerification",
Config: constants.AlicePrivateKey.PubKey().Bytes(),
},
{
Type: "MessageFilter",
Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
},
{
Type: "ClobPairIdFilter",
Config: []byte("0,1"),
},
{
Type: "SubaccountFilter",
Config: []byte("0,1"),
},
}
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

Refactor Authenticator Configuration into a Helper Function

The authenticator configuration setup is repeated across multiple test cases. Consider refactoring this code into a helper function to adhere to the DRY (Don't Repeat Yourself) principle and enhance maintainability.

Apply this diff to create a helper function:

+func createCompositeAuthenticatorConfig() []byte {
+    config := []aptypes.SubAuthenticatorInitData{
+        {
+            Type:   "SignatureVerification",
+            Config: constants.AlicePrivateKey.PubKey().Bytes(),
+        },
+        {
+            Type:   "MessageFilter",
+            Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
+        },
+        {
+            Type:   "ClobPairIdFilter",
+            Config: []byte("0,1"),
+        },
+        {
+            Type:   "SubaccountFilter",
+            Config: []byte("0,1"),
+        },
+    }
+    compositeAuthenticatorConfig, err := json.Marshal(config)
+    if err != nil {
+        panic(err)
+    }
+    return compositeAuthenticatorConfig
+}
+
 func TestPlaceOrder_PermissionedKeys_Success(t *testing.T) {
-    config := []aptypes.SubAuthenticatorInitData{
-        {
-            Type:   "SignatureVerification",
-            Config: constants.AlicePrivateKey.PubKey().Bytes(),
-        },
-        {
-            Type:   "MessageFilter",
-            Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
-        },
-        {
-            Type:   "ClobPairIdFilter",
-            Config: []byte("0,1"),
-        },
-        {
-            Type:   "SubaccountFilter",
-            Config: []byte("0,1"),
-        },
-    }
-    compositeAuthenticatorConfig, err := json.Marshal(config)
-    require.NoError(t, err)
+    compositeAuthenticatorConfig := createCompositeAuthenticatorConfig()

Committable suggestion was skipped due to low confidence.

},
{
Type: "MessageFilter",
Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
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

Ensure Correct Message Type in MessageFilter

The MessageFilter authenticator uses the message type /dydxprotocol.clob.MsgPlaceOrder. Verify that this string correctly matches the fully-qualified type name of the MsgPlaceOrder message. If the actual message type includes a version suffix (e.g., /dydxprotocol.clob.v1.MsgPlaceOrder), update the filter accordingly to prevent mismatches.

Apply this diff if an update is needed:

 {
     Type:   "MessageFilter",
-    Config: []byte("/dydxprotocol.clob.MsgPlaceOrder"),
+    Config: []byte("/dydxprotocol.clob.v1.MsgPlaceOrder"),
 },

Committable suggestion was skipped due to low confidence.

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.

1 participant