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(blockscout-client): update to the latest swagger #1224

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

rimrakhimov
Copy link
Member

@rimrakhimov rimrakhimov commented Jan 31, 2025

Summary by CodeRabbit

Based on the comprehensive changes across the BlockScout client library, here are the updated release notes:

  • New Features

    • Added NFT-related API endpoints for retrieving NFT instances and collections.
    • Introduced new token transfer retrieval functionality.
    • Enhanced transaction summary and metadata retrieval capabilities.
  • Improvements

    • Standardized API parameter and field naming conventions.
    • Improved error handling for various API methods.
    • Updated OpenAPI specification for better clarity and consistency.
  • Changes

    • Renamed multiple transaction-related parameters (e.g., tx_hashtransaction_hash).
    • Updated method names to be more descriptive, including several transaction-related methods.
    • Refactored code to improve readability and maintainability.
  • Version

    • Updated OpenAPI generator version from 7.7.0-SNAPSHOT to 7.12.0-SNAPSHOT.

Copy link
Contributor

coderabbitai bot commented Jan 31, 2025

Walkthrough

This pull request introduces significant enhancements to the BlockScout client library, focusing on expanding API functionality and improving code consistency. The changes primarily involve adding new models and APIs for NFT-related operations, introducing token transfer endpoints, and standardizing naming conventions across the codebase. Key modifications include renaming fields like tx_hash to transaction_hash, adding new structs for transaction summaries and NFT collections, and updating the OpenAPI specification to reflect these changes. The library now supports more comprehensive querying of blockchain data, with improved clarity in method and parameter names.

Possibly related PRs

  • feat(api-client-framework)!: configuration and endpoint updates #1174: The changes in this PR involve updates to the API client framework, including the addition of new methods for handling headers in API calls, which may relate to the new API functionalities introduced in the main PR, particularly those concerning NFT and transaction data handling.

Poem

🐰 Hop, hop, hooray! A BlockScout update today! 🌟
NFTs dancing, transactions so bright,
Renamed with care, everything just right
From tx_hash to something more clear,
Our rabbit client brings blockchain cheer! 🚀
Twitch, twitch goes my coding ear! 🐇


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33d601f and 6e5abd3.

📒 Files selected for processing (2)
  • libs/blockscout-client/crate/src/models/indexing_status.rs (2 hunks)
  • libs/blockscout-client/crate/tests/it_works.rs (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • libs/blockscout-client/crate/tests/it_works.rs
🔇 Additional comments (2)
libs/blockscout-client/crate/src/models/indexing_status.rs (2)

26-34: LGTM! Clean constructor implementation.

The constructor follows Rust idioms with:

  • Appropriate use of field init shorthand
  • Sensible defaults for optional fields

Line range hint 14-24: LGTM! Verify the type changes for ratio fields.

The struct definition follows Rust best practices with appropriate serde annotations. The ratio fields using Option<String> makes sense for nullable values.

Let's verify the previous types of the ratio fields:

✅ Verification successful

Type changes for ratio fields are correctly implemented

The change to Option<String> aligns with:

  • OpenAPI specification defining these as string fields
  • API responses containing both string values ("0.00", "1.00") and null values
  • Actual usage patterns across the codebase
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check previous types of ratio fields
git log -p -- libs/blockscout-client/crate/src/models/indexing_status.rs | rg -A 5 -B 5 'indexed_.*_ratio'

Length of output: 0


Script:

#!/bin/bash
# Search for files containing IndexingStatus
echo "=== Files containing IndexingStatus ==="
rg -l "IndexingStatus"

echo -e "\n=== Usage of ratio fields ==="
rg "indexed_.*_ratio"

echo -e "\n=== Recent commits touching this file ==="
git log --oneline -- libs/blockscout-client/crate/src/models/indexing_status.rs

Length of output: 6279


Script:

#!/bin/bash
# Check OpenAPI specification for ratio fields
echo "=== OpenAPI v2 Specification ==="
rg -A 2 "indexed_.*_ratio:" libs/blockscout-client/swaggers/blockscout-api-v2.yaml

Length of output: 330


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🔭 Outside diff range comments (1)
libs/blockscout-client/crate/.openapi-generator/FILES (1)

Document the major changes in the README.

The README needs to be updated to reflect the significant new features added to the client:

  • NFT collections and instances support
  • Token transfers API
  • Transaction summaries
  • reCAPTCHA integration

Consider adding a "Features" or "Capabilities" section to help users understand what the client can do.

🔗 Analysis chain

Line range hint 1-130: Document the major changes in the README.

Consider adding a section in the README to document these significant additions:

  • NFT collections and instances support
  • Token transfers API
  • Transaction summaries
  • reCAPTCHA integration

Let's check if the README needs updating:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if README mentions the new features

echo "Checking README for new features documentation:"
fd -g "README*" . --exec grep -l -i "nft\|token transfer\|transaction summary\|recaptcha" {} \;

Length of output: 243


Script:

#!/bin/bash
# Find and display README content in blockscout-client directory
echo "Looking for README in blockscout-client directory:"
fd -p "blockscout-client/**/README*" .

echo -e "\nContent of README if found:"
fd -p "blockscout-client/**/README*" . --exec cat {}

Length of output: 1397

🧹 Nitpick comments (20)
libs/blockscout-client/crate/tests/it_works.rs (1)

45-48: Consider enhancing test coverage with additional assertions.

The test could be more thorough by verifying specific fields in the response structure, not just checking if items exist.

Example enhancement:

     let internal_transactions = transactions_api::get_transaction_internal_txs(&config, DEFAULT_TX_HASH)
         .await
         .expect("Failed to get transactions");
     assert!(!internal_transactions.items.is_empty());
+    // Verify the transaction hash matches
+    assert_eq!(internal_transactions.items[0].transaction_hash, DEFAULT_TX_HASH);
+    // Verify required fields are present
+    assert!(internal_transactions.items[0].from.is_some());
+    assert!(internal_transactions.items[0].value.is_some());
libs/blockscout-client/crate/src/apis/search_api.rs (1)

36-64: LGTM! Consider enhancing error handling with specific status codes.

The refactoring improves code clarity through parameter prefixing and streamlined request building. However, the error handling could be more specific.

Consider matching specific status codes instead of using the generic is_client_error() and is_server_error():

-    if !status.is_client_error() && !status.is_server_error() {
+    match status.as_u16() {
+        200 => {
+            let content = resp.text().await?;
+            serde_json::from_str(&content).map_err(Error::from)
+        }
+        400 => {
+            let content = resp.text().await?;
+            let entity = serde_json::from_str(&content).ok();
+            Err(Error::ResponseError(ResponseContent {
+                status,
+                content,
+                entity,
+            }))
+        }
+        _ => {
+            let content = resp.text().await?;
+            let entity = None;
+            Err(Error::ResponseError(ResponseContent {
+                status,
+                content,
+                entity,
+            }))
+        }
+    }
libs/blockscout-client/crate/src/apis/health_api.rs (1)

39-49: Consider optimizing response handling.

The current implementation has a few areas that could be improved:

  1. Content is fetched twice in different branches
  2. Text extraction errors are silently propagated
  3. Error cases lack logging for debugging

Consider refactoring to this more robust approach:

-    if !status.is_client_error() && !status.is_server_error() {
-        let content = resp.text().await?;
-        serde_json::from_str(&content).map_err(Error::from)
-    } else {
-        let content = resp.text().await?;
-        let entity: Option<HealthError> = serde_json::from_str(&content).ok();
-        Err(Error::ResponseError(ResponseContent {
-            status,
-            content,
-            entity,
-        }))
-    }
+    let content = resp.text().await.map_err(|e| {
+        tracing::error!("Failed to extract response content: {}", e);
+        e
+    })?;
+    
+    if !status.is_client_error() && !status.is_server_error() {
+        serde_json::from_str(&content).map_err(|e| {
+            tracing::error!("Failed to deserialize success response: {}", e);
+            Error::from(e)
+        })
+    } else {
+        let entity = serde_json::from_str(&content).ok();
+        if entity.is_none() {
+            tracing::warn!("Failed to deserialize error response: {}", content);
+        }
+        Err(Error::ResponseError(ResponseContent {
+            status,
+            content,
+            entity,
+        }))
+    }

This refactoring:

  • Extracts content once
  • Adds error logging for better debugging
  • Maintains the same functionality while being more maintainable
libs/blockscout-client/crate/src/models/token_address_param.rs (3)

7-7: Update the contact email in the file header.

The contact email is currently set to a placeholder value. Consider updating it to reflect the actual maintainer's contact information.

- * Contact: [email protected]
+ * Contact: <actual-maintainer-email>

14-35: Add documentation comments for all struct fields.

While the address field has documentation, other fields lack documentation comments. Consider adding documentation for all fields to improve code maintainability.

Example:

/// Represents a token address with its associated metadata
pub struct TokenAddressParam {
    /// Hash of the token address
    #[serde(rename = "hash")]
    pub hash: String,
    /// Name of the implementation
    #[serde(rename = "implementation_name")]
    pub implementation_name: String,
    // ... add docs for other fields
}

37-60: Consider adding builder pattern and utility methods.

While the current implementation is functional, consider these improvements for better ergonomics:

  1. Add a builder pattern for more flexible object construction
  2. Add methods to set/update the optional address field

Example implementation:

impl TokenAddressParam {
    // ... existing new method ...

    /// Sets the address field
    pub fn with_address(mut self, address: impl Into<String>) -> Self {
        self.address = Some(address.into());
        self
    }

    /// Builder pattern implementation
    pub fn builder() -> TokenAddressParamBuilder {
        TokenAddressParamBuilder::default()
    }
}

#[derive(Default)]
pub struct TokenAddressParamBuilder {
    hash: Option<String>,
    implementation_name: Option<String>,
    // ... other fields ...
}

impl TokenAddressParamBuilder {
    pub fn hash(mut self, hash: impl Into<String>) -> Self {
        self.hash = Some(hash.into());
        self
    }
    // ... other builder methods ...

    pub fn build(self) -> Result<TokenAddressParam, &'static str> {
        // Add validation here
        Ok(TokenAddressParam {
            hash: self.hash.ok_or("hash is required")?,
            // ... other fields ...
        })
    }
}
libs/blockscout-client/crate/src/apis/stats_api.rs (1)

98-101: Consider using single-line format for consistency.

While the multi-line format is valid, consider using a single-line format for the URI string to maintain consistency with other functions in this file.

-    let uri_str = format!(
-        "{}/api/v2/stats/charts/transactions",
-        configuration.base_path
-    );
+    let uri_str = format!("{}/api/v2/stats/charts/transactions", configuration.base_path);
libs/blockscout-client/crate/src/apis/smart_contracts_api.rs (1)

Line range hint 1-405: Consider enhancing API robustness with additional features.

While the implementation is solid, consider these improvements:

  1. Add documentation for success/error scenarios in function comments
  2. Consider implementing retry logic with exponential backoff for transient failures
  3. Add rate limiting handling capabilities

Example documentation improvement:

/// Retrieves the read methods for a smart contract
///
/// # Arguments
/// * `address_hash` - The hash of the smart contract address
/// * `is_custom_abi` - Optional flag for custom ABI usage
/// * `from` - Optional address to simulate the call from
///
/// # Success Response
/// Returns a vector of read methods if successful
///
/// # Errors
/// * `400` - Invalid address hash or parameters
/// * `429` - Rate limit exceeded
/// * `500` - Server error
libs/blockscout-client/crate/src/apis/main_page_api.rs (2)

40-65: Consider enhancing error types for better error handling.

The implementation looks good and follows Rust best practices. However, consider extending the GetIndexingStatusError enum to include specific error cases instead of using just UnknownValue. This would provide better error handling and more informative error messages.

Example enhancement:

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum GetIndexingStatusError {
    InvalidResponse { message: String },
    ServiceUnavailable { reason: String },
    UnknownValue(serde_json::Value),
}

Line range hint 1-123: Consider adding unit tests for error scenarios.

While the implementation is solid, the file would benefit from unit tests covering various error scenarios, such as:

  • Network errors
  • Invalid responses
  • Server errors
  • Client errors

Would you like me to help generate unit tests for these scenarios?

libs/blockscout-client/crate/src/models/recaptcha_body.rs (1)

14-18: LGTM! Consider adding documentation for the struct.

The struct is well-defined with appropriate traits and serialization configuration. Consider adding documentation for the struct to explain its purpose and usage.

Add documentation above the struct definition:

 #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
+/// Represents a reCAPTCHA response body used in API requests.
 pub struct RecaptchaBody {
libs/blockscout-client/crate/src/models/transaction_summary_obj.rs (1)

14-18: LGTM! Consider adding documentation for the struct.

The struct is well-defined with appropriate traits and serialization configuration. The optional field with skip serialization is a good practice.

Add documentation above the struct definition:

 #[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
+/// Represents a collection of transaction summaries.
 pub struct TransactionSummaryObj {
libs/blockscout-client/crate/src/models/summary_variable.rs (1)

19-21: Fix inconsistent field documentation.

The documentation for the value field incorrectly states "Action Type" instead of describing the variable's value.

     #[serde(rename = "type")]
     pub r#type: String,
-    /// Action Type
+    /// Variable value
     #[serde(rename = "value")]
     pub value: String,
libs/blockscout-client/crate/src/models/summary_variable_token.rs (1)

14-21: LGTM! Well-structured token summary model.

The SummaryVariableToken struct is well-defined with appropriate serialization attributes and clear field definitions.

Consider adding a comment explaining why the raw identifier (r#type) is used to avoid confusion:

 /// Type
+/// Uses raw identifier to avoid conflict with Rust keyword 'type'
 #[serde(rename = "type")]
 pub r#type: String,
libs/blockscout-client/crate/src/models/summary_variable_currency.rs (1)

24-28: Consider adding validation in the constructor.

The constructor implementation is correct but could benefit from input validation.

Consider adding validation for empty strings:

 impl SummaryVariableCurrency {
     pub fn new(r#type: String, value: String) -> SummaryVariableCurrency {
+        assert!(!r#type.is_empty(), "type cannot be empty");
+        assert!(!value.is_empty(), "value cannot be empty");
         SummaryVariableCurrency { r#type, value }
     }
 }
libs/blockscout-client/crate/src/models/summary.rs (1)

16-20: Enhance field documentation for better clarity.

Consider adding more descriptive documentation for the fields to explain their purpose and usage:

-    /// Summary template
+    /// Template string containing placeholders that will be replaced with values from summary_template_variables
     #[serde(rename = "summary_template")]
     pub summary_template: String,
+    /// Variables used to populate the placeholders in the summary_template
     #[serde(rename = "summary_template_variables")]
     pub summary_template_variables: models::SummaryTemplateVariables,
libs/blockscout-client/crate/src/models/get_transaction_state_changes_200_response.rs (1)

19-19: Consider using a typed struct for pagination parameters.

Using serde_json::Value for next_page_params sacrifices type safety. Consider creating a dedicated struct for pagination parameters to provide better type safety and documentation.

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct PaginationParams {
    pub page_number: Option<u32>,
    pub page_size: Option<u32>,
    // Add other pagination fields as needed
}
libs/blockscout-client/crate/src/models/get_transaction_token_transfers_200_response.rs (1)

14-32: Consider introducing a generic paginated response type.

All response types follow the same pattern with items and next_page_params. Consider introducing a generic type to reduce code duplication:

#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize)]
pub struct PaginatedResponse<T> {
    pub items: Vec<T>,
    pub next_page_params: PaginationParams, // Use the suggested PaginationParams struct
}

impl<T> PaginatedResponse<T> {
    pub fn new(items: Vec<T>, next_page_params: PaginationParams) -> Self {
        Self {
            items,
            next_page_params,
        }
    }
}

// Usage example:
pub type GetTransactionStateChanges200Response = PaginatedResponse<models::StateChange>;
pub type GetAddressNftCollections200Response = PaginatedResponse<models::AddressNftCollection>;
pub type GetTransactionTokenTransfers200Response = PaginatedResponse<models::TokenTransfer>;
libs/blockscout-client/crate/src/apis/token_transfers_api.rs (1)

16-22: Consider adding error details to Status400 variant.

The Status400 variant could be enhanced by including error details to provide more context about the bad request.

 pub enum GetTokenTransfersError {
-    Status400(),
+    Status400(String),
     UnknownValue(serde_json::Value),
 }
libs/blockscout-client/swaggers/blockscout-api-v2.yaml (1)

2891-3030: Consider enhancing schema documentation.

While the NFT-related schemas are well-structured, consider adding:

  • Description fields for complex properties
  • Examples for NFT-specific fields
  • Documentation about the relationships between different NFT schemas
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bc6a29f and 33d601f.

📒 Files selected for processing (47)
  • libs/blockscout-client/crate/.openapi-generator/FILES (5 hunks)
  • libs/blockscout-client/crate/.openapi-generator/VERSION (1 hunks)
  • libs/blockscout-client/crate/src/apis/addresses_api.rs (8 hunks)
  • libs/blockscout-client/crate/src/apis/blocks_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/config_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/health_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/main_page_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/mod.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/search_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/smart_contracts_api.rs (6 hunks)
  • libs/blockscout-client/crate/src/apis/stats_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/token_transfers_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/apis/tokens_api.rs (5 hunks)
  • libs/blockscout-client/crate/src/apis/transactions_api.rs (3 hunks)
  • libs/blockscout-client/crate/src/apis/withdrawals_api.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/address.rs (2 hunks)
  • libs/blockscout-client/crate/src/models/address_nft_collection.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/address_nft_instance.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/address_nft_instance_collection.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/address_with_tx_count.rs (3 hunks)
  • libs/blockscout-client/crate/src/models/get_address_nft_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/get_address_nft_collections_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/get_transaction_internal_txs_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/get_transaction_logs_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/get_transaction_state_changes_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/get_transaction_token_transfers_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/indexing_status.rs (2 hunks)
  • libs/blockscout-client/crate/src/models/log.rs (3 hunks)
  • libs/blockscout-client/crate/src/models/mod.rs (6 hunks)
  • libs/blockscout-client/crate/src/models/recaptcha_body.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/refetch_token_instance_metadata_200_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/refetch_token_instance_metadata_403_response.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/search_result_transaction.rs (2 hunks)
  • libs/blockscout-client/crate/src/models/summary.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/summary_template_variables.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/summary_variable.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/summary_variable_currency.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/summary_variable_token.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/token_address_param.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/token_info_detailed.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/token_transfer.rs (3 hunks)
  • libs/blockscout-client/crate/src/models/transaction_chart_item.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/transaction_summary.rs (1 hunks)
  • libs/blockscout-client/crate/src/models/transaction_summary_obj.rs (1 hunks)
  • libs/blockscout-client/crate/tests/it_works.rs (1 hunks)
  • libs/blockscout-client/swaggers/blockscout-api-v2.yaml (48 hunks)
  • libs/blockscout-client/swaggers/blockscout-api.yaml (48 hunks)
✅ Files skipped from review due to trivial changes (1)
  • libs/blockscout-client/crate/.openapi-generator/VERSION
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Unit, doc and integration tests
🔇 Additional comments (64)
libs/blockscout-client/crate/tests/it_works.rs (1)

45-45: LGTM! Method name change aligns with the new naming convention.

The update from get_internal_txs to get_transaction_internal_txs improves clarity and consistency.

libs/blockscout-client/crate/src/apis/search_api.rs (2)

72-100: LGTM! Consider applying the same error handling enhancement.

The changes maintain consistency with the search function. Consider applying the same error handling improvement suggested above.


Line range hint 1-100: Great job on maintaining code quality and consistency!

The code demonstrates excellent Rust practices with proper error typing, clear documentation, and consistent patterns across functions. The refactoring aligns well with the broader effort to improve the BlockScout client library.

libs/blockscout-client/crate/src/apis/health_api.rs (3)

27-28: LGTM! Clean request initialization.

The request initialization is well-structured, using direct configuration access and proper string formatting.


30-31: LGTM! Proper optional header handling.

The user agent header is set correctly using the builder pattern with proper handling of the optional value.


34-37: LGTM! Clean request execution flow.

The request building, execution, and status handling follow Rust async best practices with proper error propagation.

libs/blockscout-client/crate/src/apis/stats_api.rs (3)

40-62: LGTM! Clean and consistent implementation.

The request handling and error management are well-structured, following Rust best practices.


69-91: LGTM! Clean and consistent implementation.

The request handling and error management are well-structured, following Rust best practices.


Line range hint 1-123: Well-structured OpenAPI generated code with robust error handling.

The implementation follows consistent patterns and Rust best practices throughout the file. The error handling is robust, with proper type definitions and consistent error management patterns across all functions.

libs/blockscout-client/crate/src/apis/smart_contracts_api.rs (2)

85-88: LGTM! Consistent parameter prefixing improves code clarity.

The addition of 'p_' prefixes to parameters is a good practice that:

  • Prevents potential name collisions in generated code
  • Makes parameter usage more explicit and traceable
  • Is consistently applied across all functions

Also applies to: 132-135, 177-178, 215-217, 288-290, 330-332, 372-374


107-122: LGTM! Robust and consistent error handling pattern.

The error handling implementation:

  • Properly distinguishes between client and server errors
  • Consistently handles response deserialization
  • Uses appropriate error types for each endpoint
  • Maintains proper error context in responses

Also applies to: 154-169, 191-206, 232-247, 264-279, 306-321, 348-363, 390-405

libs/blockscout-client/crate/src/models/address.rs (2)

21-25: LGTM! Field renaming improves API consistency.

The renaming from creation_tx_hash to creation_transaction_hash aligns with the standardized naming convention across the API, making the interface more consistent and clearer.


115-115: LGTM! Constructor updated correctly.

The constructor has been properly updated to initialize the renamed field while maintaining the same initialization logic.

libs/blockscout-client/crate/src/apis/main_page_api.rs (2)

101-123: LGTM!

The implementation is clean, consistent with other functions, and follows good error handling practices.


72-94: Function name doesn't match its return type.

The function name get_main_page_tokens suggests it returns tokens, but it actually returns a Vec<models::Block>. This mismatch could lead to confusion. Consider either:

  1. Renaming the function to get_main_page_blocks to match its return type, or
  2. Updating the return type if the function is meant to return tokens.

Let's verify the intended behavior by checking the OpenAPI spec:

libs/blockscout-client/crate/src/models/transaction_chart_item.rs (1)

18-19: LGTM! Field renaming improves clarity.

The renaming from tx_count to transaction_count improves readability and maintains consistency with the API's naming conventions.

Also applies to: 23-27

libs/blockscout-client/crate/src/models/transaction_summary.rs (2)

14-20: LGTM! Well-structured model with appropriate traits.

The TransactionSummary struct is well-defined with clear field names and appropriate serialization attributes.


22-26: LGTM! Constructor follows Rust conventions.

The new constructor method is implemented correctly using Rust's idiomatic field initialization shorthand.

libs/blockscout-client/crate/src/models/refetch_token_instance_metadata_403_response.rs (2)

14-18: LGTM! Well-structured error response model.

The RefetchTokenInstanceMetadata403Response struct is well-defined with appropriate serialization attributes and proper handling of the optional message field.


20-24: LGTM! Constructor follows Rust conventions.

The new constructor method is implemented correctly, initializing the optional message field to None.

libs/blockscout-client/crate/src/models/refetch_token_instance_metadata_200_response.rs (2)

14-18: LGTM! Well-structured success response model.

The RefetchTokenInstanceMetadata200Response struct is well-defined with appropriate serialization attributes and proper handling of the optional message field. The consistent structure with the 403 response model is a plus.


20-24: LGTM! Constructor follows Rust conventions.

The new constructor method is implemented correctly, initializing the optional message field to None.

libs/blockscout-client/crate/src/models/summary_variable_token.rs (1)

23-27: LGTM! Constructor follows Rust conventions.

The new constructor method is implemented correctly using Rust's idiomatic field initialization shorthand.

libs/blockscout-client/crate/src/models/summary_variable_currency.rs (1)

14-22: LGTM! Well-structured struct definition with proper documentation.

The struct is well-defined with appropriate field types and serde attributes.

libs/blockscout-client/crate/src/models/get_transaction_logs_200_response.rs (2)

14-20: LGTM! Well-structured response type.

The struct is well-defined with appropriate field types and serde attributes.


22-32: LGTM! Clean constructor implementation.

The constructor implementation is straightforward and correct.

libs/blockscout-client/crate/src/models/get_address_nft_200_response.rs (2)

14-20: LGTM! Well-structured response type for NFT data.

The struct is well-defined with appropriate field types and serde attributes.


22-32: LGTM! Clean constructor implementation.

The constructor implementation is straightforward and correct.

libs/blockscout-client/crate/src/models/search_result_transaction.rs (1)

18-19: Verify the impact of renaming tx_hash to transaction_hash.

The renaming is consistent with the API changes, but we should verify all usages are updated.

Let's verify that all occurrences of tx_hash have been updated:

Also applies to: 29-29, 35-35

libs/blockscout-client/crate/src/models/get_address_nft_collections_200_response.rs (1)

19-19: Consider using typed pagination parameters.

Similar to the transaction state changes response, consider using a typed struct for pagination parameters instead of serde_json::Value.

libs/blockscout-client/crate/src/models/get_transaction_token_transfers_200_response.rs (1)

19-19: Consider using typed pagination parameters.

Similar to other response types, consider using a typed struct for pagination parameters instead of serde_json::Value.

libs/blockscout-client/crate/src/models/get_transaction_internal_txs_200_response.rs (1)

14-32: LGTM!

The struct is well-designed with proper derive macros, serde attributes, and a constructor method. The implementation follows Rust best practices.

libs/blockscout-client/crate/src/models/address_nft_collection.rs (1)

14-35: LGTM!

The struct is well-designed with proper derive macros, serde attributes, and a constructor method. The implementation follows Rust best practices, including proper handling of optional fields.

libs/blockscout-client/crate/src/models/summary_template_variables.rs (1)

14-36: LGTM!

The struct is well-designed with proper derive macros, serde attributes, and a constructor method. The implementation follows Rust best practices.

libs/blockscout-client/crate/src/models/indexing_status.rs (1)

Line range hint 14-38: LGTM!

The changes improve the struct by:

  • Replacing the derive_new macro with a manual constructor that properly initializes optional fields
  • Making ratio fields optional strings for better flexibility
libs/blockscout-client/crate/src/models/log.rs (1)

32-33: LGTM! Field renaming improves clarity.

The renaming from tx_hash to transaction_hash is consistent with the latest swagger specification and improves clarity by using a more descriptive name.

Also applies to: 44-44, 55-55

libs/blockscout-client/crate/src/models/token_transfer.rs (1)

32-33: LGTM! Field renaming maintains consistency.

The renaming from tx_hash to transaction_hash maintains consistency with other models and improves clarity.

Also applies to: 48-48, 60-60

libs/blockscout-client/crate/src/apis/withdrawals_api.rs (1)

26-48: LGTM! Code refactoring improves clarity.

The refactoring simplifies request handling by removing redundant variables while maintaining the same functionality.

libs/blockscout-client/crate/src/apis/config_api.rs (1)

26-48: LGTM! Code refactoring maintains consistency.

The refactoring follows the same pattern as other API files, improving code clarity while maintaining consistent error handling.

libs/blockscout-client/crate/src/apis/mod.rs (1)

111-111: LGTM!

The new token_transfers_api module is correctly added and follows the alphabetical ordering convention.

libs/blockscout-client/crate/src/models/address_with_tx_count.rs (1)

21-25: LGTM!

The field renames from tx_hash to transaction_hash and tx_count to transaction_count improve clarity and maintain consistency across the codebase. The constructor has been correctly updated to match these changes.

Also applies to: 109-110, 114-143

libs/blockscout-client/crate/src/apis/blocks_api.rs (1)

52-191: LGTM!

The changes improve code clarity and maintainability through:

  • Clear parameter prefixing to prevent name collisions
  • Simplified request building
  • More concise error handling
libs/blockscout-client/crate/src/models/mod.rs (1)

5-10: LGTM! Well-organized module declarations.

The new module declarations and re-exports are well-structured and follow a consistent pattern. The changes enhance the library's capabilities by adding support for NFT collections, transaction summaries, and token metadata.

Also applies to: 53-56, 185-194, 197-198, 205-206, 235-238

libs/blockscout-client/crate/src/apis/transactions_api.rs (3)

16-54: LGTM! Improved error handling enums.

The error enums have been renamed to be more descriptive and consistent, following the pattern GetTransaction*Error. This improves code clarity and maintainability.


228-263: LGTM! Well-implemented transaction summary endpoint.

The new get_transaction_summary endpoint follows best practices for error handling and request building. The implementation is consistent with other endpoints in the file.


265-304: LGTM! Well-structured token transfers endpoint.

The new get_transaction_token_transfers endpoint properly handles optional query parameters and follows the established error handling pattern.

libs/blockscout-client/crate/src/apis/tokens_api.rs (2)

96-102: LGTM! Enhanced error handling for metadata refetching.

The new RefetchTokenInstanceMetadataError enum properly handles the 403 status code with a specific response model, improving error handling granularity.


491-520: LGTM! Consistent parameter handling.

The implementation uses prefixed variables to prevent name collisions and follows the established pattern for request building and error handling.

libs/blockscout-client/crate/src/apis/addresses_api.rs (3)

72-86: LGTM! Well-structured error handling for NFT endpoints.

The new error enums for NFT-related endpoints follow the established pattern and properly handle error cases.


403-443: LGTM! Well-implemented NFT endpoint.

The new get_address_nft endpoint properly handles optional type filtering and follows consistent patterns for request building and error handling.


445-483: LGTM! Well-structured NFT collections endpoint.

The new get_address_nft_collections endpoint follows the same patterns as other endpoints, maintaining consistency in the codebase.

libs/blockscout-client/swaggers/blockscout-api-v2.yaml (3)

165-192: Well-designed REST API endpoints for NFT and token operations!

The new endpoints follow REST conventions and maintain consistency with the existing API design:

  • Clear resource paths using kebab-case
  • Proper use of HTTP methods
  • Consistent parameter naming
  • Proper pagination support

Also applies to: 952-1022


468-484: Excellent template-based design for transaction summaries!

The transaction summary implementation:

  • Uses a flexible template system for different transaction types
  • Provides structured variables for template substitution
  • Maintains type safety through schema definitions

Also applies to: 2292-2380


59-59: Consistent parameter naming improvements.

The renaming of tx_hash to transaction_hash across the API:

  • Improves clarity by avoiding abbreviations
  • Maintains consistency in parameter naming
  • Updates all related examples and descriptions

Also applies to: 1765-1792, 1934-1971

libs/blockscout-client/swaggers/blockscout-api.yaml (9)

61-61: LGTM! Consistent field renaming improves clarity.

The renaming of tx_hash to transaction_hash across multiple schemas improves consistency and readability. The change is applied uniformly throughout the specification.

Also applies to: 1746-1746, 1773-1773, 1915-1915, 1952-1952, 3831-3831, 3877-3877, 3921-3921


167-194: LGTM! Well-designed token transfers endpoint.

The new /api/v2/token-transfers endpoint follows REST conventions and includes proper pagination support through next_page_params.


954-989: LGTM! Comprehensive NFT listing endpoint.

The /api/v2/addresses/{address_hash}/nft endpoint provides a well-structured way to retrieve NFTs owned by an address, with support for filtering by token type (ERC-721, ERC-404, ERC-1155).


990-1024: LGTM! NFT collections endpoint provides useful grouping.

The /api/v2/addresses/{address_hash}/nft/collections endpoint efficiently groups NFTs by collection, improving the API's usability for NFT-focused applications.


470-486: LGTM! Transaction summary endpoint enhances user experience.

The /api/v2/transactions/{transaction_hash}/summary endpoint provides human-readable transaction summaries, making the API more user-friendly.


2872-2934: LGTM! Well-structured NFT instance schema.

The AddressNFTInstance schema provides comprehensive NFT metadata support, including:

  • Token type and value
  • Media URLs (image, animation)
  • External app integration
  • Rich metadata attributes

2998-3011: LGTM! NFT collection schema enables efficient grouping.

The AddressNFTCollection schema efficiently groups NFT instances while maintaining all necessary metadata.


2273-2304: LGTM! Transaction summary schema enhances readability.

The TransactionSummary schema with template-based summaries provides a flexible way to generate human-readable transaction descriptions.


1297-1338: LGTM! Added reCAPTCHA protection for metadata refresh.

The metadata refresh endpoint properly implements reCAPTCHA validation with:

  • Required reCAPTCHA response field
  • Appropriate error responses (403 for invalid reCAPTCHA)
  • Clear error messages

Also applies to: 3424-3430

libs/blockscout-client/crate/.openapi-generator/FILES (1)

Line range hint 1-130: LGTM! The file structure changes align with the PR objectives.

The additions enhance the BlockScout client with NFT support, token transfers, transaction summaries, and improved security features.

Let's verify the OpenAPI spec version and compatibility:

✅ Verification successful

OpenAPI specs and generated files are properly aligned

The generated files in .openapi-generator/FILES correctly reflect the model definitions from the OpenAPI specs (v1, v2, and main). All new models (NFT collections, token transfers, transaction summaries) are properly defined in the specs and have corresponding Rust implementations.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check OpenAPI spec version and compatibility

# Look for OpenAPI version in spec files
echo "OpenAPI Spec Version:"
fd -e yaml -e json . --exec grep -l "openapi:" {} \; --exec grep "openapi:" {} \;

# Check for any potential breaking changes in the spec
echo -e "\nBreaking Changes Check:"
fd -e yaml -e json . --exec grep -l "^  version:" {} \; --exec grep "^  version:" {} \;

Length of output: 1831


Script:

#!/bin/bash
# Description: Verify OpenAPI spec changes match generated files

# Extract model definitions from specs
echo "=== Model Definitions in Specs ==="
for spec in $(fd -e yaml . libs/blockscout-client/swaggers/); do
  echo "=== $spec ==="
  # Extract model names from components/schemas section
  yq '.components.schemas | keys' "$spec" 2>/dev/null || true
done

# Compare with generated files
echo -e "\n=== Generated Model Files ==="
fd -t f . libs/blockscout-client/crate/src/models/ -x basename {} \;

# Check for new endpoints
echo -e "\n=== API Endpoints ==="
for spec in $(fd -e yaml . libs/blockscout-client/swaggers/); do
  echo "=== $spec ==="
  # Extract paths (endpoints)
  yq '.paths | keys' "$spec" 2>/dev/null || true
done

Length of output: 5502


Script:

#!/bin/bash
# Description: Verify OpenAPI specs content

# Check spec file contents
for spec in $(fd -e yaml . libs/blockscout-client/swaggers/); do
  echo "=== $spec ==="
  echo "First 20 lines:"
  head -n 20 "$spec"
  echo -e "\nSearching for new model definitions..."
  grep -A 5 "NFTCollection\|TokenTransfer\|TransactionSummary" "$spec" || true
  echo -e "\n---\n"
done

Length of output: 10431

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