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

refactor: add error field in cctx #2952

Open
wants to merge 10 commits into
base: develop
Choose a base branch
from

Conversation

fbac
Copy link
Contributor

@fbac fbac commented Oct 1, 2024

Description

Closes #2913

Introduce a new function with signature:
UpdateCctxStatus(newStatus CctxStatus, isError bool, statusMsg, errorMsg string)

This function will update the Cctx status accordingly, and update error_message is signaled with isError.

It will populate two fields in the cctx.Status:

  • status_message:

    • if the message is specified and the status change is succesful, the status_message is updated
    • if not specified and the status change is succesful, the status_change will change to a generic "Status changed from %s to %s"
    • if the status change is not succesful, it will carry "Failed to transition status from %s to %s"
  • error_message:

    • if isError && msg != "", update the error_message
    • if isError && msg == "", just place "unknown error"

This results in the following kind of statuses:

status:Aborted status_message:"Status changed from PendingOutbound to Aborted" error_message:"unknown error" lastUpdate_timestamp:5375812124373633744 created_timestamp:5375812124373633744
status:Aborted status_message:"custom message" error_message:"custom error" lastUpdate_timestamp:5375812124373633744 created_timestamp:5375812124373633744
status:Aborted status_message:"Failed to transition status from PendingInbound to Reverted" error_message:"test" lastUpdate_timestamp:5375812124373633744 created_timestamp:5375812124373633744

Notes:

  • SetAbort, SetReverted and SetPendingRevert are always marked as isError. It will mean that any call to these functions specifying a non-empty errorMsg will update
  • SetPendingOutbound and SetOutboundMined are marked as non errors, so they won't update error_message

Introduced minor fixes:

  • keys.go used a deprecated math pkg.
  • rate_limiter_flags_test.go was importing the math pkg twice.
  • remove deprecated errors pkg in msg_server_migrate_tss_funds.go.
  • fixed formatting errors.

How Has This Been Tested?

  • Tested CCTX in localnet
  • Tested in development environment
  • Go unit tests
  • Go integration tests
  • Tested via GitHub Actions

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced support for stateful precompiled contracts and a common importable RPC package.
    • Enhanced Bitcoin chain support for multiple chains and static testnet information.
    • Added staking precompiled contract with event emission capability.
    • New field error_message added to transaction status for improved error reporting.
  • Bug Fixes

    • Resolved issues with outbound transaction processing on EVM chains and duplicate checks in the observer set.
  • Testing Enhancements

    • Added new end-to-end tests for stateful precompiled contracts and improved existing tests for various transaction scenarios.
  • Refactoring

    • Updated method signatures and improved error handling across multiple modules for clearer status updates and error reporting.

Copy link
Contributor

coderabbitai bot commented Oct 1, 2024

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces significant updates across multiple components of the ZetaChain node. Key changes include the addition of an error_message field to various structures, enhancements to cross-chain transaction handling, and improved error reporting mechanisms. Refactoring includes method signature updates and the introduction of new methods for better clarity in error handling. Testing has been expanded to cover new functionalities, ensuring robust validation of cross-chain transactions. The changelog reflects these changes, documenting the evolution of features, tests, and code quality improvements.

Changes

File Path Change Summary
changelog.md Updated to include new features, refactoring, tests, fixes, and CI improvements.
docs/openapi/openapi.swagger.yaml Added error_message property to schema definition.
e2e/e2etests/test_eth_deposit_call.go Updated assertion in TestEtherDepositAndCall to check for "revert executed" in error message.
e2e/e2etests/test_solana_deposit_refund.go Updated assertion in TestSolanaDepositAndCallRefund to check for "revert executed" in error message.
proto/zetachain/zetacore/crosschain/cross_chain_tx.proto Added string error_message field to Status message.
testutil/sample/crosschain.go Added ErrorMessage field to Status struct.
x/crosschain/keeper/cctx.go Added GetCrossChainTxError method to retrieve error messages.
x/crosschain/keeper/cctx_gateway_observers.go Modified error handling in InitiateOutbound method.
x/crosschain/keeper/cctx_gateway_zevm.go Modified error handling in InitiateOutbound method.
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Enhanced error message handling across multiple methods.
x/crosschain/keeper/cctx_test.go Added assertions for error handling in TestCCTXs and new test case in TestCrossChainTx_AddOutbound.
x/crosschain/keeper/initiate_outbound_test.go Renamed assertions to check for ErrorMessage.
x/crosschain/keeper/msg_server_migrate_tss_funds.go Replaced error handling with errorsmod package.
x/crosschain/keeper/msg_server_vote_inbound_tx_test.go Added new test cases and renamed existing functions for clarity.
x/crosschain/keeper/msg_server_vote_outbound_tx.go Updated error handling in SaveFailedOutbound method.
x/crosschain/migrations/v5/migrate.go Added GetAbortedAmount function for handling aborted transactions.
x/crosschain/types/cctx.go Updated status-setting methods to include error messages.
x/crosschain/types/cctx_test.go Updated tests to verify new method signatures for setting statuses.
x/crosschain/types/keys.go Changed return type of GetProtocolFee from sdk.Uint to math.Uint.
x/crosschain/types/rate_limiter_flags_test.go Updated variable type in test for consistency with new import alias.
x/crosschain/types/status.go Added AbortRefunded method and replaced ChangeStatus with UpdateCctxMessages.
x/crosschain/types/status_test.go Updated tests to reflect changes in status message handling.

Assessment against linked issues

Objective Addressed Explanation
Add new field in CCTX object to contain cross-chain call error (#2913)

Possibly related PRs

Suggested labels

no-changelog, V2_TESTS

Suggested reviewers

  • kingpinXD
  • swift1337
  • lumtis
  • brewmaster012
  • skosito
  • ws4charlie

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.

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.

@fbac fbac requested review from kingpinXD and lumtis October 2, 2024 12:28
@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch from 64217ae to 823c5c9 Compare October 2, 2024 12:36
Copy link

codecov bot commented Oct 2, 2024

Codecov Report

Attention: Patch coverage is 86.36364% with 6 lines in your changes missing coverage. Please review.

Project coverage is 66.40%. Comparing base (1ed1015) to head (cd9818e).
Report is 2 commits behind head on develop.

Files with missing lines Patch % Lines
...hain/keeper/cctx_orchestrator_validate_outbound.go 78.57% 3 Missing ⚠️
x/crosschain/types/status.go 86.66% 1 Missing and 1 partial ⚠️
x/crosschain/types/cctx.go 90.90% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@           Coverage Diff            @@
##           develop    #2952   +/-   ##
========================================
  Coverage    66.39%   66.40%           
========================================
  Files          389      389           
  Lines        21758    21772   +14     
========================================
+ Hits         14447    14458   +11     
- Misses        6584     6586    +2     
- Partials       727      728    +1     
Files with missing lines Coverage Δ
x/crosschain/keeper/cctx_gateway_observers.go 100.00% <100.00%> (ø)
x/crosschain/keeper/cctx_gateway_zevm.go 100.00% <100.00%> (ø)
.../crosschain/keeper/msg_server_migrate_tss_funds.go 87.83% <100.00%> (ø)
x/crosschain/keeper/msg_server_vote_outbound_tx.go 90.10% <100.00%> (ø)
x/crosschain/migrations/v5/migrate.go 83.07% <ø> (ø)
x/crosschain/types/cctx.go 43.47% <90.90%> (-0.28%) ⬇️
x/crosschain/types/status.go 96.22% <86.66%> (-3.78%) ⬇️
...hain/keeper/cctx_orchestrator_validate_outbound.go 72.88% <78.57%> (+0.30%) ⬆️

... and 1 file with indirect coverage changes

@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch 2 times, most recently from d0cd715 to a2077bb Compare October 2, 2024 17:27
@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch from a2077bb to 8758f27 Compare October 2, 2024 20:29
@fbac fbac marked this pull request as ready for review October 3, 2024 06:39
@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch from ee77ab8 to 9d32695 Compare October 3, 2024 06:43
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: 11

🧹 Outside diff range and nitpick comments (37)
docs/openapi/openapi.swagger.yaml (1)

58449-58450: Approve addition of error_message property

The addition of the error_message property is appropriate and aligns with the PR objectives. It provides a dedicated field for error messages, improving clarity in cross-chain call status reporting.

Consider updating relevant API documentation to inform consumers about this new field and its intended use. This will ensure smooth adoption of the enhanced error reporting capability.

e2e/e2etests/test_solana_deposit_refund.go (2)

34-35: Approve change with minor enhancement suggestion.

The modification aligns with the PR objectives by utilizing the new ErrorMessage field for error checking. This change improves error clarity and separation from status messages.

To further enhance the test's robustness, consider the following suggestion:

-	require.Contains(r, cctx.CctxStatus.ErrorMessage, "revert executed")
+	require.Contains(r, cctx.CctxStatus.ErrorMessage, "revert executed", "Error message should indicate a revert")
+	require.Empty(r, cctx.CctxStatus.StatusMessage, "Status message should be empty for a reverted transaction")

This change adds an explanatory message to the assertion and includes a check to ensure the StatusMessage is empty, reinforcing the separation between error and status messages.


Line range hint 13-31: Suggestions for code improvements

  1. Address the TODO comment:
    Consider implementing a shared setup function for the reverter contract deployment to avoid repetition across tests.

  2. Inline the error check for conciseness:

-	reverterAddr, _, _, err := testcontract.DeployReverter(r.ZEVMAuth, r.ZEVMClient)
-	require.NoError(r, err)
+	reverterAddr, _, _, _ := testcontract.DeployReverter(r.ZEVMAuth, r.ZEVMClient)
+	require.NoError(r, err, "Failed to deploy reverter contract")
  1. Standardize logging approach:
    Consider using a consistent logging method throughout the function. If r.Logger.CCTX is a custom method for logging CCTXs, consider creating a similar method for other types of logs to maintain consistency.
x/crosschain/types/keys.go (1)

32-33: Function modification approved with a suggestion.

The changes to the GetProtocolFee function are consistent with the updated import statements, transitioning from sdk.Uint to math.Uint. The function's behavior remains unchanged.

To enhance clarity and maintainability, consider adding a brief comment explaining the purpose of this function and the significance of the ProtocolFee constant.

Here's a suggested improvement:

// GetProtocolFee returns the protocol fee as a math.Uint
// The fee is set to a constant value defined by ProtocolFee
func GetProtocolFee() math.Uint {
	return math.NewUint(ProtocolFee)
}
x/crosschain/keeper/cctx_gateway_observers.go (1)

78-78: Improved error handling structure, but consider further enhancements.

The modification to SetAbort("", err.Error()) aligns with the PR objective of creating a dedicated field for cross-chain call errors. This change separates the error message from other status information, potentially improving error clarity and traceability.

To further enhance this implementation:

  1. Consider using named parameters for improved readability:

    config.CCTX.SetAbort(statusMessage: "", errorMessage: err.Error())
  2. Evaluate if providing an empty string as the status message is the best approach. It might be more informative to include a brief status description:

    config.CCTX.SetAbort(statusMessage: "Outbound initiation failed", errorMessage: err.Error())
  3. To align with the PR objectives more closely, ensure that the SetAbort method is updating the new dedicated error field within the Cctx object.

e2e/e2etests/test_eth_deposit_call.go (1)

90-91: Approve the change with a suggestion for improvement

The updated assertion aligns with the PR objective of improving error handling in cross-chain calls. It provides more flexibility in error message checking, which is beneficial. However, to maintain test precision, consider using a more specific assertion.

Consider using a regular expression for a more precise yet flexible assertion:

require.Regexp(r, `(?i)revert executed.*foo`, cctx.CctxStatus.ErrorMessage)

This assertion:

  1. Is case-insensitive ((?i))
  2. Checks for "revert executed"
  3. Allows for any characters in between
  4. Ensures "foo" is present (assuming this is part of the expected error)

This approach balances flexibility with specificity, ensuring the test remains robust while accommodating minor variations in the error message.

proto/zetachain/zetacore/crosschain/cross_chain_tx.proto (1)

98-98: Approve the addition of the error_message field with a minor suggestion.

The addition of the error_message field in the Status message is a positive change that aligns with the PR objectives. It provides a dedicated field for error messages, improving clarity and separation of concerns.

To enhance documentation and maintainability, consider adding a comment to explain the purpose and usage of this new field.

Consider adding a comment above the field:

+  // Stores specific error messages related to the cross-chain transaction status
   string error_message = 6;
x/crosschain/keeper/msg_server_migrate_tss_funds.go (2)

28-28: Approve error handling update with a minor suggestion.

The transition from errors.Wrap to errorsmod.Wrap is a positive change, aligning with modern error handling practices in the Cosmos SDK ecosystem. This update enhances consistency and potentially provides more detailed error information.

For complete consistency, consider updating the error return in the initiateMigrateTSSFundsCCTX function call (line 70) to use errorsmod.Wrap as well.


Line range hint 141-141: Enhance consistency in error handling.

While the use of errorsmod.Wrap in this instance is appropriate, there are opportunities to improve error handling consistency throughout the function. Consider applying errorsmod.Wrap to other error returns, particularly for custom error types, to provide additional context.

For example, lines 108 and 116 could be updated as follows:

if !isFound {
    return errorsmod.Wrap(types.ErrUnableToGetGasPrice, "median gas values not found")
}

if err != nil {
    return errorsmod.Wrap(err, "failed to create MigrateFundCmdCCTX")
}

This approach would maintain consistency with the error handling pattern established in the MigrateTssFunds function and provide more informative error messages.

x/crosschain/types/status_test.go (2)

151-158: Approval with suggestion: Remove debug print statement.

The test case effectively verifies the behavior of UpdateStatusMessage with an empty message. The new status message format provides clear information about the status transition.

However, the fmt.Printf statement on line 152 appears to be unnecessary for the test and may clutter the output. Consider removing this line to maintain a clean test environment.

 s.UpdateStatusMessage(types.CctxStatus_PendingOutbound, "")
-fmt.Printf("%+v\n", s)
 assert.Equal(t, s.Status, types.CctxStatus_PendingOutbound)

Line range hint 1-176: Summary: Enhanced test coverage for improved status message handling.

The modifications to this test file effectively support the PR objectives of improving error representation in cross-chain calls. The changes include:

  1. Renaming ChangeStatus to UpdateStatusMessage, which better reflects the method's functionality.
  2. Updating test cases to verify the new status message format, which now includes both the old and new status.
  3. Ensuring proper error handling for invalid status transitions.

These changes contribute to a more robust and informative status handling system, which should improve debugging and error tracking in the cross-chain functionality.

To further enhance the test suite, consider adding test cases that specifically verify the new error field functionality mentioned in the PR objectives.

x/crosschain/migrations/v5/migrate.go (2)

Line range hint 91-95: Approve changes with a minor suggestion for clarity.

The modification to use GetAbortedAmount improves the handling of aborted transactions for the Zeta coin type, ensuring accurate accounting even when the outbound transaction is not created. This aligns well with the PR objectives.

To enhance code clarity, consider adding a brief comment explaining the rationale behind using GetAbortedAmount:

// Use GetAbortedAmount to ensure correct refund amount,
// especially when outbound transaction is not created
abortedValue := GetAbortedAmount(cctx)

This comment will help future maintainers understand the purpose of this change quickly.


Line range hint 140-149: Approve new function with a suggestion for improved robustness.

The GetAbortedAmount function effectively calculates the aborted amount for a cross-chain transaction, prioritizing the outbound amount when available. This aligns well with the PR objectives and improves the accuracy of aborted transaction handling.

To enhance robustness, consider adding nil checks before accessing struct fields:

func GetAbortedAmount(cctx types.CrossChainTx) sdkmath.Uint {
	if cctx.OutboundParams != nil && len(cctx.OutboundParams) > 0 && !cctx.GetCurrentOutboundParam().Amount.IsZero() {
		return cctx.GetCurrentOutboundParam().Amount
	}
	if cctx.InboundParams != nil && !cctx.InboundParams.Amount.IsZero() {
		return cctx.InboundParams.Amount
	}
	return sdkmath.ZeroUint()
}

These additional checks will prevent potential panics if the struct fields are unexpectedly nil.

x/crosschain/types/cctx_test.go (5)

153-157: Approve changes with minor improvement suggestion.

The modifications to the TestCrossChainTx_SetAbort function align with the PR objectives. The test now correctly verifies both the StatusMessage and ErrorMessage fields.

To enhance test readability and maintainability, consider extracting the test message into a constant:

const testMessage = "test"

cctx.SetAbort(testMessage, testMessage)
require.Equal(t, types.CctxStatus_Aborted, cctx.CctxStatus.Status)
require.Contains(t, cctx.CctxStatus.StatusMessage, testMessage)
require.Contains(t, cctx.CctxStatus.ErrorMessage, testMessage)

This approach reduces duplication and makes it easier to update the test message in the future if needed.


163-166: Approve changes with consistency improvement suggestion.

The modifications to the TestCrossChainTx_SetPendingRevert function are consistent with the changes made to TestCrossChainTx_SetAbort. The test now correctly verifies both the StatusMessage and ErrorMessage fields.

To maintain consistency and improve test readability, consider applying the same improvement suggested for the TestCrossChainTx_SetAbort function:

const testMessage = "test"

cctx.SetPendingRevert(testMessage, testMessage)
require.Equal(t, types.CctxStatus_PendingRevert, cctx.CctxStatus.Status)
require.Contains(t, cctx.CctxStatus.StatusMessage, testMessage)
require.Contains(t, cctx.CctxStatus.ErrorMessage, testMessage)

This change will enhance consistency across test functions and improve maintainability.


175-175: Approve change with minor improvement suggestion.

The addition of the assertion to verify that the ErrorMessage does not contain the test string is a valuable improvement. It ensures that the SetPendingOutbound method does not inadvertently set an error message.

To maintain consistency with other test functions and improve readability, consider extracting the test message into a constant:

const testMessage = "test"

cctx.SetPendingOutbound(testMessage)
require.Equal(t, types.CctxStatus_PendingOutbound, cctx.CctxStatus.Status)
require.Contains(t, cctx.CctxStatus.StatusMessage, testMessage)
require.NotContains(t, cctx.CctxStatus.ErrorMessage, testMessage)

This change will align the test structure with other functions in the file and improve overall consistency.


184-184: Approve change with consistency improvement suggestion.

The addition of the assertion to verify that the ErrorMessage does not contain the test string is consistent with the changes made to TestCrossChainTx_SetPendingOutbound. This improvement ensures that the SetOutboundMined method does not inadvertently set an error message.

To maintain consistency across test functions and improve readability, consider applying the same improvement suggested for the TestCrossChainTx_SetPendingOutbound function:

const testMessage = "test"

cctx.SetOutboundMined(testMessage)
require.Equal(t, types.CctxStatus_OutboundMined, cctx.CctxStatus.Status)
require.Contains(t, cctx.CctxStatus.StatusMessage, testMessage)
require.NotContains(t, cctx.CctxStatus.ErrorMessage, testMessage)

This change will enhance consistency across test functions and improve overall maintainability.


190-193: Approve changes with consistency improvement suggestion.

The modifications to the TestCrossChainTx_SetReverted function are consistent with the changes made to TestCrossChainTx_SetAbort and TestCrossChainTx_SetPendingRevert. The test now correctly verifies both the StatusMessage and ErrorMessage fields.

To maintain consistency across all test functions and improve readability, consider applying the same improvement suggested for the other functions:

const testMessage = "test"

cctx.SetReverted(testMessage, testMessage)
require.Equal(t, types.CctxStatus_Reverted, cctx.CctxStatus.Status)
require.Contains(t, cctx.CctxStatus.StatusMessage, testMessage)
require.Contains(t, cctx.CctxStatus.ErrorMessage, testMessage)

This change will enhance consistency across all test functions, improve maintainability, and reduce duplication.

x/crosschain/types/cctx.go (5)

174-175: Approve changes with minor suggestion for consistency

The modifications to the SetAbort method align with the PR objectives by improving error handling in cross-chain calls. The addition of separate status and error message parameters enhances the granularity of status updates.

To maintain consistency across the codebase, consider updating the method signature to use more descriptive parameter names:

func (m CrossChainTx) SetAbort(statusMessage, errorMessage string) {
    m.CctxStatus.UpdateCctxMessages(CctxStatus_Aborted, true, statusMessage, errorMessage)
}

This change would improve readability and make the purpose of each parameter more explicit.


179-180: Approve changes with minor suggestion for consistency

The modifications to the SetPendingRevert method are consistent with the changes made to SetAbort and align with the PR objectives. The addition of separate status and error message parameters enhances the granularity of status updates.

For consistency with the previous suggestion, consider updating the method signature:

func (m CrossChainTx) SetPendingRevert(statusMessage, errorMessage string) {
    m.CctxStatus.UpdateCctxMessages(CctxStatus_PendingRevert, true, statusMessage, errorMessage)
}

This change would improve readability and maintain consistency across the codebase.


184-185: Approve changes with minor suggestion for consistency

The modifications to the SetPendingOutbound method are appropriate, as this status doesn't represent an error state. The removal of the error message parameter simplifies the method while still providing detailed status updates.

For consistency with previous suggestions and to improve readability, consider updating the method signature:

func (m CrossChainTx) SetPendingOutbound(statusMessage string) {
    m.CctxStatus.UpdateCctxMessages(CctxStatus_PendingOutbound, false, statusMessage, "")
}

This change maintains the simplified signature while improving clarity.


189-190: Approve changes with minor suggestion for consistency

The modifications to the SetOutboundMined method are appropriate and consistent with the changes made to SetPendingOutbound. The removal of the error message parameter simplifies the method for this non-error state while still providing detailed status updates.

For consistency with previous suggestions and to improve readability, consider updating the method signature:

func (m CrossChainTx) SetOutboundMined(statusMessage string) {
    m.CctxStatus.UpdateCctxMessages(CctxStatus_OutboundMined, false, statusMessage, "")
}

This change maintains the simplified signature while improving clarity.


194-195: Approve changes with minor suggestion for consistency

The modifications to the SetReverted method are consistent with the changes made to SetAbort and SetPendingRevert, aligning with the PR objectives. The addition of separate status and error message parameters enhances the granularity of status updates.

For consistency with previous suggestions and to improve readability, consider updating the method signature:

func (m CrossChainTx) SetReverted(statusMessage, errorMessage string) {
    m.CctxStatus.UpdateCctxMessages(CctxStatus_Reverted, true, statusMessage, errorMessage)
}

This change would improve readability and maintain consistency across the codebase.

x/crosschain/types/rate_limiter_flags_test.go (1)

265-265: Type change approved with a suggestion for improvement.

The modification of expectedValue type from sdkmath.Int to math.Int is consistent with the import alias change and does not affect the test logic.

To enhance code readability, consider using type aliases for commonly used types. This can make the code more maintainable and easier to update in the future.

Consider adding a type alias at the beginning of the file:

type Int = math.Int

Then, update the expectedValue type:

expectedValue Int

This approach can simplify future updates and improve code consistency.

x/crosschain/keeper/msg_server_vote_inbound_tx_test.go (2)

Line range hint 268-305: Well-structured test for non-finalized ballot scenario.

The test case effectively verifies the behavior when a ballot does not reach finalization due to insufficient votes. This is a crucial edge case to cover.

Consider adding an assertion to verify the exact number of votes received, ensuring that it matches the number of validators who voted. This would provide an additional layer of validation to the test case.


Line range hint 268-305: Appropriate renaming and update of status change test.

The renaming of TestStatus_ChangeStatus to TestStatus_UpdateCctxStatus enhances clarity. The update to use UpdateCctxMessages aligns well with the changes in the main codebase.

To further improve this test:

  1. Consider adding a test case for the scenario where both status_message and error_message are updated simultaneously.
  2. Verify that the LastUpdateTimestamp is updated correctly in each test case.

These additions would provide more comprehensive coverage of the UpdateCctxMessages functionality.

x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (1)

Line range hint 125-140: Enhance error message consistency and informativeness

The modifications to error messages in the SetAbort calls improve specificity. However, there's an opportunity to further enhance consistency and informativeness across these error messages.

Consider the following improvements:

  1. For line 125:
-cctx.SetAbort("", "outbound failed, cmd cctx reverted")
+cctx.SetAbort("CMD CCTX Revert", "Outbound transaction failed for command CCTX")
  1. For line 140:
-cctx.SetAbort("", "outbound failed for non-ZETA cctx")
+cctx.SetAbort("Non-ZETA CCTX Failure", "Outbound transaction failed for non-ZETA CCTX")

These changes provide a consistent structure (summary in the first argument, detailed message in the second) and offer more informative error descriptions.

x/crosschain/keeper/cctx_test.go (2)

172-174: Approve changes with a minor suggestion for improvement

The addition of error checking for cross-chain transactions is a valuable enhancement. It aligns well with the PR objectives to improve error handling and representation.

To further improve clarity and maintainability, consider extracting the error checking logic into a separate helper function. This would make the test more readable and easier to maintain, especially if similar checks are needed in other test cases.

Consider refactoring the error checking logic as follows:

func assertNoCrossChainTxError(t *testing.T, keeper *keeper.Keeper, ctx sdk.Context, index string) {
    err, found := keeper.GetCrossChainTxError(ctx, index)
    require.True(t, found)
    require.Equal(t, "", err)
}

// Usage in the test
assertNoCrossChainTxError(t, keeper, ctx, s.Index)

This refactoring would improve the test's readability and make it easier to reuse the error checking logic in other test cases if needed.


Line range hint 421-435: Approve new test case with a suggestion for consistency

The addition of this test case is commendable as it enhances the coverage of error handling in cross-chain transactions. It effectively tests the scenario where the amount doesn't match the value received, which is crucial for maintaining the integrity of cross-chain operations.

To maintain consistency with other test cases and improve readability, consider using a descriptive name for the test case and adding a brief comment explaining the purpose of the test.

Consider refactoring the test case as follows:

t.Run("should return error when amount doesn't match value received", func(t *testing.T) {
    // Test case to verify that AddOutbound returns an error when the amount
    // doesn't match the value received in a successful observation
    _, ctx, _, _ := keepertest.CrosschainKeeper(t)

    cctx := sample.CrossChainTx(t, "test")
    hash := sample.Hash().String()

    err := cctx.AddOutbound(ctx, types.MsgVoteOutbound{
        ValueReceived:                     sdkmath.NewUint(100),
        ObservedOutboundHash:              hash,
        ObservedOutboundBlockHeight:       10,
        ObservedOutboundGasUsed:           100,
        ObservedOutboundEffectiveGasPrice: sdkmath.NewInt(100),
        ObservedOutboundEffectiveGasLimit: 20,
    }, observertypes.BallotStatus_BallotFinalized_SuccessObservation)
    require.ErrorIs(t, err, sdkerrors.ErrInvalidRequest)
})

This refactoring improves the test's readability and makes its purpose clearer, which is beneficial for maintaining and understanding the test suite in the long run.

x/crosschain/keeper/initiate_outbound_test.go (2)

287-287: Assertion updates approved with suggestion for improvement.

The changes from StatusMessage to ErrorMessage consistently apply the new error handling approach across various test cases, which is commendable. However, the repetitive nature of these changes suggests an opportunity for optimization.

Consider introducing a helper function to encapsulate the error message assertion logic. This would not only reduce code duplication but also make future updates more manageable.

Example:

func assertErrorMessage(t *testing.T, cctx *types.CrossChainTx, expectedError string) {
    t.Helper()
    require.Contains(t, cctx.CctxStatus.ErrorMessage, expectedError)
}

This helper function can then be used across all test cases, simplifying the assertions and making the tests more maintainable.

Also applies to: 324-324, 364-366, 430-430, 459-459


Line range hint 1-479: Overall assessment: Changes approved with suggestions for improvement.

The modifications in this file consistently update the error message assertions from StatusMessage to ErrorMessage, aligning with the PR objective of introducing a dedicated error field. This change enhances the clarity of error handling in the codebase.

To further improve the test suite:

  1. Consider introducing helper functions for common assertions to reduce code duplication and enhance maintainability.
  2. Evaluate the possibility of using table-driven tests for scenarios with similar structures but different inputs and expected outputs. This could significantly reduce the amount of boilerplate code and make it easier to add new test cases in the future.

These improvements would make the test suite more robust, easier to maintain, and more aligned with Go best practices for testing.

testutil/sample/crosschain.go (1)

194-194: Approve the addition of ErrorMessage field with a suggestion for improvement.

The addition of the ErrorMessage field aligns well with the PR objectives to create a dedicated field for cross-chain call errors. This change enhances the Status struct by allowing for more detailed error reporting in cross-chain calls.

To improve clarity and maintainability, consider adding a comment explaining the purpose of this field:

 CreatedTimestamp:    createdAt,
 LastUpdateTimestamp: createdAt,
+ErrorMessage:        String(), // Stores specific error messages for cross-chain calls

This comment will help other developers understand the intended use of this field in the context of cross-chain transactions.

changelog.md (3)

Line range hint 48-114: Significant improvements with room for further enhancements.

Version v12.1.0 introduces several noteworthy changes:

  1. Modified emission distribution to use fixed block rewards, which could improve predictability and fairness in the system.
  2. Enhanced gas handling, including exemptions for system transactions from minimum gas price checks.
  3. Improved error handling and chain parameter management.
  4. Added support for lower gas limits in certain voting scenarios.
  5. Refactored various components to optimize performance and improve code organization.

These changes demonstrate a commitment to system improvement and optimization. However, there are areas where further enhancements could be considered:

  1. The changes to emission distribution and gas handling are significant. Consider adding more comprehensive tests to ensure these changes don't introduce unexpected behaviors.
  2. With the refactoring of zetaclient into subpackages, ensure that the documentation is updated to reflect the new structure.
  3. The addition of EVM fee calculation to TSS migration of EVM chains is a good step. Consider extending this to other chain types if applicable.

To further improve the system, consider implementing a more robust logging and monitoring system to track the effects of these changes in production, particularly for the emission distribution and gas handling modifications.


Line range hint 116-271: Major version update with significant breaking changes and enhancements.

Version v12.0.0 introduces substantial changes to the system:

Breaking Changes:

  1. Relocation of TSS and chain validation queries from crosschain to observer module.
  2. Unification of observer sets across all chains.
  3. Merging of observer params and core params into chain params.
  4. Changes to the GetTssAddress query, now requiring Bitcoin chain ID.

These breaking changes will require updates to any systems interacting with the affected queries and parameters.

Key New Features:

  1. Support for stateful precompiled contracts.
  2. Addition of a common importable RPC package.
  3. Implementation of staking and bank precompiled contracts.
  4. Support for multiple Bitcoin chains in zetaclient.

Important Fixes:

  1. Improvements to outbound transaction confirmation and inclusion.
  2. Enhanced error handling and validation in various components.
  3. Fixes for issues related to nonce management and block header processing.

The refactoring efforts, including the reorganization of the zetaclient into subpackages and the movement of various components between modules, appear to improve code organization and efficiency.

Given the significant changes in this version:

  1. Develop and provide comprehensive migration guides for users of the affected queries and parameters.
  2. Update all relevant documentation to reflect the new structure and functionality.
  3. Consider implementing a deprecation period for the old query paths to allow for a smoother transition.
  4. Enhance monitoring and alerting systems to track the impact of these changes in production environments.

Discrepancy Detected Between Changelog and Codebase Implementations

Upon verification, it appears that the implementations for HSM capability and Observer Update functionality referenced in the changelog are absent in the current codebase. This inconsistency may lead to misunderstandings regarding the actual features included in version v11.0.0.

Recommended Actions:

  • Update the Changelog: Ensure that all listed features and fixes accurately reflect the changes implemented in the codebase.
  • Implement Missing Features: If HSM capability and Observer Update functionalities are intended for this release, prioritize their development and integration.
  • Conduct Comprehensive Verification: Re-run verification scripts after implementing the necessary features to confirm their presence and functionality.
🔗 Analysis chain

Line range hint 273-308: Security enhancements and system improvements with room for further testing.

Version v11.0.0 introduces several important changes:

Key Features:

  1. HSM capability for zetaclient hot key, enhancing security.
  2. New functionality for updating observers, improving system management.
  3. Addition of a thread in zetaclient to check zeta supply across all connected chains in every block.

Important Fixes:

  1. Improved handling of contract redeployment for gas and asset token contracts.
  2. Enhanced transaction processing, including fixes for inbound tx digest and Bitcoin-related issues.
  3. Improved logging and speed optimization for EVM outbound transaction inclusion.

The refactoring efforts, while limited, include consolidation of node builds and updates to contract bytecode management.

To ensure the robustness of these changes, consider the following:

  1. Implement comprehensive testing for the new HSM capability, especially under various network conditions and potential attack scenarios.
  2. Verify the performance impact of the new zeta supply check thread, particularly on networks with a large number of connected chains.
  3. Conduct thorough testing of the observer update functionality, including edge cases such as multiple simultaneous updates.

To assist with verification, you can run the following script:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation of HSM capability and new observer management features

# Test: Search for HSM-related code. Expect: Implementation details of HSM capability.
rg --type go 'HSM|Hardware Security Module'

# Test: Search for observer update functionality. Expect: Implementation of observer update logic.
rg --type go 'UpdateObserver|ObserverUpdate'

# Test: Search for zeta supply check implementation. Expect: Thread implementation for supply checks.
rg --type go 'CheckZetaSupply|SupplyCheck'

Length of output: 29324

x/crosschain/types/status.go (2)

18-38: Handle Potential Race Conditions

If this code is accessed concurrently, updating the Status and StatusMessage fields without proper synchronization may lead to race conditions. Consider adding appropriate locking mechanisms or making use of concurrency-safe structures.


12-16: Document the UpdateCctxMessages Method Parameters

To improve code maintainability and developer experience, add comments that describe the parameters of the UpdateCctxMessages method. This is especially helpful for complex functions or those that will be used by other developers.

For example:

// UpdateCctxMessages updates the status and error messages of the cross-chain transaction context (Cctx).
// Parameters:
// - newStatus: The new status to transition to.
// - isError: Flag indicating whether an error occurred.
// - statusMsg: Optional custom status message.
// - errorMsg: Optional custom error message.
func (m *Status) UpdateCctxMessages(newStatus CctxStatus, isError bool, statusMsg, errorMsg string) {
    // method implementation
}
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between f0ed61d and 9d32695.

⛔ Files ignored due to path filters (2)
  • typescript/zetachain/zetacore/crosschain/cross_chain_tx_pb.d.ts is excluded by !**/*_pb.d.ts
  • x/crosschain/types/cross_chain_tx.pb.go is excluded by !**/*.pb.go, !**/*.pb.go
📒 Files selected for processing (22)
  • changelog.md (1 hunks)
  • docs/openapi/openapi.swagger.yaml (1 hunks)
  • e2e/e2etests/test_eth_deposit_call.go (1 hunks)
  • e2e/e2etests/test_solana_deposit_refund.go (1 hunks)
  • proto/zetachain/zetacore/crosschain/cross_chain_tx.proto (2 hunks)
  • testutil/sample/crosschain.go (1 hunks)
  • x/crosschain/keeper/cctx.go (1 hunks)
  • x/crosschain/keeper/cctx_gateway_observers.go (1 hunks)
  • x/crosschain/keeper/cctx_gateway_zevm.go (1 hunks)
  • x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (10 hunks)
  • x/crosschain/keeper/cctx_test.go (1 hunks)
  • x/crosschain/keeper/initiate_outbound_test.go (10 hunks)
  • x/crosschain/keeper/msg_server_migrate_tss_funds.go (1 hunks)
  • x/crosschain/keeper/msg_server_vote_inbound_tx_test.go (2 hunks)
  • x/crosschain/keeper/msg_server_vote_outbound_tx.go (1 hunks)
  • x/crosschain/migrations/v5/migrate.go (1 hunks)
  • x/crosschain/types/cctx.go (2 hunks)
  • x/crosschain/types/cctx_test.go (3 hunks)
  • x/crosschain/types/keys.go (2 hunks)
  • x/crosschain/types/rate_limiter_flags_test.go (1 hunks)
  • x/crosschain/types/status.go (1 hunks)
  • x/crosschain/types/status_test.go (1 hunks)
🧰 Additional context used
📓 Path-based instructions (20)
e2e/e2etests/test_eth_deposit_call.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

e2e/e2etests/test_solana_deposit_refund.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

proto/zetachain/zetacore/crosschain/cross_chain_tx.proto (1)

Pattern **/*.proto: Review the Protobuf definitions, point out issues relative to compatibility, and expressiveness.

testutil/sample/crosschain.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx_gateway_observers.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx_gateway_zevm.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx_orchestrator_validate_outbound.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/cctx_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/initiate_outbound_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/msg_server_migrate_tss_funds.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/msg_server_vote_inbound_tx_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/keeper/msg_server_vote_outbound_tx.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/migrations/v5/migrate.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/cctx.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/cctx_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/keys.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/rate_limiter_flags_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/status.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

x/crosschain/types/status_test.go (1)

Pattern **/*.go: Review the Go code, point out issues relative to principles of clean code, expressiveness, and performance.

📓 Learnings (1)
x/crosschain/keeper/msg_server_vote_outbound_tx.go (1)
Learnt from: kingpinXD
PR: zeta-chain/node#2615
File: x/crosschain/keeper/msg_server_vote_outbound_tx_test.go:472-472
Timestamp: 2024-08-01T18:08:13.681Z
Learning: The `SaveFailedOutbound` function in `x/crosschain/keeper/msg_server_vote_outbound_tx.go` requires a string argument for the error message.
🪛 GitHub Check: codecov/patch
x/crosschain/keeper/cctx.go

[warning] 93-93: x/crosschain/keeper/cctx.go#L93
Added line #L93 was not covered by tests

x/crosschain/keeper/cctx_orchestrator_validate_outbound.go

[warning] 339-339: x/crosschain/keeper/cctx_orchestrator_validate_outbound.go#L339
Added line #L339 was not covered by tests


[warning] 357-357: x/crosschain/keeper/cctx_orchestrator_validate_outbound.go#L357
Added line #L357 was not covered by tests


[warning] 370-370: x/crosschain/keeper/cctx_orchestrator_validate_outbound.go#L370
Added line #L370 was not covered by tests

x/crosschain/types/cctx.go

[warning] 262-262: x/crosschain/types/cctx.go#L262
Added line #L262 was not covered by tests

x/crosschain/types/status.go

[warning] 48-48: x/crosschain/types/status.go#L48
Added line #L48 was not covered by tests

🔇 Additional comments (22)
x/crosschain/keeper/cctx_gateway_zevm.go (1)

31-31: 🛠️ Refactor suggestion

Consider providing a meaningful status message in SetAbort call

The modification to SetAbort aligns with the PR objectives of improving error handling. However, passing an empty string as the first parameter may not be optimal.

  1. Ensure that the SetAbort method signature has been updated to accept two parameters.
  2. Consider providing a meaningful status message instead of an empty string. For example:
    config.CCTX.SetAbort("EVM Deposit Failed", err.Error())
  3. Verify that this change is consistent with other SetAbort calls in the codebase.

To ensure consistency, let's check other SetAbort calls:

If the first parameter is indeed intended for a status message, consider extracting it to a constant or variable for better maintainability:

const EVMDepositFailedStatus = "EVM Deposit Failed"
// ...
config.CCTX.SetAbort(EVMDepositFailedStatus, err.Error())

This approach improves code readability and allows for easier updates to the status message in the future.

✅ Verification successful

Provision of an empty status message in SetAbort is consistent across the codebase

Upon reviewing other instances of SetAbort calls, it is evident that passing an empty string as the statusMsg is a common and accepted practice within the codebase.

  • Consistency Confirmed: Multiple files utilize SetAbort("", err.Error()), aligning with the reviewed change.

No immediate issues are identified with the current implementation. However, if specific contexts would benefit from more descriptive status messages, consider providing meaningful messages where appropriate.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for other SetAbort calls in the codebase
rg --type go 'SetAbort\(' -A 2

Length of output: 2890

e2e/e2etests/test_solana_deposit_refund.go (1)

Line range hint 1-35: Summary of file review

The TestSolanaDepositAndCallRefund function effectively tests the deposit and refund scenario for Solana in an end-to-end context. The recent changes align well with the PR objectives by utilizing the new ErrorMessage field for error checking.

Key points:

  1. The function structure follows a clear setup-action-verification pattern.
  2. The change improves error handling clarity by separating error messages from status messages.
  3. Minor optimizations and standardizations could further enhance the code quality.

Overall, the file demonstrates good testing practices for cross-chain functionality.

x/crosschain/types/keys.go (2)

6-6: Import change approved.

The replacement of the sdk package import with math from cosmossdk.io/math is appropriate and aligns with the subsequent changes in the GetProtocolFee function. This modification contributes to a more focused and specific use of dependencies.


Line range hint 1-114: Summary of changes and their impact.

The modifications in this file are focused and consistent:

  1. The import statements have been updated to use math from cosmossdk.io/math instead of the sdk package.
  2. The GetProtocolFee function has been adjusted to return math.Uint instead of sdk.Uint.

These changes appear to be part of a larger effort to transition from the cosmos-sdk types to a more specific math package. The alterations are minimal and do not affect the overall functionality of the module. The consistency in these changes suggests a well-planned refactoring process.

To ensure the changes are applied consistently across the codebase, it would be prudent to verify that all usages of GetProtocolFee() are updated to handle the new return type correctly.

Run the following script to check for any remaining usages of sdk.Uint that might need updating:

✅ Verification successful

Verification Successful: No Remaining sdk.Uint Usages Found

The refactoring in x/crosschain/types/keys.go has been thoroughly verified:

  • No remaining instances of sdk.Uint are present in the codebase.
  • All usages of GetProtocolFee() have been correctly updated to handle the new math.Uint return type.

These changes are consistent and maintain the intended functionality of the module without introducing any issues.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for remaining usages of sdk.Uint that might need updating

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

# Test: Search for GetProtocolFee() usages to ensure they're used correctly with the new return type
rg --type go 'GetProtocolFee\(\)'

Length of output: 1104

proto/zetachain/zetacore/crosschain/cross_chain_tx.proto (1)

20-20: Acknowledge the formatting improvement.

The reformatting of the comment for the Aborted status enhances readability. This change, while minor, contributes to the overall code quality and consistency.

x/crosschain/types/status_test.go (2)

143-145: Approval: Enhanced status message clarity.

The modification to use UpdateStatusMessage and the new status message format improves the clarity of the test case. The inclusion of both the old and new status in the message provides more comprehensive information about the transition.


164-173: Approval: Improved error handling and message format.

The modifications to this test case effectively verify the behavior of UpdateStatusMessage during an invalid status transition. The new error message format is more concise and informative, clearly indicating the attempted transition that failed.

The consistent use of string formatting across test cases enhances readability and maintainability of the test suite.

x/crosschain/keeper/msg_server_vote_outbound_tx.go (2)

Line range hint 1-187: Enhancements to error handling and logging are commendable.

The modifications to the VoteOutbound function demonstrate an improved approach to error handling and logging. The core logic remains intact while providing more comprehensive error context. This change aligns with best practices for robust system design.


188-188: Clarification needed on SetAbort parameter change.

The modification to cctx.SetAbort("", errMessage) introduces an empty string as the first parameter. This change warrants explanation:

  1. What is the purpose of the empty string parameter?
  2. How does this align with the PR objective of creating a dedicated error field?

Consider enhancing clarity by using named parameters or a more descriptive method signature. For example:

cctx.SetAbort(statusMessage: "", errorMessage: errMessage)

or

cctx.SetAbortWithError(errorMessage: errMessage)

This would make the intention clearer and improve code readability.

To ensure consistency across the codebase, let's check for other occurrences of SetAbort:

x/crosschain/types/cctx.go (1)

262-262: Approve changes and address test coverage

The initialization of the ErrorMessage field to an empty string in the NewCCTX function is a positive change. It ensures that this field is explicitly set upon creation of a new CrossChainTx instance, aligning with the PR objectives to improve error handling in cross-chain calls.

However, the static analysis tool has flagged that this new line is not covered by tests. To ensure the robustness of the codebase, consider adding or updating unit tests to cover this initialization.

To verify the test coverage for this change, you can run the following command:

This script will help identify if there are existing tests for the NewCCTX function and provide information about its coverage. Based on the results, you may need to add or update tests to cover the new ErrorMessage field initialization.

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 262-262: x/crosschain/types/cctx.go#L262
Added line #L262 was not covered by tests

x/crosschain/types/rate_limiter_flags_test.go (1)

Line range hint 1-13: Import alias change approved.

The modification of the import alias from sdkmath to math for the cosmossdk.io/math package is consistent and does not impact the functionality of the tests.

x/crosschain/keeper/msg_server_vote_inbound_tx_test.go (1)

Line range hint 268-305: Commendable addition of error handling test case.

The new test case effectively verifies the error handling when voting on an inbound ballot fails. The use of a mock observer to simulate the failure scenario is a robust approach to unit testing.

x/crosschain/keeper/cctx_test.go (1)

Line range hint 1-435: Summary of changes

The modifications to this test file effectively enhance the error handling and test coverage for cross-chain transactions. The additions align well with the PR objectives to improve error representation and handling in cross-chain calls.

Key improvements:

  1. Addition of error checking in the TestCCTXs function.
  2. New test case in TestCrossChainTx_AddOutbound to verify behavior when amounts don't match.

These changes contribute to a more robust and well-tested codebase. The suggestions provided for minor refactoring aim to further improve code readability and maintainability.

x/crosschain/keeper/initiate_outbound_test.go (5)

79-80: Assertion update approved.

The change from StatusMessage to ErrorMessage correctly aligns with the new error handling approach introduced in this PR.


114-116: Assertion update approved.

The modification from StatusMessage to ErrorMessage is consistent with the new error handling approach and maintains test integrity.


154-156: Assertion update approved.

The change from StatusMessage to ErrorMessage maintains consistency with the new error handling mechanism introduced in this PR.


197-199: Assertion update approved.

The modification from StatusMessage to ErrorMessage consistently applies the new error handling approach across test cases.


242-244: Assertion update approved.

The change from StatusMessage to ErrorMessage maintains consistency with the new error handling mechanism across different test scenarios.

changelog.md (2)

Line range hint 28-46: Commendable fixes and improvements.

The changelog for version v12.2.4 presents a series of important fixes that enhance the system's stability and reliability:

  1. Improved external chain height validation.
  2. Enhanced gas price management for EIP1559.
  3. Refined authorization for WhitelistERC20.
  4. Improved handling of pending outbound transactions.
  5. Optimized Bitcoin-related operations, including keysign scheduling and fee calculations.
  6. Added robustness for handling new transaction types and potential issues on test networks.

These changes demonstrate a commitment to addressing critical issues and optimizing performance. The removal of the standalone network in the chore item also indicates a move towards a more streamlined testing environment.


Line range hint 310-393: Comprehensive enhancements with focus on system reliability and functionality.

Version v10.1.2 introduces significant improvements:

Key Features:

  1. External stress testing capabilities, enhancing system robustness.
  2. Liquidity cap setting for ZRC20, providing better control over token economics.
  3. Bitcoin block header and merkle proof functionality, improving cross-chain verification.
  4. TSS funds migration capability, enhancing security and management of threshold signatures.
  5. Addition of a zetaclient thread for zeta supply checks, improving monitoring.

Important Fixes:

  1. Improvements to upgrade processes and release testing.
  2. Enhanced authorization checks and blame index updates.
  3. Refinements to gas limit handling and stability pool management.
  4. Various improvements to CLI commands and queries.

The refactoring efforts focus on optimizing cross-chain calls and mempool management.

To further enhance the system's reliability and performance:

  1. Conduct comprehensive stress tests using the new external stress testing capabilities, particularly focusing on high-load scenarios and edge cases.
  2. Implement thorough testing of the new liquidity cap feature for ZRC20, ensuring it behaves correctly under various market conditions.
  3. Verify the correctness and performance of the Bitcoin block header and merkle proof functionality across different network conditions.
  4. Test the TSS funds migration capability extensively, including scenarios with partial node failures or network partitions.

To assist with verification, you can run the following script:

#!/bin/bash
# Description: Verify the implementation of key features and fixes

# Test: Search for stress testing implementation. Expect: Code related to stress test setup and execution.
rg --type go 'StressTest|LoadTest'

# Test: Search for ZRC20 liquidity cap functionality. Expect: Implementation of liquidity cap setting and checking.
rg --type go 'LiquidityCap|SetCap'

# Test: Search for Bitcoin block header and merkle proof implementation. Expect: Code handling Bitcoin headers and proofs.
rg --type go 'BitcoinHeader|MerkleProof'

# Test: Search for TSS funds migration capability. Expect: Implementation of TSS migration logic.
rg --type go 'TSSMigration|MigrateFunds'

# Test: Search for zeta supply check implementation. Expect: Thread implementation for supply checks in zetaclient.
rg --type go 'CheckZetaSupply|SupplyCheck'
x/crosschain/types/status.go (2)

48-48: Increase Test Coverage for Line 48

The static analysis indicates that line 48 is not covered by tests. To ensure robustness, add a unit test that covers the scenario where errorMsg is an empty string, and isError is true. This will confirm that the default message "unknown error" is correctly assigned.

Would you like assistance in creating the unit test to improve coverage?

🧰 Tools
🪛 GitHub Check: codecov/patch

[warning] 48-48: x/crosschain/types/status.go#L48
Added line #L48 was not covered by tests


18-38: Validate Status Transition Messages for Accuracy

In the UpdateStatusMessage method, when a status transition fails, the StatusMessage is updated to indicate the failure, and the Status is set to CctxStatus_Aborted. Ensure that this behavior aligns with the system's requirements for handling invalid transitions. It might be unexpected for a failed transition attempt to result in an aborted status without explicit handling.

Consider reviewing the status transition logic to confirm that automatically aborting on invalid transitions is the desired behavior.

x/crosschain/keeper/cctx.go Outdated Show resolved Hide resolved
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Outdated Show resolved Hide resolved
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Outdated Show resolved Hide resolved
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Outdated Show resolved Hide resolved
x/crosschain/keeper/cctx_orchestrator_validate_outbound.go Outdated Show resolved Hide resolved
x/crosschain/types/status.go Outdated Show resolved Hide resolved
x/crosschain/types/status.go Show resolved Hide resolved
x/crosschain/types/status.go Outdated Show resolved Hide resolved
@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch from 9d32695 to 5cd63aa Compare October 3, 2024 07:24
@fbac fbac force-pushed the GH2913/add-error-field-to-cctx branch from 5cd63aa to 4d7b1aa Compare October 3, 2024 07:53
cctx.SetAbort(fmt.Sprintf("%s : %s", depositErr, err.Error()))
cctx.SetAbort(
"Aborted because an error was raised while trying to revert cctx",
fmt.Sprintf("Deposit error: %s, Processing error: %s", depositErr, err.Error()))
Copy link
Contributor

Choose a reason for hiding this comment

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

Can we declare Deposit Error and Processing Error ( the strings ) as constants and then use them when ever setting the error message

Also, Something more generic, like Outbound Error and Revert Outbound Error, would be helpful.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

We just have a couple logs using deposit error, so I'll manually add them.

@@ -28,7 +28,7 @@ func (c CCTXGatewayZEVM) InitiateOutbound(

if err != nil && !isContractReverted {
// exceptional case; internal error; should abort CCTX
config.CCTX.SetAbort(err.Error())
config.CCTX.SetAbort("Aborted while trying to handle EVM deposit", err.Error())
Copy link
Contributor

Choose a reason for hiding this comment

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

Related topmy other commend , if we declare constants , we can use that in this error message also;
If using the terminology you already have, this would be

config.CCTX.SetAbort("Aborted while trying to handle EVM deposit", fmt.sprintf("Deposit Error :%s",err.Error))

Copy link
Contributor

@kingpinXD kingpinXD left a comment

Choose a reason for hiding this comment

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

Can we add a test to simulate this call or something similar
#2913 (comment)

It would be helpful to visualise what the updated message looks like

@@ -25,6 +25,7 @@
* [2826](https://github.com/zeta-chain/node/pull/2826) - remove unused code from emissions module and add new parameter for fixed block reward amount
* [2890](https://github.com/zeta-chain/node/pull/2890) - refactor `MsgUpdateChainInfo` to accept a single chain, and add `MsgRemoveChainInfo` to remove a chain
* [2899](https://github.com/zeta-chain/node/pull/2899) - remove btc deposit fee v1 and improve unit tests
* [2952](https://github.com/zeta-chain/node/pull/2952) - add error_message to cctx.status
Copy link
Member

Choose a reason for hiding this comment

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

PR title has feat type but added in refactoring here

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Modifying the PR title to refactor.

Comment on lines 97 to 98
string status_message = 2;
string error_message = 6;
Copy link
Member

Choose a reason for hiding this comment

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

Can we add comments to differentiate both?

@@ -81,6 +81,23 @@ func (k Keeper) GetCrossChainTx(ctx sdk.Context, index string) (val types.CrossC
return val, true
}

// GetCrossChainTxError returns the error message for a given cctx index.
func (k Keeper) GetCrossChainTxError(ctx sdk.Context, index string) (errMsg string, found bool) {
Copy link
Member

Choose a reason for hiding this comment

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

Why implementing this function? It is not used and I don't think we will need it as you can fetch the object and read the error message from it.

In general we should keep message that interact with the store as minimal as possible for simplicity

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Deleted.

@@ -75,7 +75,7 @@ func (c CCTXGatewayObservers) InitiateOutbound(
}()
if err != nil {
// do not commit anything here as the CCTX should be aborted
config.CCTX.SetAbort(err.Error())
config.CCTX.SetAbort("Aborted due to an internal error", err.Error())
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
config.CCTX.SetAbort("Aborted due to an internal error", err.Error())
config.CCTX.SetAbort("aborted due to an internal error", err.Error())

I think we can keep Go error standard that is to keep all lowercase

@@ -28,7 +28,7 @@ func (c CCTXGatewayZEVM) InitiateOutbound(

if err != nil && !isContractReverted {
// exceptional case; internal error; should abort CCTX
config.CCTX.SetAbort(err.Error())
config.CCTX.SetAbort("Aborted while trying to handle EVM deposit", err.Error())
Copy link
Member

Choose a reason for hiding this comment

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

We should add more details:
"error during deposit that is not smart contract revert"

@@ -53,7 +53,9 @@ func (k Keeper) ValidateOutboundZEVM(
cctx.InboundParams.Amount,
)
if err != nil {
cctx.SetAbort(fmt.Sprintf("%s : %s", depositErr, err.Error()))
cctx.SetAbort(
"Aborted because an error was raised while trying to revert cctx",
Copy link
Member

Choose a reason for hiding this comment

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

"because reverts failed" would be simpler

@fbac fbac changed the title feat: add error field in cctx refactor: add error field in cctx Oct 4, 2024
@fbac fbac requested review from lumtis and kingpinXD October 4, 2024 11:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add new field in CCTX object to contains cross-chain call error
3 participants