Skip to content

Feat/add missing explorer endpoints #369

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

Merged
merged 11 commits into from
Jan 23, 2025
Merged

Conversation

aarmoa
Copy link
Collaborator

@aarmoa aarmoa commented Jan 22, 2025

  • Added support for all Indexer Explorer endpoints. Added example scripts for the new supported endpoints.
  • Removed old deprecated functions from Composer and AsyncClient
  • Removed the deprecation tests no longer required

Summary by CodeRabbit

Based on the comprehensive summary, here are the updated release notes:

  • New Features

    • Added new example scripts for interacting with Injective Protocol's API, including:
      • Contract transaction retrieval
      • Validator information fetching
      • WebAssembly (WASM) contract and code exploration
      • CW20 token balance checking
      • Relayer and bank transfer querying
  • Improvements

    • Refactored AsyncClient with more consistent method naming (from get_* to fetch_*)
    • Enhanced pagination and parameter handling in API methods
    • Improved type precision for financial calculations
    • Streamlined method signatures across the library
  • Breaking Changes

    • Deprecated several methods in AsyncClient and Composer classes
    • Removed some legacy method signatures
    • Updated method parameters and return types
  • Deprecation Notices

    • Old method names like get_tx, get_account, etc., are now deprecated
    • Recommended to use new fetch_* methods instead

These release notes provide a high-level overview of the significant changes in the library while maintaining user confidentiality about internal implementation details.

Copy link
Contributor

coderabbitai bot commented Jan 22, 2025

Walkthrough

This pull request introduces multiple new example scripts and significant updates to the Injective Protocol's Python client library. The changes primarily focus on expanding the explorer RPC examples, refactoring the AsyncClient and Composer classes, and standardizing method naming conventions. The updates include new methods for fetching contract transactions, validators, WASM codes, and other blockchain-related data, with an emphasis on improving API consistency and usability.

Changes

File Change Summary
examples/exchange_client/explorer_rpc/11_GetContractsTxsV2.py New script to fetch contract transactions with pagination and time range support
examples/exchange_client/explorer_rpc/12_GetValidators.py New script to retrieve and display blockchain validators
examples/exchange_client/explorer_rpc/13_GetValidator.py New script to fetch details for a specific validator
examples/exchange_client/explorer_rpc/14_GetValidatorUptime.py New script to retrieve a validator's uptime
examples/exchange_client/explorer_rpc/15_GetWasmCodes.py New script to fetch WebAssembly codes with pagination
examples/exchange_client/explorer_rpc/16_GetWasmCodeById.py New script to retrieve a specific WASM code by ID
examples/exchange_client/explorer_rpc/17_GetWasmContracts.py New script to fetch WASM contracts with filtering options
examples/exchange_client/explorer_rpc/18_GetWasmContractByAddress.py New script to retrieve a WASM contract by its address
examples/exchange_client/explorer_rpc/19_GetCw20Balance.py New script to fetch CW20 token balance
examples/exchange_client/explorer_rpc/20_Relayers.py New script to retrieve blockchain relayers
examples/exchange_client/explorer_rpc/21_GetBankTransfers.py New script to fetch bank transfers with pagination
pyinjective/async_client.py Major refactoring of method names, replacing get_* methods with fetch_* methods
pyinjective/composer.py Deprecated methods replaced with new methods using msg_ prefix
pyinjective/client/indexer/grpc/indexer_grpc_explorer_api.py New method fetch_contract_txs_v2 added; pagination handling refined in existing methods
tests/client/indexer/configurable_explorer_query_servicer.py New attribute and method for handling contract transactions responses
tests/client/indexer/grpc/test_indexer_grpc_explorer_api.py New test method for fetch_contract_txs_v2; pagination logic standardized in tests
tests/test_async_client_deprecation_warnings.py Removed various imports and fixture definitions related to deprecated services
tests/test_composer_deprecation_warnings.py Entire file removed; previously tested deprecation warnings for Composer methods
.github/workflows/run-tests.yml Updated job matrix for testing environments

Poem

🐰 Hop, hop, through the blockchain's maze,
New methods bloom like springtime days!
From contracts to validators' might,
Our library dances with pure delight 🌟
CodeRabbit's magic, swift and bright! 🚀


🪧 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.

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: 4

🧹 Nitpick comments (26)
examples/exchange_client/explorer_rpc/14_GetValidatorUptime.py (3)

7-12: Add docstring and consider making network configurable.

Consider these improvements for better documentation and flexibility:

  1. Add a docstring explaining the purpose and usage of the script
  2. Consider using environment variables or command-line arguments to make the network selection configurable
 async def main():
+    """
+    Example script demonstrating how to fetch validator uptime using the AsyncClient.
+    
+    This script connects to the Injective network and retrieves uptime information
+    for a specified validator address.
+    """
+    # Get network from environment variable or default to testnet
+    network_name = os.getenv("NETWORK", "testnet")
+    network = getattr(Network, network_name)()
-    # Select network: choose between testnet, mainnet, or local
-    network = Network.testnet()

13-18: Document validator address format and add validation.

The validator address is hardcoded without format validation or documentation. Consider:

  1. Adding a comment explaining the expected address format
  2. Adding basic validation for the address format
  3. Making the address configurable via environment variables
+    # Validator address in bech32 format with 'injvaloper' prefix
+    address = os.getenv("VALIDATOR_ADDRESS", "injvaloper1kk523rsm9pey740cx4plalp40009ncs0wrchfe")
+    
+    # Validate address format
+    if not address.startswith("injvaloper"):
+        raise ValueError("Invalid validator address format. Must start with 'injvaloper'")
-    address = "injvaloper1kk523rsm9pey740cx4plalp40009ncs0wrchfe"

15-24: Enhance error handling and output formatting.

The current error handling and output could be improved:

  1. Catch specific exceptions instead of generic Exception
  2. Use structured output format (e.g., JSON) for better readability
  3. Consider using logging instead of print statements
+    import json
+    import logging
+    
+    logging.basicConfig(level=logging.INFO)
+    logger = logging.getLogger(__name__)
+
     try:
         # Fetch validator uptime
         uptime = await client.fetch_validator_uptime(address=address)
 
         # Print uptime
-        print("Validator uptime:")
-        print(uptime)
+        logger.info("Validator uptime: %s", json.dumps(uptime, indent=2))
 
-    except Exception as e:
-        print(f"Error: {e}")
+    except ValueError as e:
+        logger.error("Invalid input: %s", e)
+    except ConnectionError as e:
+        logger.error("Network error: %s", e)
+    except Exception as e:
+        logger.error("Unexpected error: %s", e)
pyinjective/async_client.py (1)

1124-1125: Use keyword argument for clarity in fetch_validator

For consistency and improved readability, consider specifying the address parameter as a keyword argument when calling fetch_validator.

Apply this diff to make the change:

-        return await self.exchange_explorer_api.fetch_validator(address)
+        return await self.exchange_explorer_api.fetch_validator(address=address)
examples/exchange_client/explorer_rpc/16_GetWasmCodeById.py (1)

9-9: Remove redundant commented-out code

The commented-out line # network: Network = Network.testnet() is unnecessary and can be removed to keep the code clean and maintainable.

Apply this diff:

-    # network: Network = Network.testnet()
examples/exchange_client/explorer_rpc/19_GetCw20Balance.py (1)

9-9: Eliminate unnecessary commented-out code

The commented-out line # network: Network = Network.testnet() serves no purpose and should be removed to improve code readability.

Apply this diff:

-    # network: Network = Network.testnet()
examples/exchange_client/explorer_rpc/18_GetWasmContractByAddress.py (2)

9-10: Remove duplicate comment line.

Line 9 is a duplicate of line 10's network initialization comment.

-    # network: Network = Network.testnet()
     network: Network = Network.testnet()

11-13: Add type hints and docstring.

Add type hints for better code maintainability and a docstring explaining the script's purpose.

 async def main() -> None:
+    """Fetch and display WASM contract details for a specific address on testnet."""
     network: Network = Network.testnet()
-    client: AsyncClient = AsyncClient(network)
+    client: AsyncClient = AsyncClient(network)
 
-    address = "inj1yhz4e7df95908jhs9erl87vdzjkdsc24q7afjf"
+    address: str = "inj1yhz4e7df95908jhs9erl87vdzjkdsc24q7afjf"
examples/exchange_client/explorer_rpc/20_Relayers.py (1)

7-7: Add return type hint and docstring.

Add return type hint and docstring for better code documentation.

-async def main():
+async def main() -> None:
+    """Fetch and display all relayers on testnet."""
examples/exchange_client/explorer_rpc/12_GetValidators.py (2)

7-7: Add return type hint and docstring.

Add return type hint and docstring for better code documentation.

-async def main():
+async def main() -> None:
+    """Fetch and display all validators on testnet."""

14-21: Consider handling pagination.

The fetch_validators call might return paginated results. Consider handling pagination for large result sets.

     try:
-        # Fetch validators
-        validators = await client.fetch_validators()
-
-        # Print validators
-        print("Validators:")
-        print(validators)
+        # Fetch validators with pagination
+        page = 1
+        while True:
+            validators = await client.fetch_validators(page=page)
+            if not validators:
+                break
+            print(f"Validators (Page {page}):")
+            print(validators)
+            page += 1
examples/exchange_client/explorer_rpc/13_GetValidator.py (4)

7-7: Add return type hint and docstring.

Add return type hint and docstring for better code documentation.

-async def main():
+async def main() -> None:
+    """Fetch and display details for a specific validator on testnet."""

13-13: Add comment explaining the hardcoded address.

Add a comment explaining what this validator address represents.

+    # Example validator address - replace with your target validator
     address = "injvaloper1kk523rsm9pey740cx4plalp40009ncs0wrchfe"

19-21: Fix comment in print statement.

The comment mentions "validators" (plural) but we're printing a single validator.

-        # Print validators
+        # Print validator details
         print("Validator:")
         print(validator)

1-28: Consider implementing shared utilities for example scripts.

All example scripts follow similar patterns and could benefit from shared utilities:

  1. A common configuration module for network selection
  2. Shared error handling and logging setup
  3. Documentation templates
  4. Command-line argument parsing for addresses and other parameters

This would improve maintainability and consistency across examples.

Would you like me to provide an example implementation of these shared utilities?

examples/exchange_client/explorer_rpc/15_GetWasmCodes.py (3)

10-11: Remove duplicate network initialization comment.

Remove the commented out line as it's redundant with the line below it.

-    # network: Network = Network.testnet()
     network: Network = Network.testnet()

20-24: Add error handling and improve response formatting.

The API call should be wrapped in a try-except block, and the response should be properly formatted for better readability.

-    wasm_codes = await client.fetch_wasm_codes(
-        pagination=pagination,
-    )
-    print("Wasm codes:")
-    print(wasm_codes)
+    try:
+        wasm_codes = await client.fetch_wasm_codes(
+            pagination=pagination,
+        )
+        print("Wasm codes:")
+        print(json.dumps(wasm_codes, indent=2))
+    except Exception as e:
+        print(f"Error fetching wasm codes: {e}")

1-29: Add docstring and comments explaining the example's purpose.

The script would benefit from documentation explaining its purpose and the expected output format.

Add a docstring at the beginning of the file:

"""
Example script demonstrating how to fetch WebAssembly (Wasm) codes from the Injective blockchain.
This example shows how to:
1. Initialize a testnet client
2. Set up pagination parameters
3. Fetch Wasm codes within a specific range
"""
examples/exchange_client/explorer_rpc/21_GetBankTransfers.py (3)

11-12: Remove duplicate network initialization comment.

Remove the commented out line as it's redundant with the line below it.

-    # network: Network = Network.testnet()
     network: Network = Network.testnet()

16-16: Add comment explaining the sender address.

The hardcoded sender address should be documented for clarity.

-    senders = ["inj17xpfvakm2amg962yls6f84z3kell8c5l6s5ye9"]
+    # Example sender address - replace with actual address when using
+    senders = ["inj17xpfvakm2amg962yls6f84z3kell8c5l6s5ye9"]

18-20: Add error handling around the API call.

The API call should be wrapped in a try-except block for better error handling.

-    bank_transfers = await client.fetch_bank_transfers(senders=senders, pagination=pagination)
-    print("Bank transfers:")
-    print(json.dumps(bank_transfers, indent=2))
+    try:
+        bank_transfers = await client.fetch_bank_transfers(senders=senders, pagination=pagination)
+        print("Bank transfers:")
+        print(json.dumps(bank_transfers, indent=2))
+    except Exception as e:
+        print(f"Error fetching bank transfers: {e}")
examples/exchange_client/explorer_rpc/17_GetWasmContracts.py (2)

10-11: Remove duplicate network initialization comment.

Remove the commented out line as it's redundant with the line below it.

-    # network: Network = Network.testnet()
     network: Network = Network.testnet()

20-25: Add error handling and improve response formatting.

The API call should be wrapped in a try-except block, and the response should be properly formatted. Also, add documentation for the assets_only parameter.

+    # Filter to only return contracts that represent assets (e.g., tokens)
     wasm_contracts = await client.fetch_wasm_contracts(
         assets_only=True,
         pagination=pagination,
     )
-    print("Wasm contracts:")
-    print(wasm_contracts)
+    try:
+        wasm_contracts = await client.fetch_wasm_contracts(
+            assets_only=True,  # Only return contracts that represent assets
+            pagination=pagination,
+        )
+        print("Wasm contracts:")
+        print(json.dumps(wasm_contracts, indent=2))
+    except Exception as e:
+        print(f"Error fetching wasm contracts: {e}")
examples/exchange_client/explorer_rpc/11_GetContractsTxsV2.py (3)

18-18: Add comment explaining the contract address and its purpose.

The hardcoded contract address should be documented for clarity.

-        address = "inj1ady3s7whq30l4fx8sj3x6muv5mx4dfdlcpv8n7"  # Replace with actual contract address
+        # Example contract address for demonstration
+        # This address represents a smart contract deployed on the testnet
+        # Replace with an actual contract address when using
+        address = "inj1ady3s7whq30l4fx8sj3x6muv5mx4dfdlcpv8n7"

28-28: Document the significance of the block height parameter.

The hardcoded block height should be explained for better understanding.

-        response = await client.fetch_contract_txs_v2(address=address, height=60_000_000, pagination=pagination)
+        # Fetch transactions after block height 60,000,000
+        # Adjust this value based on your needs - higher values mean more recent transactions
+        response = await client.fetch_contract_txs_v2(
+            address=address,
+            height=60_000_000,  # Example block height threshold
+            pagination=pagination
+        )

1-47: Add docstring explaining the example's purpose and functionality.

The script would benefit from comprehensive documentation.

Add a docstring at the beginning of the file:

"""
Example script demonstrating how to fetch smart contract transactions using the V2 API.

This example shows how to:
1. Initialize a testnet client
2. Set up time-based pagination
3. Fetch transactions for a specific contract after a given block height
4. Process and display transaction details

The script includes error handling and formats the output for better readability.
"""
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 302f09b and 1719ef5.

📒 Files selected for processing (18)
  • examples/exchange_client/explorer_rpc/11_GetContractsTxsV2.py (1 hunks)
  • examples/exchange_client/explorer_rpc/12_GetValidators.py (1 hunks)
  • examples/exchange_client/explorer_rpc/13_GetValidator.py (1 hunks)
  • examples/exchange_client/explorer_rpc/14_GetValidatorUptime.py (1 hunks)
  • examples/exchange_client/explorer_rpc/15_GetWasmCodes.py (1 hunks)
  • examples/exchange_client/explorer_rpc/16_GetWasmCodeById.py (1 hunks)
  • examples/exchange_client/explorer_rpc/17_GetWasmContracts.py (1 hunks)
  • examples/exchange_client/explorer_rpc/18_GetWasmContractByAddress.py (1 hunks)
  • examples/exchange_client/explorer_rpc/19_GetCw20Balance.py (1 hunks)
  • examples/exchange_client/explorer_rpc/20_Relayers.py (1 hunks)
  • examples/exchange_client/explorer_rpc/21_GetBankTransfers.py (1 hunks)
  • pyinjective/async_client.py (5 hunks)
  • pyinjective/client/indexer/grpc/indexer_grpc_explorer_api.py (3 hunks)
  • pyinjective/composer.py (0 hunks)
  • tests/client/indexer/configurable_explorer_query_servicer.py (2 hunks)
  • tests/client/indexer/grpc/test_indexer_grpc_explorer_api.py (3 hunks)
  • tests/test_async_client_deprecation_warnings.py (0 hunks)
  • tests/test_composer_deprecation_warnings.py (0 hunks)
💤 Files with no reviewable changes (3)
  • tests/test_composer_deprecation_warnings.py
  • tests/test_async_client_deprecation_warnings.py
  • pyinjective/composer.py
🧰 Additional context used
🪛 Gitleaks (8.21.2)
tests/client/indexer/grpc/test_indexer_grpc_explorer_api.py

329-329: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: run-tests (3.11, windows-latest)
  • GitHub Check: run-tests (3.10, windows-latest)
  • GitHub Check: run-tests (3.9, windows-latest)
🔇 Additional comments (11)
examples/exchange_client/explorer_rpc/14_GetValidatorUptime.py (1)

1-5: LGTM! Clean and well-organized imports.

The imports are properly structured and include all necessary dependencies for async operations.

pyinjective/async_client.py (3)

1090-1101: Method fetch_contract_txs_v2 added correctly

The new method fetch_contract_txs_v2 appropriately wraps the underlying API call fetch_contract_txs_v2 from exchange_explorer_api. The parameters are correctly passed through, and the method signature aligns with the existing conventions in the AsyncClient class.


1115-1128: Methods for fetching validator information added appropriately

The addition of fetch_validators, fetch_validator, and fetch_validator_uptime methods expands the client's capabilities to retrieve validator data. The methods correctly call the corresponding endpoints in exchange_explorer_api, and parameters are properly handled.


1256-1279: ⚠️ Potential issue

Fix incorrect attribute reference in listen_derivative_positions_v2_updates

The method listen_derivative_positions_v2_updates references self.indexer_derivative_stream, which is not initialized in the AsyncClient class. The correct attribute should be self.exchange_derivative_stream_api.

Apply this diff to correct the attribute reference:

-        await self.indexer_derivative_stream.stream_positions_v2(
+        await self.exchange_derivative_stream_api.stream_positions_v2(

Likely invalid or redundant comment.

tests/client/indexer/configurable_explorer_query_servicer.py (2)

35-37: LGTM!

The new attribute follows the established pattern and naming convention of other response attributes in the class.


117-120: LGTM!

The new method follows the established pattern of other response methods in the class, maintaining consistency in the API.

pyinjective/client/indexer/grpc/indexer_grpc_explorer_api.py (2)

245-246: LGTM!

The changes improve API consistency by using the pagination object's attributes for handling pagination parameters.


274-275: LGTM!

The changes improve API consistency by using the pagination object's attributes for handling pagination parameters.

tests/client/indexer/grpc/test_indexer_grpc_explorer_api.py (3)

314-449: LGTM!

The test is well-structured and comprehensive, following the established pattern of other test methods. It properly validates the new contract transactions v2 functionality.

🧰 Tools
🪛 Gitleaks (8.21.2)

329-329: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


1261-1262: LGTM!

The test correctly validates the updated pagination handling using the PaginationOption object.


1407-1408: LGTM!

The test correctly validates the updated pagination handling using the PaginationOption object.

Comment on lines +27 to +28
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update to modern async execution pattern.

The current async execution pattern is deprecated. Use the modern pattern introduced in Python 3.7+:

 if __name__ == "__main__":
-    asyncio.get_event_loop().run_until_complete(main())
+    asyncio.run(main())
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if __name__ == "__main__":
asyncio.get_event_loop().run_until_complete(main())
if __name__ == "__main__":
asyncio.run(main())

Comment on lines +15 to +17
wasm_contract = await client.fetch_wasm_contract_by_address(address=address)
print("Wasm contract:")
print(wasm_contract)
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling and improve logging.

Add try-except block and improve logging for better error handling and debugging.

-    wasm_contract = await client.fetch_wasm_contract_by_address(address=address)
-    print("Wasm contract:")
-    print(wasm_contract)
+    try:
+        wasm_contract = await client.fetch_wasm_contract_by_address(address=address)
+        print("Wasm contract:")
+        print(wasm_contract)
+    except Exception as e:
+        logging.error(f"Failed to fetch WASM contract: {e}")
+        raise

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +16 to +20
validators = await client.fetch_relayers()

# Print relayers
print("Relayers:")
print(validators)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix variable name mismatch.

The variable name doesn't match its purpose (validators vs relayers).

-        validators = await client.fetch_relayers()
+        relayers = await client.fetch_relayers()
 
         # Print relayers
         print("Relayers:")
-        print(validators)
+        print(relayers)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
validators = await client.fetch_relayers()
# Print relayers
print("Relayers:")
print(validators)
relayers = await client.fetch_relayers()
# Print relayers
print("Relayers:")
print(relayers)

Comment on lines +71 to +93
async def fetch_contract_txs_v2(
self,
address: str,
height: Optional[int] = None,
token: Optional[str] = None,
pagination: Optional[PaginationOption] = None,
) -> Dict[str, Any]:
pagination = pagination or PaginationOption()
request = exchange_explorer_pb.GetContractTxsV2Request(
address=address,
token=token,
)
if height is not None:
request.height = height
if pagination is not None:
setattr(request, "from", pagination.start_time)
request.to = pagination.end_time
request.limit = pagination.limit

response = await self._execute_call(call=self._stub.GetContractTxsV2, request=request)

return response

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix the use of reserved keyword 'from'.

The code uses the reserved Python keyword 'from' as an attribute name on line 86, which could lead to syntax errors in some contexts.

Apply this diff to fix the issue:

-            setattr(request, "from", pagination.start_time)
+            setattr(request, "from_time", pagination.start_time)

Also ensure that the protobuf definition uses from_time instead of from for the field name.

Committable suggestion skipped: line range outside the PR's diff.

Copy link

socket-security bot commented Jan 22, 2025

New, updated, and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
pypi/[email protected] None 0 64.1 kB Zac-HD, adriangb
pypi/[email protected] 🔁 pypi/[email protected] None 0 4.93 MB jtraglia
pypi/[email protected] None 0 826 kB nedbatchelder

🚮 Removed packages: pypi/[email protected]

View full report↗︎

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: 1

🧹 Nitpick comments (1)
pyproject.toml (1)

49-53: Consider pinning formatter versions for consistency.

While using minimum version constraints (>=) is generally fine, it's recommended to pin exact versions for formatting tools (black, isort) to ensure consistent formatting across different development environments.

-isort = ">=5.12.0"
-black = ">=23.9.1"
+isort = "^5.12.0"
+black = "^23.9.1"
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9dece94 and 2803a59.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (1)
  • pyproject.toml (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: run-tests (3.11, windows-2019)
  • GitHub Check: run-tests (3.10, windows-2019)
  • GitHub Check: run-tests (3.9, windows-2019)
🔇 Additional comments (3)
pyproject.toml (3)

34-34: LGTM! Version constraint relaxation looks safe.

The change from ^5.26.1 to ^5.26 maintains compatibility while allowing patch updates.


45-46: LGTM! Test dependency updates look appropriate.

The change to minimum version constraints (>=) for test dependencies allows for easier updates while maintaining compatibility.


38-38: Verify compatibility with web3 v7.0.

The upgrade from web3 v6.0 to v7.0 is a major version change that may introduce breaking changes. Please ensure all web3 usage in the codebase is compatible with v7.0.

pyproject.toml Outdated
@@ -22,7 +22,7 @@ include = [

[tool.poetry.dependencies]
python = "^3.9"
aiohttp = "^3.9.4" # Version dependency due to https://github.com/InjectiveLabs/sdk-python/security/dependabot/18
aiohttp = "^3.9" # Version dependency due to https://github.com/InjectiveLabs/sdk-python/security/dependabot/18
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Codebase verification

Keep the version constraint as ^3.9.4 to prevent security vulnerabilities

Relaxing the version constraint to ^3.9 would allow versions < 3.9.4, which are vulnerable to:

  • High severity Denial of Service vulnerability
  • Moderate severity Cross-site Scripting vulnerability
🔗 Analysis chain

Verify security implications of the aiohttp version range.

The version constraint has been relaxed from a specific patch version to allow any 3.9.x version. Let's verify if this range is secure.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check for security advisories for aiohttp
gh api graphql -f query='
{
  securityVulnerabilities(first: 5, ecosystem: PIP, package: "aiohttp") {
    nodes {
      advisory {
        summary
        severity
        publishedAt
      }
      vulnerableVersionRange
      firstPatchedVersion {
        identifier
      }
    }
  }
}'

Length of output: 1618

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: 1

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cd9389 and 436f8f6.

⛔ Files ignored due to path filters (1)
  • poetry.lock is excluded by !**/*.lock
📒 Files selected for processing (2)
  • .github/workflows/run-tests.yml (3 hunks)
  • pyproject.toml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pyproject.toml
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/run-tests.yml

30-30: shellcheck reported issue in this script: SC2086:info:1:44: Double quote to prevent globbing and word splitting

(shellcheck)

⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: run-tests (3.11, windows-latest)
  • GitHub Check: run-tests (3.11, macos-latest)
  • GitHub Check: run-tests (3.10, windows-latest)
  • GitHub Check: run-tests (3.10, macos-latest)
  • GitHub Check: run-tests (3.9, windows-latest)
  • GitHub Check: run-tests (3.9, macos-latest)
🔇 Additional comments (2)
.github/workflows/run-tests.yml (2)

12-12: LGTM! Good practice using macos-latest.

Using macos-latest instead of a specific version ensures the workflow stays up-to-date with security patches and improvements.


45-45: LGTM! Enhanced test output will help with debugging.

The addition of -v and --full-trace options will provide more detailed output for debugging test failures. However, be aware that this might significantly increase the workflow logs.

Consider monitoring the workflow execution time and log size after this change. You can run this script to check recent workflow runs:

Comment on lines 28 to 30
- name: Set poetry installer config
if: runner.os == 'macOS'
run: echo "POETRY_INSTALLER_NO_BINARY=:all:" >> $GITHUB_ENV
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Fix potential word splitting in shell command.

The environment variable assignment should use quotes to prevent potential word splitting issues.

-        run: echo "POETRY_INSTALLER_NO_BINARY=:all:" >> $GITHUB_ENV
+        run: echo "POETRY_INSTALLER_NO_BINARY=':all:'" >> $GITHUB_ENV
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- name: Set poetry installer config
if: runner.os == 'macOS'
run: echo "POETRY_INSTALLER_NO_BINARY=:all:" >> $GITHUB_ENV
- name: Set poetry installer config
if: runner.os == 'macOS'
run: echo "POETRY_INSTALLER_NO_BINARY=':all:'" >> $GITHUB_ENV
🧰 Tools
🪛 actionlint (1.7.4)

30-30: shellcheck reported issue in this script: SC2086:info:1:44: Double quote to prevent globbing and word splitting

(shellcheck)

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: 0

♻️ Duplicate comments (1)
.github/workflows/run-tests.yml (1)

25-28: ⚠️ Potential issue

Fix potential word splitting in shell command.

The environment variable assignment should use quotes to prevent potential word splitting issues.

-        run: echo "ARCHFLAGS=-arch arm64" >> $GITHUB_ENV
+        run: echo "ARCHFLAGS='-arch arm64'" >> $GITHUB_ENV
🧰 Tools
🪛 actionlint (1.7.4)

27-27: shellcheck reported issue in this script: SC2086:info:1:33: Double quote to prevent globbing and word splitting

(shellcheck)

🧹 Nitpick comments (1)
.github/workflows/run-tests.yml (1)

45-45: Consider conditional verbose logging.

While verbose output and full stack traces are helpful for debugging, they can significantly increase log size in CI. Consider making these flags conditional:

-          poetry run pytest --cov --cov-report=xml -v --full-trace
+          if [ "$GITHUB_EVENT_NAME" = "pull_request" ]; then
+            poetry run pytest --cov --cov-report=xml -v --full-trace
+          else
+            poetry run pytest --cov --cov-report=xml
+          fi

This way, detailed logs are only generated for pull requests where they're most useful.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e2e76d9 and 5c5867a.

📒 Files selected for processing (1)
  • .github/workflows/run-tests.yml (3 hunks)
🧰 Additional context used
🪛 actionlint (1.7.4)
.github/workflows/run-tests.yml

27-27: shellcheck reported issue in this script: SC2086:info:1:33: Double quote to prevent globbing and word splitting

(shellcheck)

🔇 Additional comments (1)
.github/workflows/run-tests.yml (1)

12-12: Consider documenting the rationale for using macos-latest.

While using macos-latest automatically tracks the latest stable version, it could introduce unexpected behavior when GitHub Actions updates the macOS runner version. Consider documenting this decision and its potential impacts.

Run this script to check the current macOS runner version and available options:

@aarmoa aarmoa merged commit f7ba353 into dev Jan 23, 2025
12 checks passed
@aarmoa aarmoa deleted the feat/add_missing_explorer_endpoints branch January 23, 2025 03:09
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.

1 participant