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-1202] logic to handle unauthorized maker orders when authenticato… #2412

Merged
merged 7 commits into from
Oct 2, 2024

Conversation

jayy04
Copy link
Contributor

@jayy04 jayy04 commented Sep 30, 2024

…rs are removed

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 a method for validating transaction authenticators, enhancing transaction security.
    • Added functionality to retrieve transaction bytes for short-term orders.
    • Expanded account management capabilities with a new interface for smart accounts.
    • Integrated AccountPlusKeeper for improved account management across modules.
  • Improvements

    • Refined order handling logic and improved checks for maker orders.
    • Enhanced testing coverage for order placements, liquidations, and state management.
    • Standardized return value handling across multiple methods for better error management.
  • Bug Fixes

    • Added error handling for transactions with multiple signers to prevent processing errors.
    • Improved logging for daemon registration failures to enhance monitoring.
  • Documentation

    • Updated interfaces and method signatures to reflect new functionalities and improve clarity.

@jayy04 jayy04 requested a review from a team as a code owner September 30, 2024 21:26
Copy link
Contributor

coderabbitai bot commented Sep 30, 2024

Walkthrough

The changes introduce a new AccountPlusKeeper to the App struct for enhanced account management and integrate a MaybeValidateAuthenticators method across various components. The Keeper struct is updated to utilize this new keeper, while several methods related to order handling and transaction validation are refined. New error handling and metrics initialization for the oracle are also implemented, alongside expanded testing coverage for the CLOB module's functionalities.

Changes

File Path Summary of Changes
protocol/app/app.go Added AccountPlusKeeper to App struct; updated createProposalHandlers to handle price updates; modified initOracle and introduced initOracleMetrics.
protocol/x/clob/keeper/keeper.go Added accountPlusKeeper field to Keeper struct; updated NewKeeper constructor to initialize this field.
protocol/mocks/MemClobKeeper.go Added MaybeValidateAuthenticators method; updated SendOrderbookFillUpdate to handle a single fill; standardized return value handling across several methods.
protocol/testutil/memclob/keeper.go Introduced MaybeValidateAuthenticators method in FakeMemClobKeeper; added placeholder method AddOrderToOrderbookSubaccountUpdatesCheck.
protocol/x/clob/keeper/authenticators.go Added MaybeValidateAuthenticators function for validating transaction authenticators; includes checks for active accounts and signer validation.
protocol/x/clob/types/errors.go Introduced new error variable ErrTxnHasMultipleSigners for handling transaction errors.
protocol/x/clob/types/expected_keepers.go Added new interface AccountPlusKeeper with methods for checking account status and retrieving authenticators.
protocol/x/clob/types/mem_clob_keeper.go Added MaybeValidateAuthenticators method to MemClobKeeper interface.
protocol/x/clob/types/operations_to_propose.go Introduced MustGetShortTermOrderTxBytes method to retrieve transaction bytes for short-term orders with validation checks.
protocol/x/clob/abci_test.go Added and modified test cases for EndBlocker, BeginBlocker, and PrepareCheckState functions, enhancing coverage for order processing and state management.
protocol/x/clob/keeper/liquidations_test.go Introduced multiple test cases for liquidation functionality, covering various scenarios and edge cases.
protocol/x/clob/keeper/orders_test.go Enhanced test cases for placing short-term and stateful orders; added checks for error conditions and improved regression tests.
protocol/testutil/keeper/accountplus.go Renamed functions for clarity regarding AccountPlus functionality; adjusted internal logic accordingly.

Possibly related PRs

Suggested labels

feature:timestamp_nonce

Suggested reviewers

  • roy-dydx
  • teddyding

Poem

🐇 In the meadow where transactions play,
New methods hop in, brightening the day.
Authenticators validated with glee,
Order handling flows like a soft, gentle breeze.
With each little change, our code takes flight,
Hopping towards futures, oh what a delight! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e200b1f and 4070e80.

📒 Files selected for processing (1)
  • protocol/testutil/keeper/accountplus.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • protocol/testutil/keeper/accountplus.go

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai 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: 7

🧹 Outside diff range and nitpick comments (7)
protocol/x/clob/types/mem_clob_keeper.go (1)

118-118: Consider architectural implications of the new method

While the new MaybeValidateAuthenticators method addresses the PR objective, it raises some architectural concerns:

  1. This method introduces authentication responsibilities to the MemClobKeeper, which may violate the single responsibility principle. Consider if this functionality belongs in a separate authentication service or middleware.

  2. The "Maybe" prefix suggests optional execution, which could lead to inconsistent usage across the codebase. It might be better to have a clear, always-executed validation method, with the conditional logic handled by the caller.

  3. It's not clear how this method integrates with the existing methods in the interface. Consider adding documentation or reorganizing the interface to show the relationship between methods.

Consider the following alternatives:

  1. Create a separate AuthenticatorValidator interface and inject it into MemClobKeeper.
  2. Rename the method to ValidateAuthenticators and handle the conditional execution in the implementation or caller.
  3. Add documentation to clarify the method's role in the overall process flow of the keeper.
protocol/x/clob/types/expected_keepers.go (1)

189-196: LGTM: New AccountPlusKeeper interface. Consider adding documentation.

The new AccountPlusKeeper interface is well-structured and aligns with the PR objectives. The method names are clear and their signatures are appropriate for their purposes.

Consider adding documentation for the interface and its methods to improve maintainability. For example:

// AccountPlusKeeper defines the expected account plus keeper used for handling smart accounts and their authenticators.
type AccountPlusKeeper interface {
    // GetIsSmartAccountActive returns whether smart accounts are currently active in the system.
    GetIsSmartAccountActive(ctx sdk.Context) bool

    // GetInitializedAuthenticatorForAccount retrieves an initialized authenticator for the specified account and selected authenticator index.
    GetInitializedAuthenticatorForAccount(
        ctx sdk.Context,
        account sdk.AccAddress,
        selectedAuthenticator uint64,
    ) (aptypes.InitializedAuthenticator, error)
}
protocol/x/clob/keeper/keeper.go (1)

47-47: Consider broader impact of accountPlusKeeper addition.

The changes in this file are minimal and focused on adding the accountPlusKeeper functionality to the CLOB module's Keeper. This suggests that this change is part of a larger feature implementation or refactoring related to account management.

To ensure a comprehensive implementation:

  1. Review the AccountPlusKeeper interface definition and implementation.
  2. Check for any necessary updates to the CLOB module's logic that might benefit from the new accountPlusKeeper functionality.
  3. Ensure that all relevant tests have been updated or added to cover the new functionality.
  4. Update the module's documentation to reflect the addition of accountPlusKeeper and its purpose within the CLOB module.
#!/bin/bash
# Search for AccountPlusKeeper interface definition
rg --type go 'type AccountPlusKeeper interface' protocol

# Search for potential usage of accountPlusKeeper in the CLOB module
rg --type go 'accountPlusKeeper\.' protocol/x/clob

# Search for test files that might need updates
rg --type go 'func Test.*Keeper' protocol/x/clob
protocol/x/clob/types/errors.go (1)

228-232: LGTM with a minor suggestion for consistency.

The addition of ErrTxnHasMultipleSigners is appropriate and well-placed within the existing error definitions. The error code (49) follows the sequence, and the message clearly describes the issue.

For consistency with other error messages in this file, consider capitalizing the first letter of the error message:

 ErrTxnHasMultipleSigners = errorsmod.Register(
 	ModuleName,
 	49,
-	"The transaction has multiple signers",
+	"Transaction has multiple signers",
 )
protocol/testutil/memclob/keeper.go (1)

532-534: LGTM: Placeholder implementation for testing purposes.

The MaybeValidateAuthenticators method is correctly implemented as a placeholder for the FakeMemClobKeeper. It always returns nil, which is appropriate for testing scenarios where actual authentication validation is not needed.

Consider adding a comment to explain that this is a placeholder implementation for testing purposes. This would improve code readability and make the intent clear for other developers. For example:

 func (f *FakeMemClobKeeper) MaybeValidateAuthenticators(ctx sdk.Context, txBytes []byte) error {
+	// Placeholder implementation for testing purposes.
+	// In a real implementation, this method would validate authenticators.
 	return nil
 }
protocol/x/clob/types/operations_to_propose.go (1)

479-501: LGTM! Consider enhancing the error message.

The implementation of MustGetShortTermOrderTxBytes is correct and consistent with the existing codebase. It properly validates the input, retrieves the data, and handles errors by panicking, which is expected for a "Must" prefixed method.

Consider enhancing the error message to include the order hash for easier debugging:

 				"MustGetShortTermOrderTxBytes: Order (%s) does not exist in "+
-					"`ShortTermOrderHashToTxBytes`.",
+					"`ShortTermOrderHashToTxBytes`. Order hash: %s",
 				order.GetOrderTextString(),
+				orderHash,
 			),
protocol/x/clob/keeper/authenticators.go (1)

16-73: Add unit tests for MaybeValidateAuthenticators function

To ensure the correctness and reliability of the MaybeValidateAuthenticators function, consider adding unit tests that cover various scenarios:

  • Transactions with no authenticators specified.
  • Smart account flow inactive.
  • Invalid transaction types.
  • Transactions with multiple signers.
  • Invalid or removed authenticators.

Do you need assistance in creating unit tests for this function? I can help generate test cases or open a GitHub issue to track this task.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 07fc0b6 and e43f28d.

📒 Files selected for processing (9)
  • protocol/mocks/MemClobKeeper.go (2 hunks)
  • protocol/testutil/memclob/keeper.go (1 hunks)
  • protocol/x/clob/keeper/authenticators.go (1 hunks)
  • protocol/x/clob/keeper/keeper.go (1 hunks)
  • protocol/x/clob/memclob/memclob.go (1 hunks)
  • protocol/x/clob/types/errors.go (1 hunks)
  • protocol/x/clob/types/expected_keepers.go (2 hunks)
  • protocol/x/clob/types/mem_clob_keeper.go (1 hunks)
  • protocol/x/clob/types/operations_to_propose.go (1 hunks)
🔇 Additional comments (15)
protocol/x/clob/types/mem_clob_keeper.go (2)

118-118: Final thoughts and reminders

The addition of the MaybeValidateAuthenticators method to the MemClobKeeper interface addresses the PR objective of handling unauthorized maker orders. However, please ensure the following:

  1. Update any relevant documentation to reflect this new method and its purpose in the overall system architecture.
  2. Add or update unit tests to cover the new method and its various use cases, including edge cases and error scenarios.
  3. Consider the architectural and security implications raised in the previous comments.

To check for updated documentation and tests, run:


118-118: Address potential security implications of the new method

The MaybeValidateAuthenticators method introduces some security considerations that should be addressed:

  1. Operating on raw transaction bytes could expose the system to malformed or malicious input. Ensure that proper input sanitization and validation are performed before processing these bytes.

  2. Consider adding logging or alerting mechanisms for failed validations to aid in detecting potential security issues or attacks.

  3. The placement of this authentication-related method in the MemClobKeeper interface might not provide the best separation of concerns for security-critical operations. Consider moving this functionality to a dedicated security or authentication module.

To ensure proper error handling and logging are implemented, run the following script:

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

10-10: LGTM: Import statement for accountplus types.

The addition of the import statement for the accountplus types package is necessary for the new AccountPlusKeeper interface. The use of the alias aptypes is consistent with the naming convention used in other imports.

protocol/x/clob/keeper/keeper.go (1)

47-47: LGTM. Verify usage of the new accountPlusKeeper field.

The addition of the accountPlusKeeper field to the Keeper struct is appropriate. This change suggests that the CLOB module now requires additional account-related functionality.

To ensure proper integration, please verify the usage of accountPlusKeeper throughout the module:

#!/bin/bash
# Search for usage of accountPlusKeeper in the CLOB module
rg --type go 'accountPlusKeeper' protocol/x/clob
protocol/x/clob/types/errors.go (1)

228-232: Verify the usage and impact of the new error.

The introduction of ErrTxnHasMultipleSigners suggests new logic for handling transactions with multiple signers. To ensure this change doesn't introduce unexpected behavior:

  1. Confirm where and how this error is being used in the codebase.
  2. Verify that existing transaction processing flows properly handle this new error case.
  3. Ensure that appropriate tests have been added to cover scenarios where this error might be thrown.

To help verify the usage of this new error, you can run the following script:

This will help identify where the new error is being used and any related changes in transaction processing logic.

protocol/testutil/memclob/keeper.go (2)

Line range hint 526-530: LGTM: Placeholder implementation for testing purposes.

The AddOrderToOrderbookSubaccountUpdatesCheck method is correctly implemented as a placeholder for the FakeMemClobKeeper. It satisfies the interface requirement and always returns satypes.Success, which is appropriate for testing scenarios where actual validation logic is not needed.


Line range hint 526-534: Overall assessment: Changes are appropriate for testing purposes.

The additions to FakeMemClobKeeper are well-implemented placeholders that satisfy interface requirements. These changes enhance the fake keeper's ability to mimic the real keeper's behavior in test scenarios without introducing actual logic. This approach is suitable for unit testing and allows for flexible test setups.

protocol/mocks/MemClobKeeper.go (2)

291-307: LGTM: New method MaybeValidateAuthenticators added

The new method MaybeValidateAuthenticators has been correctly implemented following the established pattern for mock methods in this file. This addition aligns with the PR objective of handling unauthorized maker orders.


436-439: Verify usage of updated SendOrderbookFillUpdate method

The SendOrderbookFillUpdate method has been updated to handle a single orderbookFill instead of multiple orderbookFills. This change might impact how the method is used in other parts of the codebase.

Please run the following script to check for any potential impacts:

✅ Verification successful

Verified: All usages of SendOrderbookFillUpdate conform to the updated single orderbookFill parameter signature. No issues detected.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for usages of SendOrderbookFillUpdate method
# and verify if they align with the new signature.

# Search for method calls
rg --type go "SendOrderbookFillUpdate\(" -A 3

Length of output: 3568

protocol/x/clob/keeper/authenticators.go (6)

14-15: Well-documented function purpose

The comments clearly explain the purpose and behavior of the MaybeValidateAuthenticators function, adhering to good Go documentation practices.


18-21: Proper error handling when decoding the transaction

The transaction is correctly decoded from txBytes, and errors are appropriately handled.


23-27: Efficient check for specified authenticators

The code efficiently checks if the transaction has authenticators specified and returns early if not, improving performance by avoiding unnecessary processing.


31-33: Correct verification of smart account activation

The function appropriately checks if the smart account flow is active and returns an error if it is not, ensuring that the subsequent logic is only executed when valid.


35-39: Proper type assertion for SigVerifiableTx

The transaction is correctly asserted to be of type authsigning.SigVerifiableTx, and an error is returned if the assertion fails, preventing potential runtime panics.


41-44: Appropriate retrieval and handling of signers

The signers are retrieved using GetSigners(), and errors are properly handled, ensuring that the function operates on valid signer information.

@@ -115,4 +115,5 @@ type MemClobKeeper interface {
subaccountId satypes.SubaccountId,
order PendingOpenOrder,
) satypes.UpdateResult
MaybeValidateAuthenticators(ctx sdk.Context, txBytes []byte) error
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

Missing MaybeValidateAuthenticators Implementation in MemClobKeeper Interface

The MaybeValidateAuthenticators method has been added to the MemClobKeeper interface, but it appears that many implementations do not include this method. Please ensure that all concrete types implementing MemClobKeeper provide an implementation for MaybeValidateAuthenticators to maintain interface compliance.

  • protocol/streaming/full_node_streaming_manager.go
  • protocol/streaming/noop_streaming_manager.go
  • protocol/streaming/ws/websocket_message_sender.go
  • protocol/streaming/ws/websocket_server.go
  • ... (additional files as identified)
🔗 Analysis chain

New method added to MemClobKeeper interface

The addition of MaybeValidateAuthenticators method aligns with the PR objective of handling unauthorized maker orders. However, there are a few points to consider:

  1. The method name uses "Maybe", suggesting conditional execution. Consider documenting when this validation occurs.
  2. The method operates on raw transaction bytes. Ensure that this level of access is necessary and doesn't bypass any security measures.
  3. As this is an interface method, all implementations of MemClobKeeper will need to be updated to include this method.

To ensure all implementations are updated, run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all implementations of MemClobKeeper and check for MaybeValidateAuthenticators method

# Find all Go files that might implement MemClobKeeper
implementers=$(fd -e go | xargs grep -l "type.*struct.*{")

# Check each potential implementer for the new method
for file in $implementers; do
  if grep -q "func.*MaybeValidateAuthenticators" "$file"; then
    echo "Implementation found in $file"
  else
    echo "Potential missing implementation in $file"
  fi
done

Length of output: 148215

Comment on lines 189 to 196
type AccountPlusKeeper interface {
GetIsSmartAccountActive(ctx sdk.Context) bool
GetInitializedAuthenticatorForAccount(
ctx sdk.Context,
account sdk.AccAddress,
selectedAuthenticator uint64,
) (aptypes.InitializedAuthenticator, error)
}
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

No implementations of the AccountPlusKeeper interface were found.

While the AccountPlusKeeper interface is defined and its methods are being utilized in the codebase, there are currently no concrete implementations of this interface. This could lead to potential runtime issues or indicate an incomplete integration of the new interface.

  • Action Items:
    • Implement the AccountPlusKeeper interface: Ensure that at least one struct in the codebase implements this interface to fulfill its contract.
    • Review usage points: Verify that all usages of the interface's methods correspond to an actual implementation to prevent potential runtime errors.
🔗 Analysis chain

Verify usage of the new AccountPlusKeeper interface.

The new AccountPlusKeeper interface looks good and aligns with the PR objectives. To ensure its proper integration, please verify that this interface is implemented and used correctly in other parts of the codebase.

Run the following script to check the usage of the new interface:

This script will help ensure that the new interface is properly implemented and its methods are being used in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation and usage of the AccountPlusKeeper interface.

# Test 1: Check for the interface implementation
echo "Checking for AccountPlusKeeper implementation:"
rg --type go "type \w+ struct" -A 10 | rg "AccountPlusKeeper"

# Test 2: Check for the usage of GetIsSmartAccountActive method
echo "Checking for usage of GetIsSmartAccountActive method:"
rg --type go "GetIsSmartAccountActive\("

# Test 3: Check for the usage of GetInitializedAuthenticatorForAccount method
echo "Checking for usage of GetInitializedAuthenticatorForAccount method:"
rg --type go "GetInitializedAuthenticatorForAccount\("

Length of output: 1975

@@ -44,6 +44,7 @@ type (
rewardsKeeper types.RewardsKeeper
affiliatesKeeper types.AffiliatesKeeper
revshareKeeper types.RevShareKeeper
accountPlusKeeper types.AccountPlusKeeper
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

Issues Found: Incomplete Implementation of accountPlusKeeper in NewKeeper

The NewKeeper function signature in protocol/x/clob/keeper/keeper.go has been updated to include the accountPlusKeeper parameter. However, the implementation does not initialize this new field within the Keeper struct. Additionally, multiple calls to NewKeeper across the project are missing the required accountPlusKeeper parameter.

Affected Areas:

  • protocol/x/clob/keeper/keeper.go: NewKeeper implementation missing initialization of accountPlusKeeper.
  • Numerous instances across the project where NewKeeper is called without the accountPlusKeeper parameter, including but not limited to:
    • protocol/x/stats/keeper/keeper.go
    • protocol/x/subaccounts/keeper/keeper.go
    • protocol/testutil/keeper/assets.go
    • protocol/app/app.go

Please address these issues to ensure that the accountPlusKeeper is properly integrated and initialized throughout the codebase.

🔗 Analysis chain

LGTM. Verify NewKeeper implementation and usage.

The addition of the accountPlusKeeper parameter to the NewKeeper function signature is consistent with the struct change. However, we need to ensure that the implementation properly initializes this new field.

Please verify the following:

  1. The NewKeeper function implementation:

  2. All calls to NewKeeper have been updated:


Action Required: Update All NewKeeper Calls to Include accountPlusKeeper

The NewKeeper function signature has been updated to include the accountPlusKeeper parameter. However, the implementation in protocol/x/clob/keeper/keeper.go does not initialize this new field. Additionally, ensure that all calls to NewKeeper across the project are updated to include the accountPlusKeeper parameter to maintain consistency and prevent potential issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Show the NewKeeper function implementation
rg --type go -A 30 'func NewKeeper\(' protocol/x/clob/keeper/keeper.go

Length of output: 1216


Script:

#!/bin/bash
# Find all calls to NewKeeper in the project
rg --type go 'NewKeeper\(' protocol

Length of output: 5220


Script:

#!/bin/bash
# Identify NewKeeper calls missing the 'accountPlusKeeper' parameter
rg --type go 'NewKeeper\(' protocol | grep -v 'accountPlusKeeper'

Length of output: 5248

Comment on lines 58 to 72
_, err := k.accountPlusKeeper.GetInitializedAuthenticatorForAccount(
ctx,
account,
authenticatorId,
)
if err != nil {
return errorsmod.Wrapf(
err,
"selected authenticator (%s, %d) is not registered or removed from state",
account.String(),
authenticatorId,
)
}
}
return nil
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 error messages do not disclose sensitive information

When wrapping errors that include account addresses and authenticator IDs, consider whether including this information is appropriate. Exposing sensitive details in error messages may pose security risks.

If necessary, you might limit the amount of detail in the error messages or ensure that such messages are only logged internally and not exposed to end-users.

protocol/x/clob/keeper/authenticators.go Outdated Show resolved Hide resolved
protocol/x/clob/memclob/memclob.go Show resolved Hide resolved
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: 3

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e43f28d and e0366ae.

📒 Files selected for processing (3)
  • protocol/x/clob/abci_test.go (1 hunks)
  • protocol/x/clob/keeper/liquidations_test.go (2 hunks)
  • protocol/x/clob/keeper/orders_test.go (2 hunks)
🔇 Additional comments (2)
protocol/x/clob/abci_test.go (1)

1215-1222: Order placement test setup correctly initializes transaction context

The code properly creates a temporary context with TxBytes to simulate a transaction during order placement in testing. Error handling is appropriately performed using require.NoError(t, err).

protocol/x/clob/keeper/liquidations_test.go (1)

1318-1327: Refactor duplicated code for setting TxBytes into a helper function

This code block is identical to the one at lines 355-364. Refactoring into a helper function as suggested earlier will reduce code duplication and improve maintainability.

Comment on lines +1215 to +1222
txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
err := txBuilder.SetMsgs(operation.GetShortTermOrderPlacement())
require.NoError(t, err)
bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
require.NoError(t, err)
tempCtx = tempCtx.WithTxBytes(bytes)

_, _, err = ks.ClobKeeper.PlaceShortTermOrder(
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 writeCache() is called to commit state changes

After successfully placing the short-term order with PlaceShortTermOrder, you should call writeCache() to commit the changes from the cached context to the main context. Otherwise, the modifications in tempCtx won't persist, and the order placement might not have the intended effect in the test.

Comment on lines +626 to +634
msg := &types.MsgPlaceOrder{Order: order}

txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
err := txBuilder.SetMsgs(msg)
require.NoError(t, err)
bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
require.NoError(t, err)
ctx = ctx.WithTxBytes(bytes)

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 duplicated code into a helper function

The code in lines 626-634 and 644-651 is duplicated. To improve maintainability and adhere to the DRY (Don't Repeat Yourself) principle, consider extracting this repeated code into a helper function.

Apply this diff to refactor the code:

-    msg := &types.MsgPlaceOrder{Order: order}
-
-    txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
-    err := txBuilder.SetMsgs(msg)
-    require.NoError(t, err)
-    bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
-    require.NoError(t, err)
-    ctx = ctx.WithTxBytes(bytes)
+    ctx, err = prepareTxWithMsg(ctx, &types.MsgPlaceOrder{Order: order})
+    require.NoError(t, err)
-    msg := &types.MsgPlaceOrder{Order: tc.order}
-
-    txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
-    err = txBuilder.SetMsgs(msg)
-    require.NoError(t, err)
-    bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
-    require.NoError(t, err)
-    ctx = ctx.WithTxBytes(bytes)
+    ctx, err = prepareTxWithMsg(ctx, &types.MsgPlaceOrder{Order: tc.order})
+    require.NoError(t, err)

Define the helper function outside the selected line ranges:

func prepareTxWithMsg(ctx sdk.Context, msg sdk.Msg) (sdk.Context, error) {
    txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
    err := txBuilder.SetMsgs(msg)
    if err != nil {
        return ctx, err
    }
    bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
    if err != nil {
        return ctx, err
    }
    return ctx.WithTxBytes(bytes), nil
}

Also applies to: 644-651

Comment on lines +355 to +364
msg := &types.MsgPlaceOrder{Order: order}

txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
err := txBuilder.SetMsgs(msg)
require.NoError(t, err)
bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
require.NoError(t, err)
ctx = ctx.WithTxBytes(bytes)

_, _, err = ks.ClobKeeper.PlaceShortTermOrder(ctx, msg)
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 duplicated code for setting TxBytes into a helper function

The code for creating a transaction builder, setting messages, encoding the transaction, and updating ctx.TxBytes is duplicated. Consider refactoring this code into a helper function to improve maintainability and reduce code duplication.

You can create a helper function like this:

func setContextTxBytes(ctx sdk.Context, msg sdk.Msg) (sdk.Context, error) {
  txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
  err := txBuilder.SetMsgs(msg)
  if err != nil {
    return ctx, err
  }
  bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
  if err != nil {
    return ctx, err
  }
  return ctx.WithTxBytes(bytes), nil
}

Then, replace the duplicated code with:

-    txBuilder := constants.TestEncodingCfg.TxConfig.NewTxBuilder()
-    err := txBuilder.SetMsgs(msg)
-    require.NoError(t, err)
-    bytes, err := constants.TestEncodingCfg.TxConfig.TxEncoder()(txBuilder.GetTx())
-    require.NoError(t, err)
-    ctx = ctx.WithTxBytes(bytes)
+    ctx, err = setContextTxBytes(ctx, msg)
+    require.NoError(t, err)


// MaybeValidateAuthenticators checks if the transaction has authenticators specified and if so,
// validates them. It returns an error if the authenticators are not valid or removed from state.
func (k Keeper) MaybeValidateAuthenticators(ctx sdk.Context, txBytes []byte) error {
Copy link
Contributor

Choose a reason for hiding this comment

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

None of the logic here is specific to x/clob - should this function be a method in CLOB or Accountplus?

@@ -0,0 +1,73 @@
package keeper
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, this PR doesn't need to touch ProcessOperations explicitly, because it's already taken care of by calling AnteHandler on the orders right?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

correct.

again, the assumption here is that the light weight validation is sufficient because all current validations are stateless

Copy link
Contributor

Choose a reason for hiding this comment

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

Correct, and ProcessOperations do run the anthenticators explicitly since we cannot trust the proposer

// validates them. It returns an error if the authenticators are not valid or removed from state.
func (k Keeper) MaybeValidateAuthenticators(ctx sdk.Context, txBytes []byte) error {
// Decode the tx from the tx bytes.
tx, err := k.txDecoder(txBytes)
Copy link
Contributor

Choose a reason for hiding this comment

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

We need to decode maker orders for all fills (regardless of smart account) - do we think this is okay because there are not many fews?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I was planning to look at frame graphs after this is merged and deployed and optimize only if needed. I feel like this might be okay since like you said, only a very small percentage of the orders get matched.

note that all crossing maker orders get decoded, not just those that generate a fill

// are registered and not removed from state.
//
// Note that we only verify the existence of the authenticators here without actually
// runnning them. This is because all current authenticators are stateless and do not read/modify any states.
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we document the we are not running the authenticators due to deadlock concerns

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 (3)
protocol/x/accountplus/keeper/authenticators.go (3)

13-13: Organize Imports for Better Readability

The imports at lines 13 and 16 introduce new packages. Consider grouping imports into standard library packages, third-party packages, and local packages, and separating them with blank lines to improve readability.

Also applies to: 16-16


46-48: Consider Supporting Multiple Signers if Applicable

At lines 46-48, the code returns an error if there are multiple signers, enforcing that only one signer is allowed.

  • Architecture Advice: Evaluate if there are valid cases where multiple signers should be permitted, such as multi-signature transactions. If so, consider updating the logic to handle multiple signers appropriately.

50-51: Simplify Conversion to sdk.AccAddress

At line 50, the code converts the first signer to an sdk.AccAddress:

account := sdk.AccAddress(signers[0])
  • Suggestion: Ensure that signers[0] is already of type sdk.AccAddress to avoid unnecessary conversions. If signers is not guaranteed to be of this type, add appropriate checks or handle potential conversion errors.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e0366ae and 7249c08.

📒 Files selected for processing (4)
  • protocol/x/accountplus/keeper/authenticators.go (1 hunks)
  • protocol/x/accountplus/types/errors.go (1 hunks)
  • protocol/x/clob/keeper/authenticators.go (1 hunks)
  • protocol/x/clob/types/expected_keepers.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • protocol/x/clob/keeper/authenticators.go
  • protocol/x/clob/types/expected_keepers.go
🔇 Additional comments (4)
protocol/x/accountplus/types/errors.go (2)

Line range hint 1-35: Overall, the change looks good and aligns with the PR objectives.

The addition of ErrTxnHasMultipleSigners enhances the error handling capabilities of the accountplus module, specifically addressing scenarios where unauthorized maker orders might occur due to multiple signers. This change is consistent with the existing error definitions and contributes to the PR's goal of improving the handling of unauthorized maker orders.


31-35: New error definition looks good, but consider improving the error message.

The addition of ErrTxnHasMultipleSigners is consistent with the existing error definitions in terms of structure and naming convention. The error code (6) is unique within this file, which is correct.

However, the error message could be more specific to provide better context:

Consider updating the error message to be more descriptive:

 	ErrTxnHasMultipleSigners = errorsmod.Register(
 		ModuleName,
 		6,
-		"The transaction has multiple signers",
+		"Unauthorized: Transaction has multiple signers when only one is expected",
 	)

This change would provide more context about why multiple signers are problematic in this scenario.

To ensure this error is used appropriately, let's check for its usage:

This will help verify that the error is being used in the correct contexts related to handling unauthorized maker orders.

✅ Verification successful

Verified: ErrTxnHasMultipleSigners is used appropriately

The error ErrTxnHasMultipleSigners is correctly utilized within the authenticators.go file to enforce the single signer constraint. The current implementation ensures that transactions with multiple signers are properly handled.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usage of ErrTxnHasMultipleSigners
rg --type go "ErrTxnHasMultipleSigners"

Length of output: 257

protocol/x/accountplus/keeper/authenticators.go (2)

57-72: Optimize Authenticator Retrieval Loop

In the loop from lines 57-72, each selected authenticator is retrieved individually.

  • Performance Consideration: If the number of selected authenticators is large, consider batch retrieval methods or caching mechanisms to minimize state reads and improve performance.

[performance]


31-33: Verify the Smart Account Activation Check

At lines 31-33, the code checks if the smart account flow is active using k.GetIsSmartAccountActive(ctx). Ensure that the smart account activation state is correctly managed elsewhere in the codebase and that this check aligns with the intended system behavior.

Run the following script to verify the usage of GetIsSmartAccountActive:

✅ Verification successful

Smart Account Activation Check Verified

The GetIsSmartAccountActive method correctly retrieves the activation state from the parameters. The IsSmartAccountActive parameter is properly defined and managed within the codebase, ensuring that the activation check aligns with the intended system behavior.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify where and how `GetIsSmartAccountActive` is set.

# Test: Search for all occurrences of `SetIsSmartAccountActive`. Expect: Places where the smart account flow is activated or deactivated.
rg --type go 'SetIsSmartAccountActive'

Length of output: 38


Script:

#!/bin/bash
# Description: Locate the definition and implementation of `GetIsSmartAccountActive`.

# Search for the definition of the method `GetIsSmartAccountActive` within the Go codebase.
ast-grep --lang go --pattern $'func (k *Keeper) GetIsSmartAccountActive($_) bool { $$$ }'

Length of output: 332


Script:

#!/bin/bash
# Description: Locate the definition of the parameters struct containing `IsSmartAccountActive` and all its assignments.

# Search for the struct definition that includes `IsSmartAccountActive`.
ast-grep --lang go --pattern $'type $_ struct { $$$ IsSmartAccountActive $_ $$$ }'

# Search for all assignments to `IsSmartAccountActive`.
ast-grep --lang go --pattern $'$_.IsSmartAccountActive = $_'

Length of output: 498

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 (4)
protocol/testutil/keeper/accountplus.go (2)

Line range hint 19-41: LGTM! Consider updating the comment for clarity.

The renaming from TimestampNonceKeepers to AccountPlusKeepers aligns well with the shift towards AccountPlus functionality. The changes are consistent and maintain the existing logic.

Consider adding a brief comment above the function to describe its purpose, e.g.:

// AccountPlusKeepers initializes and returns the necessary keepers and context for AccountPlus module testing.
func AccountPlusKeepers(t testing.TB) (
    // ... (existing parameters)
) {
    // ... (existing function body)
}

Line range hint 44-68: LGTM! Consider updating import alias for consistency.

The renaming from createTimestampNonceKeeper to createAccountPlusKeeper is consistent with the overall changes and maintains the existing logic.

For better consistency and readability, consider updating the import alias for the keeper package:

- keeper "github.com/dydxprotocol/v4-chain/protocol/x/accountplus/keeper"
+ accountpluskeeper "github.com/dydxprotocol/v4-chain/protocol/x/accountplus/keeper"

Then update the usage:

- k := keeper.NewKeeper(
+ k := accountpluskeeper.NewKeeper(
    // ... (existing parameters)
)

This change would make it clearer that we're dealing with the AccountPlus keeper specifically.

protocol/testutil/keeper/listing.go (2)

61-65: Update tests and documentation for accountPlusKeeper.

With the introduction of accountPlusKeeper:

  1. Ensure that relevant test cases have been updated or added to cover the new functionality.
  2. Update any affected documentation, including API docs and README files, to reflect this change.
  3. Consider adding comments explaining the purpose and importance of accountPlusKeeper in the CLOB module.

Also applies to: 163-163


Line range hint 1-224: Summary: New accountPlusKeeper added to keeper initialization.

The changes introduce accountPlusKeeper to the keeper initialization process, specifically integrating it with the CLOB module. While the implementation looks correct, please provide more context on:

  1. The purpose and functionality of accountPlusKeeper.
  2. Why it was necessary to add this keeper to the CLOB module.
  3. Any expected changes in system behavior due to this addition.

This information will help ensure that the changes align with the PR objectives and that all potential impacts have been considered.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 186588b and e200b1f.

📒 Files selected for processing (3)
  • protocol/testutil/keeper/accountplus.go (3 hunks)
  • protocol/testutil/keeper/clob.go (6 hunks)
  • protocol/testutil/keeper/listing.go (2 hunks)
🔇 Additional comments (8)
protocol/testutil/keeper/accountplus.go (1)

Line range hint 1-68: Overall, the changes look good and align with the PR objectives.

The renaming of functions from TimestampNonce to AccountPlus is consistent throughout the file and reflects the shift in focus towards AccountPlus functionality. The logic remains intact, ensuring that the existing behavior is preserved while improving clarity.

A few minor suggestions have been made to further enhance readability and consistency. Great job on maintaining code quality while refactoring!

protocol/testutil/keeper/listing.go (1)

59-60: LGTM: Minor formatting improvements.

The alignment of closing parentheses enhances code readability.

protocol/testutil/keeper/clob.go (6)

20-20: Importing accountpluskeeper Package

The import statement for accountpluskeeper is correctly added, which integrates the AccountPlus functionality into the module.


55-55: Adding AccountPlusKeeper Field to ClobKeepersTestContext

The addition of the AccountPlusKeeper field to the ClobKeepersTestContext struct is appropriate for incorporating AccountPlus functionality into the test context.


96-102: Initializing AccountPlusKeeper in Test Context

The AccountPlusKeeper is properly initialized using the createAccountPlusKeeper function, ensuring it's ready for use in the test context.


202-202: Passing AccountPlusKeeper to createClobKeeper

The AccountPlusKeeper is correctly passed to the createClobKeeper function, integrating it into the Clob keeper's initialization.


243-243: Updating createClobKeeper Function Signature

The createClobKeeper function signature now includes the accountplusKeeper parameter, which is necessary for the integration with the AccountPlus module.


275-275: Verify keeper.NewKeeper Accepts accountplusKeeper Parameter

Ensure that the keeper.NewKeeper function has been updated to accept the accountplusKeeper parameter and that all instances where keeper.NewKeeper is called include this new parameter.

Run the following script to confirm:

#!/bin/bash
# Description: Verify `keeper.NewKeeper` function definition and its usage.

# Test 1: Check the function definition includes `accountplusKeeper`. Expect: Function definition should have `accountplusKeeper` as a parameter.
rg --type go 'func NewKeeper\(' -A 10 | rg 'accountplusKeeper'

# Test 2: Verify all calls to `keeper.NewKeeper` include `accountplusKeeper`. Expect: All calls should pass `accountplusKeeper` as an argument.
rg --type go 'keeper\.NewKeeper\(' -A 10 | rg 'accountplusKeeper'

protocol/testutil/keeper/listing.go Show resolved Hide resolved
protocol/testutil/keeper/clob.go Show resolved Hide resolved
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.

2 participants