Skip to content

Conversation

@iuwqyir
Copy link
Contributor

@iuwqyir iuwqyir commented May 22, 2025

TL;DR

Added proper HTTP response handling in the GetABIForContract function.

What changed?

  • Added defer resp.Body.Close() to ensure the response body is properly closed after use
  • Added a check for the HTTP status code to verify that the response is successful (200 OK)
  • Added error handling for non-200 status codes with a descriptive error message

How to test?

  1. Test the function with a valid contract address and chain ID to ensure it still works correctly
  2. Test with an invalid or non-existent contract to verify the proper error is returned
  3. Test with a scenario where the API returns a non-200 status code to ensure the error is properly handled

Why make this change?

This change improves error handling and resource management in the GetABIForContract function. The previous implementation didn't close the response body, which could lead to resource leaks, and didn't check the HTTP status code, which could lead to unexpected behavior when the API returns an error status.

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability when fetching contract information by enhancing error handling and resource management.

@coderabbitai
Copy link

coderabbitai bot commented May 22, 2025

Walkthrough

The function responsible for retrieving a contract's ABI was updated to ensure the HTTP response body is always closed after use and to add explicit error handling for non-200 HTTP responses. No changes were made to function signatures or public APIs.

Changes

File(s) Change Summary
internal/common/abi.go Added deferred response body closure and explicit check for HTTP 200 status in ABI retrieval.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant ABIHelper

    Caller->>ABIHelper: GetABIForContract(contractAddress)
    ABIHelper->>ABIHelper: HTTP GET request for ABI
    ABIHelper->>ABIHelper: defer resp.Body.Close()
    ABIHelper->>ABIHelper: Check if response status is 200
    alt Status is 200
        ABIHelper->>ABIHelper: Parse ABI from response body
        ABIHelper-->>Caller: Return ABI
    else Status is not 200
        ABIHelper-->>Caller: Return error (unexpected status code)
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@iuwqyir iuwqyir requested a review from catalyst17 May 22, 2025 17:28
Copy link
Contributor Author

iuwqyir commented May 22, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@iuwqyir iuwqyir marked this pull request as ready for review May 22, 2025 17:28
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

🧹 Nitpick comments (2)
internal/common/abi.go (2)

43-45: Good error handling improvement.

Adding a status code check ensures that the ABI is only parsed from successful responses. This prevents potential parsing errors or unexpected behavior when the API returns error responses.

However, you might consider providing more specific error messages for common status codes:

if resp.StatusCode != http.StatusOK {
-	return nil, fmt.Errorf("failed to get contract abi: unexpected status code %d", resp.StatusCode)
+	if resp.StatusCode == http.StatusNotFound {
+		return nil, fmt.Errorf("failed to get contract abi: contract not found for %s on chain %s", contract, chainId)
+	} else {
+		return nil, fmt.Errorf("failed to get contract abi: unexpected status code %d for %s", resp.StatusCode, url)
+	}
}

34-52: Consider adding a timeout to the HTTP request.

The current implementation uses the default HTTP client without a timeout, which could lead to long-running requests if the API is slow to respond.

You could create a client with a timeout:

func GetABIForContract(chainId string, contract string) (*abi.ABI, error) {
	url := fmt.Sprintf("%s/abi/%s/%s", config.Cfg.API.ThirdwebContractApi, chainId, contract)

+	client := &http.Client{
+		Timeout: 10 * time.Second,
+	}
-	resp, err := http.Get(url)
+	resp, err := client.Get(url)
	if err != nil {
		return nil, fmt.Errorf("failed to get contract abi: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return nil, fmt.Errorf("failed to get contract abi: unexpected status code %d", resp.StatusCode)
	}

	abi, err := abi.JSON(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("failed to load contract abi: %v", err)
	}
	return &abi, nil
}

Don't forget to add "time" to the imports if you implement this suggestion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f520cfc and 7f31774.

📒 Files selected for processing (1)
  • internal/common/abi.go (1 hunks)
🔇 Additional comments (2)
internal/common/abi.go (2)

41-41: Good addition for proper resource management.

Adding defer resp.Body.Close() ensures that the HTTP response body is properly closed after use, preventing potential resource leaks. This is a Go best practice that should be applied to all HTTP requests.


15-32:

✅ Verification successful

Verify that cache mechanism properly handles non-200 responses.

Now that GetABIForContract returns errors for non-200 responses, ensure that GetABIForContractWithCache correctly handles these new error cases. The current implementation appears to be handling all errors in the same way by setting the cached value to nil, which is appropriate.


🏁 Script executed:

#!/bin/bash
# Search for any other callers of GetABIForContract to ensure they handle errors properly
rg "GetABIForContract\(" --type go -A 5 -B 5

Length of output: 1168


Cache correctly handles non-200 responses
GetABIForContractWithCache already treats any error (including non-200 HTTP responses) by caching nil and returning nil, which aligns with the intended behavior. No other callers of GetABIForContract were found in the codebase.
No further changes needed.

@iuwqyir iuwqyir merged commit 77ebcc3 into main May 22, 2025
6 checks passed
@iuwqyir iuwqyir deleted the 05-22-close_body_when_fetching_abi branch May 22, 2025 17:35
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.

3 participants