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

572 write functions to call agents contract and fetch data #573

Merged

Conversation

gabrielfior
Copy link
Contributor

No description provided.

@gabrielfior gabrielfior linked an issue Dec 26, 2024 that may be closed by this pull request
Copy link

coderabbitai bot commented Dec 26, 2024

Walkthrough

This pull request introduces enhancements to the prediction market agent tooling, focusing on agent communication contracts, data models, and market-related structures. The changes include a new AgentCommunicationContract for managing message interactions, a MessageContainer data model for structured messaging, updates to Seer market data models, and corresponding integration tests. The modifications aim to improve the framework's capabilities for blockchain-based agent communication and market data handling.

Changes

File Change Summary
prediction_market_agent_tooling/tools/contract.py Added AgentCommunicationContract class with methods for counting unseen messages, retrieving messages by index, popping messages, and sending messages
prediction_market_agent_tooling/tools/data_models.py Introduced MessageContainer Pydantic model with attributes for sender, recipient, message, and value
tests_integration_with_local_chain/markets/omen/test_contract.py Added test_sdai_asset_balance_of test function to check asset token balance
tests_integration_with_local_chain/markets/omen/test_contracts.py Removed existing test function test_sdai_asset_balance_of
tests_integration_with_local_chain/nft_agents/test_agent_communication.py New integration tests for AgentCommunicationContract with tests for counting unseen messages and popping messages
prediction_market_agent_tooling/markets/seer/data_models.py Added SeerParentMarket class and updated SeerMarket.parent_market type to reference `SeerParentMarket
prediction_market_agent_tooling/markets/seer/seer_subgraph_handler.py Modified _get_fields_for_markets method to retrieve the id attribute of parentMarket
tests/markets/omen/test_omen.py Modified test_get_positions_1 function to remove specific assertion on the length of large_positions

Sequence Diagram

sequenceDiagram
    participant Agent1
    participant AgentCommunicationContract
    participant Agent2

    Agent1->>AgentCommunicationContract: send_message(recipient, message, amount)
    AgentCommunicationContract-->>Agent1: Transaction Receipt
    
    Agent2->>AgentCommunicationContract: count_unseen_messages()
    AgentCommunicationContract-->>Agent2: Message Count
    
    Agent2->>AgentCommunicationContract: get_at_index(index)
    AgentCommunicationContract-->>Agent2: Message Details
    
    Agent2->>AgentCommunicationContract: pop_message()
    AgentCommunicationContract-->>Agent2: Message and Remove
Loading

This sequence diagram illustrates the key interactions of the new AgentCommunicationContract, showing how agents can send messages, count unseen messages, retrieve messages by index, and pop messages from the contract.

Possibly related PRs


📜 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 53fe07a and 0d8c4fa.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (1)
  • tests/markets/omen/test_omen.py (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/markets/omen/test_omen.py

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

@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 (7)
tests_integration_with_local_chain/markets/omen/test_contract.py (1)

133-140: Add negative test coverage to ensure robust test validation.

While the current test gracefully verifies that the sDaiContract().get_asset_token_balance() result is non-negative, it could be beneficial to also test against edge cases (e.g., querying an invalid or non-existent address, or an address that has never transacted with the contract) to ensure the contract method handles unexpected inputs gracefully. This would solidify confidence that the integration behaves as expected in all circumstances.

Below is a potential follow-up test you could include:

+def test_sdai_asset_balance_of_non_existent_address(local_web3: Web3) -> None:
+    # Check that an empty or non-existent address returns 0 or raises an expected exception
+    balance = sDaiContract().get_asset_token_balance(
+        Web3.to_checksum_address("0x0000000000000000000000000000000000000000"),
+        web3=local_web3,
+    )
+    assert balance == 0, f"Expected 0 balance for a non-existent address, but got {balance}"
prediction_market_agent_tooling/tools/contract.py (3)

541-549: Consider verifying contract address via environment configuration.

Hardcoding the contract address increases the risk of accidental deployments on the wrong network. It might be beneficial to make this address configurable via environment variables or configuration files for better maintainability and flexibility.


564-574: Ensure safe handling of the raw message container structure.

get_at_index relies on from_tuple to parse the raw tuple. Consider validating the length or structure of message_container_raw to avoid unexpected errors if the contract returns malformed data or changes its return signature.


597-612: Confirm message correctness and ensure robust error-handling.

The send_message function sends both data and funds to the contract. Confirm that internal or external calls won't revert unexpectedly, especially for large message sizes or zero amount_wei. You might add error handling or checks for contract reverts.

prediction_market_agent_tooling/tools/data_models.py (1)

13-28: Validate tuple length before unpacking.

While from_tuple is straightforward, consider verifying the tuple’s length to avoid indexing errors if the contract ABI changes or returns different data.

prediction_market_agent_tooling/tools/web3_utils.py (2)

97-97: Reduced retry attempts may cause transient failures.

Decreasing from 5 to 2 attempts could lead to more transient call failures. Ensure external dependencies are stable enough that fewer retries won't degrade user experience.


169-169: Balance between speed and reliability.

Similarly, for send_function_on_contract_tx, having fewer retries can limit resilience to intermittent network issues or load spikes. Consider making the retry count configurable when high availability is needed.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 52aeeb2 and b8cc804.

⛔ Files ignored due to path filters (1)
  • prediction_market_agent_tooling/abis/agentcommunication.abi.json is excluded by !**/*.json
📒 Files selected for processing (6)
  • prediction_market_agent_tooling/tools/contract.py (2 hunks)
  • prediction_market_agent_tooling/tools/data_models.py (1 hunks)
  • prediction_market_agent_tooling/tools/web3_utils.py (2 hunks)
  • tests_integration_with_local_chain/markets/omen/test_contract.py (1 hunks)
  • tests_integration_with_local_chain/markets/omen/test_contracts.py (0 hunks)
  • tests_integration_with_local_chain/nft_agents/test_agent_communication.py (1 hunks)
💤 Files with no reviewable changes (1)
  • tests_integration_with_local_chain/markets/omen/test_contracts.py
🔇 Additional comments (6)
prediction_market_agent_tooling/tools/contract.py (3)

21-24: Imports look good.

These data models are essential for typed data exchange, and importing them here keeps the contract logic self-contained.


550-563: Validate the scenario when no unseen messages exist.

While count_unseen_messages works correctly, consider adding a check or handling around scenarios where the contract call might revert for an invalid address or if something else goes wrong. Ensuring robust error handling or introducing a fallback path in the calling code might be helpful.


575-596: Verify logs before accessing them by index.

After popping a message, process_receipt(tx_receipt) may yield an empty list if the event is not emitted or fails. Safeguard with a check on log_message_raw length to avoid potential IndexError if no events match.

prediction_market_agent_tooling/tools/data_models.py (1)

30-35: Data model usage looks solid.

LogMessageEvent with populate_by_name is a tidy solution for reading contract event fields with matching aliases.

tests_integration_with_local_chain/nft_agents/test_agent_communication.py (2)

1-42: Integration tests illustrate real blockchain interactions well.

Test coverage for test_count_unseen_messages is good. You might also consider negative tests, such as sending no message or calling the function on a non-existent agent address, to confirm error-handling under edge cases.
[approve]


45-91: Comprehensive test for message retrieval.

test_pop_message thoroughly checks the retrieval flow. To strengthen coverage, test popping a message from an empty queue to confirm that the contract or library raises the expected error or handles it gracefully.

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 (10)
prediction_market_agent_tooling/tools/contract.py (4)

540-547: Consider making ABI path configurable.
The ABI file path is hard-coded. For robust environments, consider making this configurable or passing it as a parameter so that you can easily swap ABIs as needed during testing or across environments.


549-551: Avoid hard-coding contract address.
Hard-coding the contract address can cause maintainability issues when the contract is redeployed or changed. You may want to load this address from a configuration file or environment variable.


563-573: Validate index or handle out-of-range indexes.
The contract could revert if idx is out of range. Consider catching or logging potential errors to improve debugging and error transparency.


605-620: Add minimal docstring or notes on behavior for send_message.
While the usage of the underlying send_with_value function is clear, a short docstring or inline comment explaining possible revert scenarios or usage constraints can benefit future maintainers.

prediction_market_agent_tooling/tools/data_models.py (1)

1-27: Validate tuple size in from_tuple().
You assume that the tuple will always have four elements in the correct order. Consider checking the length or using more robust parsing to avoid potential index errors.

tests_integration_with_local_chain/nft_agents/test_agent_communication.py (5)

12-21: Add negative test scenario.
In test_count_unseen_messages, you might also add a test for a nonexistent, erroneous, or invalid agent address to confirm how the system behaves.


22-28: Remove or refine commented-out code.
This code block is commented out. If it’s purely illustrative, consider adding a comment explaining its purpose or remove it to avoid confusion.


44-53: Add explicit assertion message for clarity.
When verifying initial_messages == 0, consider providing a short reason in the assertion to clarify the expectation in case of test failure.


54-59: Remove or refine commented-out snippet.
Similar to the prior comment, decide if this snippet can be safely removed or should be documented.


75-82: Test additional edge cases.
It could be valuable to test a scenario where get_at_index is called with an invalid index to confirm proper error handling.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b8cc804 and 2d6510c.

📒 Files selected for processing (3)
  • prediction_market_agent_tooling/tools/contract.py (2 hunks)
  • prediction_market_agent_tooling/tools/data_models.py (1 hunks)
  • tests_integration_with_local_chain/nft_agents/test_agent_communication.py (1 hunks)
🔇 Additional comments (4)
prediction_market_agent_tooling/tools/contract.py (3)

21-23: New import for MessageContainer.
Looks good and correctly references the new model.


553-562: Add error handling for contract call failures.
When calling countMessages on the contract, consider defensively handling exceptions that might arise if the contract is unavailable or the call fails for any reason.


574-604: Check transaction success when popping messages.
Currently, the transaction receipt is silently discarded. Consider at least logging or verifying transaction success to handle any unexpected reverts or failures.

tests_integration_with_local_chain/nft_agents/test_agent_communication.py (1)

83-89: Ensure message authenticity is tested.
You’re checking that the popped message matches mock_agent_address and compressed payload. Consider also verifying logic for potential modifications or invalid data in real usage.

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 (4)
tests_integration/markets/seer/test_seer_subgraph_handler.py (1)

20-20: Clarify or remove the skipped test.

The test is currently skipped with a vague reason. If the subgraph is unavailable or unstable, consider marking it as @pytest.mark.xfail instead and providing clearer context. Otherwise, remove the skip if the test is ready.

prediction_market_agent_tooling/tools/contract.py (3)

538-550: Document the new AgentCommunicationContract class.

This class adds important communication features. While the comment at line 540 references the ABI, consider adding a dedicated docstring explaining how to instantiate and use this class, its constructor expectations, and its constraints.


561-571: Validate index bounds for get_at_index.

A large or negative idx might cause the contract call to revert. Ensure caller code handles or prevents out-of-range indexes to avoid unexpected exceptions.


572-602: Handle empty queue scenarios in pop_message.

If the queue is empty, get_at_index(idx=0) may revert. To enhance reliability, consider implementing a safety check for zero messages before attempting to retrieve or pop.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d6510c and 7f86266.

📒 Files selected for processing (4)
  • prediction_market_agent_tooling/markets/seer/data_models.py (1 hunks)
  • prediction_market_agent_tooling/tools/contract.py (2 hunks)
  • prediction_market_agent_tooling/tools/data_models.py (1 hunks)
  • tests_integration/markets/seer/test_seer_subgraph_handler.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • prediction_market_agent_tooling/tools/data_models.py
🔇 Additional comments (4)
prediction_market_agent_tooling/markets/seer/data_models.py (1)

12-12: Make parent_market usage robust when allowing None.

Changing parent_market from HexBytes to HexBytes | None is beneficial for optional usage scenarios, but please ensure any downstream references safely handle None cases to prevent potential errors or unexpected behavior.

prediction_market_agent_tooling/tools/contract.py (3)

21-21: New import is appropriately introduced.

MessageContainer is essential for handling message payloads within the new AgentCommunicationContract. Nice addition.


551-560: Check contract availability for countMessages.

Although the method looks correct, watch out for scenarios where the on-chain contract might be missing or might not implement the countMessages function. Consider verifying contract capabilities or capturing errors if the call reverts.


603-618: Consider potential transaction failures in send_message.

While this method is straightforward, the contract call might fail (e.g., if agent_address is invalid or if amount_wei is insufficient). As a safeguard, ensure calling code is prepared to handle exceptions or revert logs for better failure transparency.

@gabrielfior gabrielfior merged commit 707a765 into main Dec 26, 2024
12 of 16 checks passed
@gabrielfior gabrielfior deleted the 572-write-functions-to-call-agents-contract-and-fetch-data branch December 26, 2024 19:55
@coderabbitai coderabbitai bot mentioned this pull request Dec 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Write functions to call agent's contract and fetch data
1 participant