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

feat(x/crosschain): recover execute claimEvent #811

Merged
merged 1 commit into from
Nov 18, 2024

Conversation

zakir-code
Copy link
Contributor

@zakir-code zakir-code commented Nov 18, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced ExecuteClaimEvent to include an error reason for better context during event handling.
    • Updated error handling in claim execution processes to capture and report multiple error types.
  • Bug Fixes

    • Improved error reporting in the ExecuteClaim function, allowing for more detailed feedback on execution status.
  • Chores

    • Deprecated older ABI and bytecode variables in favor of a centralized metadata structure for better maintainability.

Copy link

coderabbitai bot commented Nov 18, 2024

Walkthrough

The pull request introduces significant updates to various components of the Ethereum contract ecosystem, primarily focusing on the BridgeFeeOracle and ICrosschain contracts. Key changes include the regeneration of Go bindings with updated ABI and bytecode, modifications to event signatures to enhance error reporting, and improved error handling in claim execution methods. The changes aim to centralize metadata management and refine contract interactions, ensuring more robust and informative handling of events and errors across multiple contract interfaces.

Changes

File Path Change Summary
contract/bridge_fee_oracle.sol.go Regenerated Go binding for BridgeFeeOracle, updated ABI and bytecode, deprecated BridgeFeeOracleABI and BridgeFeeOracleBin, introduced BridgeFeeOracleMetaData.
contract/icrosschain.sol.go Updated ICrosschainMetaData to include _errReason in ExecuteClaimEvent, modified associated function comments.
precompiles/crosschain/execute_claim.go Enhanced error handling in ExecuteClaimMethod, updated Run method to capture multiple error types, modified NewExecuteClaimEvent signature.
precompiles/crosschain/execute_claim_test.go Updated TestExecuteClaimMethod_ABI to reflect new ExecuteClaimEvent signature with _errReason.
precompiles/types/expected_keepers.go Changed ExecuteClaim method signature in CrosschainKeeper to return two errors instead of one.
solidity/contracts/bridge/ICrosschain.sol Added _errReason to ExecuteClaimEvent, marked crossChain function as deprecated.
tests/contract/crosschain_test.sol.go Updated bytecode and ABI metadata for CrosschainTest, deprecated CrosschainTestABI and CrosschainTestBin.
x/crosschain/keeper/attestation_handler.go Modified ExecuteClaim return signature to include two error types for better error reporting.
x/crosschain/keeper/keeper_v1_test.go Enhanced error handling in SendClaim method, separating checks for preliminary and execution errors.

Possibly related PRs

🐇 In the meadow, changes bloom,
Contracts dance, dispelling gloom.
With error tales now more precise,
Each claim whispers, "Be nice!"
ABI shines, bytecode anew,
A brighter path for all to pursue! 🌼


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

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (5)
precompiles/crosschain/execute_claim_test.go (1)

22-22: LGTM! Consider adding test cases for error reason.

The event signature update correctly reflects the addition of the _errReason parameter, aligning with the broader changes to enhance error reporting across the codebase.

Consider adding test cases that verify the packing/unpacking of event data with various error reasons to ensure the new parameter is handled correctly.

Example test case structure:

func TestExecuteClaimEvent_PackUnpack(t *testing.T) {
    executeClaimABI := crosschain.NewExecuteClaimABI()
    testCases := []struct {
        name      string
        sender    common.Address
        nonce     *big.Int
        chain     string
        errReason string
    }{
        {
            name:      "with error reason",
            sender:    common.HexToAddress("0x123"),
            nonce:     big.NewInt(1),
            chain:     ethtypes.ModuleName,
            errReason: "invalid signature",
        },
        // Add more test cases
    }
    // Implement test logic
}
x/crosschain/keeper/attestation_handler.go (1)

37-47: Consider standardizing error message format.

The implementation is solid with proper use of cache context for atomic operations and consistent error handling across all claim types. However, there's a minor inconsistency in error message formatting.

Consider standardizing the error message format in the default case:

-		executeErr = sdkerrors.ErrInvalidRequest.Wrapf("invalid claim type: %s", claim.GetType())
+		executeErr = sdkerrors.ErrInvalidRequest.Wrapf("event type: %s", claim.GetType())

This would make it consistent with the error message format in AttestationHandler.

solidity/contracts/bridge/ICrosschain.sol (1)

69-70: LGTM: Enhanced error reporting improves debugging capabilities

The addition of _errReason to the event signature is a valuable enhancement that provides better context for failed claim executions, making it easier to diagnose issues in cross-chain operations.

Consider documenting common error reasons in the interface comments to ensure consistent error messaging across implementations.

    event ExecuteClaimEvent(
        address indexed _sender,
        uint256 _eventNonce,
        string _chain,
+       /// @dev Common error reasons:
+       /// - "invalid chain"
+       /// - "invalid event nonce"
+       /// - "execution failed"
        string _errReason
    );
precompiles/crosschain/execute_claim.go (1)

87-92: Consider adding error message length validation

The error handling implementation looks good, but consider adding validation for the error message length to prevent excessive gas costs in case of very long error messages.

Consider applying this improvement:

 func (m ExecuteClaimABI) NewExecuteClaimEvent(sender common.Address, eventNonce *big.Int, dstChain string, executeErr error) (data []byte, topic []common.Hash, err error) {
 	errReason := ""
 	if executeErr != nil {
-		errReason = executeErr.Error()
+		// Limit error message length to prevent excessive gas costs
+		errMsg := executeErr.Error()
+		const maxErrLength = 256
+		if len(errMsg) > maxErrLength {
+			errMsg = errMsg[:maxErrLength]
+		}
+		errReason = errMsg
 	}
 	return evmtypes.PackTopicData(m.Event, []common.Hash{sender.Hash()}, eventNonce, dstChain, errReason)
 }
tests/contract/crosschain_test.sol.go (1)

Line range hint 466-469: Consider enhancing error handling for claim recovery

Given that this PR aims to recover execute claimEvent functionality, the current implementation could benefit from:

  1. More specific error types for different failure scenarios
  2. Explicit handling of recovery cases
  3. Logging or events for tracking claim execution status

Consider wrapping the error returns to provide more context:

 func (_CrosschainTest *CrosschainTestTransactor) ExecuteClaim(opts *bind.TransactOpts, _chain string, _eventNonce *big.Int) (*types.Transaction, error) {
-    return _CrosschainTest.contract.Transact(opts, "executeClaim", _chain, _eventNonce)
+    tx, err := _CrosschainTest.contract.Transact(opts, "executeClaim", _chain, _eventNonce)
+    if err != nil {
+        return nil, fmt.Errorf("failed to execute claim for chain %s and nonce %s: %w", _chain, _eventNonce, err)
+    }
+    return tx, nil
 }

Also applies to: 476-479, 483-486

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 509f4cd and 52897b3.

📒 Files selected for processing (9)
  • contract/bridge_fee_oracle.sol.go (1 hunks)
  • contract/icrosschain.sol.go (4 hunks)
  • precompiles/crosschain/execute_claim.go (2 hunks)
  • precompiles/crosschain/execute_claim_test.go (1 hunks)
  • precompiles/types/expected_keepers.go (1 hunks)
  • solidity/contracts/bridge/ICrosschain.sol (1 hunks)
  • tests/contract/crosschain_test.sol.go (1 hunks)
  • x/crosschain/keeper/attestation_handler.go (1 hunks)
  • x/crosschain/keeper/keeper_v1_test.go (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • contract/bridge_fee_oracle.sol.go
🔇 Additional comments (13)
precompiles/crosschain/execute_claim_test.go (1)

22-22: Verify consistent implementation of the updated event signature.

Since this is a breaking change in the event signature, we should verify that all related code has been updated accordingly.

x/crosschain/keeper/attestation_handler.go (3)

30-33: LGTM! Well-structured error handling improvement.

The separation of preExecuteErr and executeErr provides better error granularity, allowing callers to distinguish between claim retrieval and execution failures. The early return pattern is clean and follows Go best practices.


48-51: LGTM! Proper atomic operation handling.

The commit logic correctly ensures atomic operations by only committing on successful execution. The return statement properly maintains the separation of concerns between pre-execution and execution errors.


30-51: Verify consistent error handling across callers.

The change from single to dual error returns is significant. Let's verify that all callers properly handle both error types.

✅ Verification successful

Based on the search results, I can now generate a final response since I have enough information about the error handling pattern and its usage:

Dual error return pattern is consistently implemented

The dual error return pattern (preExecuteErr, executeErr) is properly handled across the codebase:

  • The ExecuteClaim method is the only place using this specific pattern, which is appropriate since it has unique two-phase execution requirements
  • All callers properly handle the errors:
    • Integration tests check for both errors via NoError assertions
    • Precompile layer properly propagates both errors through the EVM bridge
    • Contract bindings maintain the error semantics
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all callers of ExecuteClaim to verify proper error handling

# Search for ExecuteClaim function calls
rg -t go "ExecuteClaim\(" --context 5

# Search for any similar dual-error patterns in the codebase for consistency
rg -t go "\) \(.*Err,.*Err error\)" --context 3

Length of output: 37246

solidity/contracts/bridge/ICrosschain.sol (1)

69-70: Breaking change: Event signature modification requires careful deployment coordination

The addition of the _errReason parameter to ExecuteClaimEvent is a breaking change that affects event filtering and contract interactions. This enhancement improves error reporting but requires coordination during deployment.

Let's verify the impact on existing event listeners and contracts:

precompiles/crosschain/execute_claim.go (1)

58-62: Verify alignment with ICrosschain interface changes

The enhanced error handling with separate preExecuteErr and executeErr looks good. This change allows for more granular error reporting and aligns with the updated event signature.

Let's verify the alignment with the contract interface:

✅ Verification successful

Let me gather more information about the executeClaim function signature since it wasn't visible in the previous results.


Based on the gathered information, I can now provide the final response:

The error handling changes align correctly with the contract interface

The changes in error handling are verified to be correct because:

  • The Solidity interface ICrosschain.sol defines the event with the error reason parameter: event ExecuteClaimEvent(address indexed _sender, uint256 _eventNonce, string _chain, string _errReason)
  • The keeper implementation in x/crosschain/keeper/attestation_handler.go correctly returns both preExecuteErr and executeErr
  • The event emission properly includes the error information from executeErr in the event parameters
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the ICrosschain interface matches these changes

# Check the event signature in the contract
rg -A 2 "event ExecuteClaimEvent" 

# Check the execute claim function signature
ast-grep --pattern 'function executeClaim($$$) $$$'

Length of output: 1750


Script:

#!/bin/bash
# Search for executeClaim function definition in Solidity files
rg -A 3 "function executeClaim" 

# Search for ExecuteClaim method in Go files to verify the error handling pattern
rg -A 3 "func.*ExecuteClaim.*error"

Length of output: 19163

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

115-117: LGTM! Improved error handling with clear separation of concerns.

The changes enhance error handling by separately validating preliminary checks (preErr) and execution errors (executeErr). This separation provides better visibility into where failures occur during claim execution.

precompiles/types/expected_keepers.go (1)

30-30: LGTM! Consider adding documentation for error returns.

The change to return two errors improves error handling granularity, which aligns well with the PR's objective of recovering execute claimEvent functionality.

Consider adding documentation to clarify the meaning of each error return (e.g., pre-execution vs execution errors).

Let's verify the consistent implementation across the codebase:

✅ Verification successful

Let me analyze the results from the shell scripts:

  1. Found the implementation in x/crosschain/keeper/attestation_handler.go:
func (k Keeper) ExecuteClaim(ctx sdk.Context, eventNonce uint64) (preExecuteErr, executeErr error) {
    externalClaim, preExecuteErr := k.GetPendingExecuteClaim(ctx, eventNonce)
    if preExecuteErr != nil {
        return preExecuteErr, nil
    }
    k.DeletePendingExecuteClaim(ctx, eventNonce)
    // ...
}
  1. Found callers handling both errors correctly:
  • In precompiles/crosschain/execute_claim.go:
preExecuteErr, executeErr := crosschainKeeper.ExecuteClaim(ctx, args.EventNonce.Uint64())
if preExecuteErr != nil {
    return preExecuteErr
}
  1. Found test cases in x/crosschain/keeper/keeper_v1_test.go:
preErr, executeErr := suite.Keeper().ExecuteClaim(suite.Ctx, externalClaim.GetEventNonce())
suite.Require().NoError(preErr)
suite.Require().NoError(executeErr)

Implementation and error handling are consistent across the codebase

The implementation in attestation_handler.go clearly shows:

  • First error (preExecuteErr) is for pending claim retrieval issues
  • Second error (executeErr) is for execution-related issues

All callers properly handle both error returns, making the change safe and well-implemented.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for implementations and callers of ExecuteClaim
# to ensure they handle both error returns correctly

# Find ExecuteClaim implementations
echo "Checking ExecuteClaim implementations:"
ast-grep --pattern 'func $$$ExecuteClaim(ctx $_, eventNonce $_) (error, error)'

# Find ExecuteClaim callers
echo "Checking ExecuteClaim callers:"
rg -A 3 'ExecuteClaim\(' 

Length of output: 17745

tests/contract/crosschain_test.sol.go (3)

Line range hint 39-44: LGTM: Proper deprecation notices

The deprecation notices for CrosschainTestABI and CrosschainTestBin are well documented with clear migration paths to use CrosschainTestMetaData. This aligns with the codebase's move towards centralized metadata management.


Line range hint 1-1: Verify no manual modifications to generated file

Since this is a generated file (as indicated by the header comment), please ensure that all changes are made to the Solidity source file and then regenerated, rather than modified directly in this file.

#!/bin/bash
# Description: Check for any manual modifications to the generated file
# Look for the generation command in build files
rg -l "abigen|solc" -g "Makefile*"
rg -l "abigen|solc" -g "*.sh"

# Check git history for manual modifications
git log -p tests/contract/crosschain_test.sol.go | grep -C5 "^[+-]" | grep -v "// Code generated"

35-35: Verify the bytecode generation process

The bytecode has been significantly modified, which is more extensive than what would be expected for just recovering the executeClaim functionality. Please verify that the bytecode was properly generated from the Solidity source.

✅ Verification successful

Let me analyze the provided context and generate additional verification scripts to understand the bytecode changes better.

The previous output showed the Makefile and compile.sh contain relevant information, but we need to see their content to understand how the contract is being compiled and if the bytecode generation is correct.


Let me check the Solidity contract source to verify if the bytecode changes are legitimate.


Bytecode changes are legitimate and properly generated

The bytecode changes in tests/contract/crosschain_test.sol.go are legitimate because:

  1. The Solidity source file was newly added in the same PR (commit 509f4cd)
  2. The bytecode was generated through a proper compilation process as shown in contract/compile.sh:
    • Uses correct solc version (^0.8.0)
    • Compiles with yarn in the solidity directory
    • Uses abigen 1.12.0 to generate the Go bindings
  3. The contract includes the executeClaim function which aligns with the PR objective of "recover execute claimEvent"
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the contract source matches the bytecode
# Look for the original Solidity contract file
fd -e sol -t f crosschain_test

# Check if there are any other contract files that might be related
rg -l "contract CrosschainTest" -g "*.sol"

Length of output: 37443


Script:

#!/bin/bash
# Look for the original Solidity contract file and compilation scripts
fd -e sol crosschain_test
fd -e sh compile

# Check the compilation command in the Makefile
rg -l "abigen|solc" -g "Makefile*"

# Check if there are any test files that might show the contract deployment
rg -l "DeployCrosschainTest" -g "*.go"

# Look for the original contract implementation
rg -l "contract CrosschainTest" -g "*.sol"

Length of output: 277


Script:

#!/bin/bash
# Check the content of compilation related files
cat Makefile | grep -A5 -B5 'solc\|abigen'
cat contract/compile.sh

Length of output: 2691


Script:

#!/bin/bash
# Check the Solidity contract source
cat solidity/contracts/test/CrosschainTest.sol

# Check if there are any recent changes to the contract
git log -p solidity/contracts/test/CrosschainTest.sol

Length of output: 7345

contract/icrosschain.sol.go (2)

740-740: LGTM: Error reason field added to event structure

The addition of ErrReason field to ICrosschainExecuteClaimEvent enhances error reporting capabilities.


744-746: Verify event signature consistency

The event signature has been updated consistently across Filter, Watch, and Parse functions. Let's verify the event hash matches the new signature.

Also applies to: 761-763, 803-805

✅ Verification successful

Event signature is consistent across all implementations

The verification shows that:

  • The event signature ExecuteClaimEvent(address indexed _sender, uint256 _eventNonce, string _chain, string _errReason) is consistently defined in the ABI and used across all related functions
  • The event hash 0x67ddf3796d30bb96cc50ccd9d322ab53317f5c6cac5860f3137894ee70ed0053 is consistently used in all three functions: Filter, Watch, and Parse
  • The struct definition ICrosschainExecuteClaimEvent and its usage in iterators and event handlers align with the event signature
  • The test file execute_claim_test.go confirms the expected event signature
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify that the event signature hash is correct for the updated event definition
# Expected: Hash should match 0x67ddf3796d30bb96cc50ccd9d322ab53317f5c6cac5860f3137894ee70ed0053

# Search for the Solidity event definition
ast-grep --pattern 'event ExecuteClaimEvent(address indexed _sender, uint256 _eventNonce, string _chain, string _errReason)'

# Calculate the event signature hash
echo -n "ExecuteClaimEvent(address indexed _sender,uint256 _eventNonce,string _chain,string _errReason)" | \
  sha3sum -a keccak256

Length of output: 332


Script:

#!/bin/bash
# Let's try a different approach to verify the event signature consistency

# Search for all occurrences of ExecuteClaimEvent in the codebase
rg -A 2 "ExecuteClaimEvent" --type go

# Also search for the event hash to ensure it's consistent
rg "0x67ddf3796d30bb96cc50ccd9d322ab53317f5c6cac5860f3137894ee70ed0053"

Length of output: 11736

@zakir-code zakir-code merged commit ea214d9 into main Nov 18, 2024
16 checks passed
@zakir-code zakir-code deleted the fx0x55/execute-claim branch November 18, 2024 08:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants