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

Fix/sync dev after v1 53 0 #252

Merged
merged 3 commits into from
Oct 10, 2024
Merged

Fix/sync dev after v1 53 0 #252

merged 3 commits into from
Oct 10, 2024

Conversation

PavelInjective
Copy link
Contributor

@PavelInjective PavelInjective commented Oct 9, 2024

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for transaction broadcasting to ensure clearer feedback on transaction failures.
    • Introduction of an OFAC list for improved compliance checks.
  • Bug Fixes

    • Updated transaction methods to return more accurate error responses.
  • Documentation

    • Added constants and updated method names for better clarity regarding OFAC functionalities.
  • Tests

    • New test suite for OFAC functionality to ensure proper address checks and compliance.
    • Retained and updated existing tests for subaccount functionalities.

@PavelInjective PavelInjective requested a review from aarmoa October 9, 2024 20:25
Copy link

coderabbitai bot commented Oct 9, 2024

Walkthrough

The pull request introduces several modifications primarily focused on error handling in the SyncBroadcastSignedTx and broadcastTx methods of the chainClient struct. Additionally, it transitions the chain_test.go file to chain_test for testing purposes, updates the OFAC-related functionality in ofac.go, and introduces a new test suite for OFAC checks in ofac_test.go. A new JSON file, ofac.json, containing Ethereum addresses, is also added.

Changes

File Change Summary
client/chain/chain.go Updated error handling in SyncBroadcastSignedTx and broadcastTx methods to check res.TxResponse.Code.
client/chain/chain_test.go Transitioned to chain_test package; modified imports and retained some tests while removing OFAC-related tests.
client/chain/ofac.go Updated naming conventions and added new constants; modified methods to incorporate new naming.
client/chain/ofac_test.go Introduced a new test suite for OFAC functionality with setup, teardown, and test methods.
injective_data/ofac.json Added a new JSON file containing an array of Ethereum addresses.

Possibly related PRs

  • (feat) Add OFAC list check #236: The changes in this PR add an ofacChecker to the chainClient struct, which is relevant to the modifications in the main PR that also involve error handling related to transaction broadcasting, ensuring compliance with OFAC regulations.
  • Release/v1.52.0 #242: Similar to (feat) Add OFAC list check #236, this PR also introduces an ofacChecker and modifies the NewChainClient function to include OFAC checks, which aligns with the error handling updates in the main PR.
  • fix/check_tx_result_in_sync_broadcast_before_await #249: This PR modifies the SyncBroadcastSignedTx and broadcastTx methods, which are also the focus of the main PR, enhancing error handling during transaction broadcasting.
  • Fix/sync dev after v1 52 2 #250: This PR also updates the SyncBroadcastSignedTx and broadcastTx methods, reinforcing the changes made in the main PR regarding error handling for transaction responses.
  • Fix/make OFAC list file path relative #251: This PR modifies the ofac.go file, which is related to the OFAC functionality discussed in the main PR, ensuring that the OFAC list file path is relative, thus enhancing the overall compliance checks.

Suggested reviewers

  • aarmoa

Poem

🐇 In the code where bunnies play,
Errors caught, they won't stray.
OFAC checks now stand so tall,
With tests in place, we won't fall.
Hopping through the lines so bright,
Our changes make the code just right! 🌟


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.

@PavelInjective PavelInjective marked this pull request as draft October 9, 2024 20:28
@PavelInjective PavelInjective force-pushed the fix/sync_dev_after_v1_53_0 branch from 4ae8d48 to 722a2d3 Compare October 9, 2024 20:30
@PavelInjective PavelInjective marked this pull request as ready for review October 9, 2024 20:30
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.

Caution

Inline review comments failed to post

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (13)
client/chain/ofac.go (3)

13-13: LGTM! Consider using a versioned URL.

The constant DefaultOfacListURL is well-named and follows Go conventions. However, consider using a versioned URL or a more stable endpoint to prevent potential issues if the repository structure changes.


17-18: LGTM! Consider environment-specific configurations.

The variables OfacListPath and OfacListFilename are now exported, which is good for reusability. However, consider the following improvements:

  1. Use environment variables or configuration files to set OfacListPath for different environments.
  2. Add comments explaining the purpose of these variables and their expected values.

Line range hint 41-59: LGTM! Good improvements in error handling and directory creation.

The new GetOfacListPath function and the updates to DownloadOfacList are well-implemented. The addition of directory creation is a good improvement. A few suggestions:

  1. Consider adding a comment explaining why 0755 permissions are used and why the linter exception is necessary.
  2. The error handling for os.MkdirAll could be combined with the os.Create error handling to reduce nesting.

Here's a suggestion for combining error handling:

if err := os.MkdirAll(OfacListPath, 0755); err != nil {
    return fmt.Errorf("failed to create directory: %w", err)
}
outFile, err := os.Create(GetOfacListPath())
if err != nil {
    return fmt.Errorf("failed to create file: %w", err)
}
defer outFile.Close()
injective_data/ofac.json (1)

1-48: Consider the implications of maintaining an OFAC-related address list.

The file name "ofac.json" suggests this list is related to the Office of Foreign Assets Control (OFAC). This list likely serves a compliance purpose, possibly to check transactions against sanctioned addresses. Consider the following implications:

  1. Regulatory compliance: Ensure your system uses this list effectively to comply with OFAC regulations.
  2. Privacy: Verify that storing and using this list complies with relevant data protection regulations.
  3. Maintenance: Implement a process for regular updates to reflect the latest OFAC sanctions.
  4. Performance: Optimize the application for quick lookups against this list, especially if used in transaction processing.

Consider implementing a more robust solution for managing and using this list, such as:

  • Using a database instead of a JSON file for better performance and easier updates.
  • Implementing a background job for regular updates from an authoritative source.
  • Adding logging and alerting mechanisms for when transactions involve listed addresses.
client/chain/ofac_test.go (2)

27-54: LGTM with a minor suggestion: Consider improving error handling in file operations.

The SetupTest method thoroughly initializes the test environment, including network setup and OFAC list preparation. However, consider using defer for file closing to ensure it happens even if an error occurs.

Consider modifying the file handling part as follows:

 file, err := os.Create(chain.GetOfacListPath())
 suite.NoError(err)
+defer func() {
+    cerr := file.Close()
+    if err == nil {
+        err = cerr
+    }
+}()

 _, err = io.WriteString(file, string(jsonData))
 suite.NoError(err)

-err = file.Close()
-suite.NoError(err)

This ensures that the file is always closed and any error during closing is properly handled.


56-80: LGTM with a suggestion: Consider expanding test coverage in TestOfacList.

The TearDownTest and TestOfacList methods are well-implemented. The OFAC checking functionality and client creation are properly tested. However, consider adding more test cases to TestOfacList for a more comprehensive coverage.

Consider adding the following test cases to TestOfacList:

  1. Test with multiple addresses in the OFAC list.
  2. Test the behavior when the OFAC list is empty.
  3. Test with invalid addresses.
  4. Test the performance with a large OFAC list.

Example:

func (suite *OfacTestSuite) TestOfacList() {
    // ... existing code ...

    // Test with multiple addresses
    multipleAddresses := []string{suite.senderAddress.String(), "inj1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq"}
    testChecker, err = chain.NewOfacChecker()
    suite.NoError(err)
    for _, addr := range multipleAddresses {
        suite.True(testChecker.IsBlacklisted(addr))
    }

    // Test with empty OFAC list
    // ... implement this test case

    // Test with invalid address
    suite.False(testChecker.IsBlacklisted("invalid_address"))

    // Test performance with large OFAC list
    // ... implement this test case
}
client/chain/chain_test.go (7)

Line range hint 17-24: Use a temporary directory for keyring storage in tests

Using a hardcoded path like os.Getenv("HOME")+"/.injectived" for the keyring storage can lead to conflicts or issues when running tests in different environments or concurrently. It's better to use a temporary directory to ensure isolation and prevent side effects.

Apply this change:

-func accountForTests() (cosmtypes.AccAddress, keyring.Keyring, error) {
+func accountForTests(t *testing.T) (cosmtypes.AccAddress, keyring.Keyring, error) {
+    tempDir := t.TempDir()
     senderAddress, cosmosKeyring, err := chain.InitCosmosKeyring(
-        os.Getenv("HOME")+"/.injectived",
+        tempDir,
         "injectived",
         "file",
         "inj-user",
         "12345678",
         "5d386fbdbf11f1141010f81a46b40f94887367562bd33b452bbaa6ce1cd1381e", // keyring will be used if pk not provided
         false,
     )

Note: You will need to pass t *testing.T to accountForTests and update any calls to this function accordingly.


Line range hint 55-57: Use t.Fatalf instead of t.Errorf for critical setup errors

When an error occurs during test setup, such as failing to create the address, it's appropriate to use t.Fatalf to immediately terminate the test. Using t.Errorf logs the error but allows the test to continue, which may lead to misleading results or panics.

Apply this change:

 if err != nil {
-    t.Errorf("Error creating the address %v", err)
+    t.Fatalf("Error creating the address: %v", err)
 }

Line range hint 61-63: Use t.Fatalf instead of t.Errorf when failing to create the client

Failing to create the client is a critical error that should halt the test immediately to prevent subsequent failures or misleading results.

Apply this change:

 if err != nil {
-    t.Errorf("Error creating the client %v", err)
+    t.Fatalf("Error creating the client: %v", err)
 }

Line range hint 77-79: Use t.Fatalf instead of t.Errorf for critical setup errors

Consistently use t.Fatalf when setup errors occur to ensure the test stops immediately, maintaining test reliability.

Apply this change:

 if err != nil {
-    t.Errorf("Error creating the address %v", err)
+    t.Fatalf("Error creating the address: %v", err)
 }

Line range hint 83-85: Use t.Fatalf instead of t.Errorf when failing to create the client

As with the previous test, use t.Fatalf to handle critical errors appropriately.

Apply this change:

 if err != nil {
-    t.Errorf("Error creating the client %v", err)
+    t.Fatalf("Error creating the client: %v", err)
 }

Line range hint 91-96: Correct typos in variable names

There are typos in the variable names that could lead to confusion or errors:

  • expectedSubaccounOnetId should be expectedSubaccountOneId
  • expectedSubaccounThirtytId should be expectedSubaccountThirtyId

Apply this change:

-expectedSubaccounOnetId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
-expectedSubaccountOneIdHash := eth.HexToHash(expectedSubaccounOnetId)
+expectedSubaccountOneId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
+expectedSubaccountOneIdHash := eth.HexToHash(expectedSubaccountOneId)

-expectedSubaccounThirtytId := "0xaf79152ac5df276d9a8e1e2e22822f971347490200000000000000000000001e"
-expectedSubaccountThirtyIdHash := eth.HexToHash(expectedSubaccounThirtytId)
+expectedSubaccountThirtyId := "0xaf79152ac5df276d9a8e1e2e22822f971347490200000000000000000000001e"
+expectedSubaccountThirtyIdHash := eth.HexToHash(expectedSubaccountThirtyId)

Line range hint 17-24: Consider parameterizing test account details and network configuration

The tests currently use hardcoded account credentials and network configurations, which may not be suitable for all testing environments and could pose security risks if sensitive information is exposed.

Consider externalizing these details using environment variables or a configuration file. This approach enhances flexibility and security by allowing different test setups without modifying the code.

Also applies to: 55-63, 77-85

🛑 Comments failed to post (1)
injective_data/ofac.json (1)

1-48: ⚠️ Potential issue

Remove duplicate Ethereum addresses.

There are several duplicate entries in the list:

  • "0x19aa5fe80d33a56d56c78e82ea5e50e5d80b4dff" (lines 4 and 5)
  • "0x2f389ce8bd8ff92de3402ffce4691d17fc4f6535" (lines 7 and 8)
  • "0x4f47bc496083c727c5fbe3ce9cdf2b0f6496270c" (lines 14, 15, and 16)
  • "0xb6f5ec1a0a9cd1526536d3f0426c429529471f40" (lines 33, 34, and 35)
  • "0xd882cfc20f52f2599d84b8e8d58c7fb62cfe344b" (lines 39 and 40)

Consider removing these duplicates to improve efficiency and prevent potential issues in processing this list.

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 (2)
client/chain/chain_test.go (2)

Line range hint 31-52: LGTM: Function signature and implementation updates are correct.

The changes to createClient function, including the return type update to chain.ChainClient and the use of chain.NewClientContext and chain.NewChainClient, are appropriate given the package change. These modifications improve type safety and clarity.

Consider adding error handling for the tmClient creation:

-tmClient, _ := rpchttp.New(network.TmEndpoint, "/websocket")
+tmClient, err := rpchttp.New(network.TmEndpoint, "/websocket")
+if err != nil {
+    return nil, fmt.Errorf("failed to create tmClient: %w", err)
+}

This would ensure that any issues with creating the tmClient are properly caught and reported.


Line range hint 78-106: LGTM: Test function updated correctly with a minor suggestion.

The TestGetSubaccountWithIndex function has been properly updated to use the new createClient function while maintaining the original test logic. This ensures that the existing test coverage is preserved while adapting to the package changes.

For consistency, consider updating the variable names to use camelCase:

-expectedSubaccounOnetId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
-expectedSubaccountOneIdHash := eth.HexToHash(expectedSubaccounOnetId)
+expectedSubaccountOneId := "0xaf79152ac5df276d9a8e1e2e22822f9713474902000000000000000000000001"
+expectedSubaccountOneIdHash := eth.HexToHash(expectedSubaccountOneId)

-expectedSubaccounThirtytId := "0xaf79152ac5df276d9a8e1e2e22822f971347490200000000000000000000001e"
-expectedSubaccountThirtyIdHash := eth.HexToHash(expectedSubaccounThirtytId)
+expectedSubaccountThirtyId := "0xaf79152ac5df276d9a8e1e2e22822f971347490200000000000000000000001e"
+expectedSubaccountThirtyIdHash := eth.HexToHash(expectedSubaccountThirtyId)

This would improve readability and maintain consistent naming conventions throughout the code.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4ae8d48 and 722a2d3.

📒 Files selected for processing (4)
  • client/chain/chain_test.go (3 hunks)
  • client/chain/ofac.go (4 hunks)
  • client/chain/ofac_test.go (1 hunks)
  • injective_data/ofac.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • client/chain/ofac.go
  • client/chain/ofac_test.go
  • injective_data/ofac.json
🧰 Additional context used
🔇 Additional comments (4)
client/chain/chain_test.go (4)

1-14: LGTM: Package and import changes are appropriate.

The transition to chain_test package and the addition of new imports align with the file's new purpose as a dedicated test file for the chain package. This change improves the separation of concerns and test organization.


Line range hint 16-28: LGTM: Improved code reuse in accountForTests.

The function now utilizes chain.InitCosmosKeyring, which reduces code duplication and ensures consistency between the main implementation and tests. This is a good practice for maintaining code quality and reducing potential discrepancies.


Line range hint 54-76: LGTM: Test function updated correctly.

The TestDefaultSubaccount function has been properly updated to use the new createClient function while maintaining the original test logic. This ensures that the existing test coverage is preserved while adapting to the package changes.


Line range hint 1-106: Verify the removal of OFAC-related tests.

The OFAC-related tests (OfacTestSuite and its methods) have been removed from this file. While this aligns with the file's transition to a dedicated test file for the chain package, it's important to ensure that these tests haven't been accidentally removed without being relocated elsewhere.

Please confirm that the OFAC-related tests have been intentionally removed or relocated to an appropriate location. If they've been moved, could you provide information about their new location?

✅ Verification successful

OFAC-related tests have been successfully relocated.

The OFAC-related tests have been moved to client/chain/ofac_test.go. The removal from client/chain/chain_test.go is intentional and correctly executed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for OFAC-related test files or test suites in the project
echo "Searching for OFAC-related test files:"
fd -e go | xargs rg -i "ofac.*test"

echo "Searching for OfacTestSuite in other files:"
rg -i "type\s+OfacTestSuite\s+struct"

Length of output: 704

Copy link
Collaborator

@aarmoa aarmoa left a comment

Choose a reason for hiding this comment

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

The PR looks good to me

@aarmoa aarmoa merged commit bc027f7 into dev Oct 10, 2024
4 checks passed
@aarmoa aarmoa deleted the fix/sync_dev_after_v1_53_0 branch October 10, 2024 02:03
This was referenced Nov 13, 2024
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