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

Trades return ID, matches with ID returned from AgentMarket.get_bets_made_since #434

Merged
merged 8 commits into from
Sep 25, 2024

Conversation

evangriffiths
Copy link
Contributor

Fixes #422

Copy link

coderabbitai bot commented Sep 25, 2024

Walkthrough

The changes in this pull request involve significant updates to the data models and method signatures across various files in the prediction market agent tooling. Key modifications include the introduction of a unique identifier for the Bet class, the transition from generic Trade representations to more specific PlacedTrade instances, and alterations to several methods to return string identifiers instead of None. These updates enhance the traceability and functionality of betting and trade processing within the system.

Changes

Files Change Summary
prediction_market_agent_tooling/deploy/agent.py Updated ProcessedMarket to use list[PlacedTrade] instead of list[Trade].
prediction_market_agent_tooling/markets/agent_market.py Changed place_bet, buy_tokens, and sell_tokens methods to return str instead of None.
prediction_market_agent_tooling/markets/data_models.py Added id attribute to Bet, created PlacedTrade subclass, and added from_trade method.
prediction_market_agent_tooling/markets/manifold/api.py Modified place_bet to return ManifoldBet instead of None, and added id to ResolvedBet.
prediction_market_agent_tooling/markets/manifold/manifold.py Updated place_bet method to return str instead of None.
prediction_market_agent_tooling/markets/omen/data_models.py Updated OmenBet id attribute and modified to_bet and to_generic_resolved_bet methods.
prediction_market_agent_tooling/markets/omen/omen.py Changed multiple methods to return str instead of None, enhancing transaction feedback.
prediction_market_agent_tooling/markets/polymarket/polymarket.py Updated place_bet method to return str instead of None.
prediction_market_agent_tooling/tools/langfuse_client_utils.py Changed ProcessMarketTrace and trace_to_trades to use PlacedTrade instead of Trade.
tests_integration/markets/omen/test_get_bets.py Introduced a new test for verifying bet IDs with the subgraph.
tests_integration_with_local_chain/markets/omen/test_omen.py Updated to capture transaction IDs for buy and sell operations, enhancing transaction tracking.

Assessment against linked issues

Objective Addressed Explanation
Add a unique id to Bet class to make matching bets easier (#422)

Possibly related issues

Possibly related PRs

  • OmenAgentMarket.sell_tokens gets token pool balance dynamically #272: The changes in omen.py regarding the sell_tokens method's return type and the overall handling of token balances are related to the main PR's focus on modifying how bets are processed and the representation of trades.
  • Fix autodeposit behaviour inside omen_buy_outcome_tx #273: The introduction of new parameters and methods in omen.py for handling token deposits and the overall market functionality aligns with the main PR's changes to the ProcessedMarket class and its handling of trades.
  • Create markets with sDai as collateral #320: The enhancements to the omen.py file regarding collateral token management and the introduction of new methods for market creation are relevant to the main PR's focus on improving the data model and trade representation.
  • Refactoring ERC-4626 and support at other places #325: The modifications in omen.py to improve collateral token handling and the introduction of new methods for market transactions are directly related to the changes in the main PR regarding the ProcessedMarket class.
  • 423 sell prev positions #374: The enhancements to the process_market method in agent.py to allow for more nuanced handling of bets are directly related to the changes in the main PR regarding the representation of trades.

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 12cf490 and 8785ac0.

📒 Files selected for processing (1)
  • tests_integration_with_local_chain/markets/omen/test_omen.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests_integration_with_local_chain/markets/omen/test_omen.py

Warning

Review ran into problems

🔥 Problems

Error running Ruff: Error cloning the repository.


Error running Gitleaks: Cloning the repository previously failed.


Error running semgrep: Cloning the repository previously failed.


Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

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

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.

api_keys=api_keys,
amount_wei=amount_wei_to_buy,
outcome_index=outcome_index,
min_outcome_tokens_to_buy=expected_shares,
web3=web3,
)

return tx_receipt["transactionHash"].hex()
Copy link
Contributor Author

Choose a reason for hiding this comment

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

If I try to access the property like tx_receipt.transactionHash mypy complains, so accessing it as a dict key

api_keys=api_keys,
amount_wei=amount_wei_to_buy,
outcome_index=outcome_index,
min_outcome_tokens_to_buy=expected_shares,
web3=web3,
)

return tx_receipt["transactionHash"].hex()
Copy link
Contributor Author

@evangriffiths evangriffiths Sep 25, 2024

Choose a reason for hiding this comment

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

Could do

    trader_address = api_keys.bet_from_address
    nonce = ContractOnGnosisChain.get_transaction_count(trader_address)
    return str(tx_receipt.to) + str(trader_address.lower()) + str(nonce)

instead (to match OmenBet.id instead of OmenBet.transactionHash), but chose this for simplicity

@@ -382,7 +382,7 @@ class OmenBetCreator(BaseModel):


class OmenBet(BaseModel):
id: HexAddress
id: HexAddress # A concatenation of: FPMM contract ID, trader ID, and trade transaction nonce. See https://github.com/protofire/omen-subgraph/blob/f92bbfb6fa31ed9cd5985c416a26a2f640837d8b/src/FixedProductMarketMakerMapping.ts#L109
Copy link
Contributor

Choose a reason for hiding this comment

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

Tiny correction - nonce is a property of the account completing the transaction, not the transaction itself (basically a counter).
https://blog.thirdweb.com/nonce-ethereum/

Copy link
Contributor Author

Choose a reason for hiding this comment

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

thanks! fixed

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

🧹 Outside diff range and nitpick comments (11)
tests_integration/markets/omen/test_get_bets.py (2)

13-22: LGTM: Market selection and bet placement look good.

The test correctly selects a binary market and places two bets, asserting that their IDs are unique. This aligns well with the PR objective of adding unique IDs to bets.

Consider adding a comment explaining why you're using get_tiny_bet_amount(). For example:

# Use tiny bet amount to minimize test costs while still placing a valid bet
amount = market.get_tiny_bet_amount()

32-34: LGTM: Assertions effectively verify bet retrieval and ID matching.

The assertions correctly check both the number of retrieved bets and their IDs, directly addressing the PR objective of matching bet IDs with those returned from get_bets_made_since.

Consider adding an assertion to verify the order of the bets:

assert bets[0].created_time <= bets[1].created_time, "Bets should be sorted by creation time"

This additional check ensures that the sorting by creation time was effective.

prediction_market_agent_tooling/markets/data_models.py (2)

132-133: Approve PlacedTrade implementation with a minor suggestion.

The addition of the PlacedTrade class with an id field effectively extends the Trade class to include a unique identifier, aligning with the PR objectives.

For consistency with the Bet class, consider adding a comment to clarify the purpose of the id field:

class PlacedTrade(Trade):
    # Unique identifier for the placed trade, typically a transaction hash
    id: str

135-142: Approve from_trade method with a suggestion for robustness.

The from_trade static method effectively converts a Trade instance to a PlacedTrade, which aligns with the PR objectives and enhances the usability of the new class.

Consider adding type checking to ensure the trade parameter is indeed a Trade instance:

@staticmethod
def from_trade(trade: Trade, id: str) -> "PlacedTrade":
    if not isinstance(trade, Trade):
        raise TypeError("Expected a Trade instance")
    return PlacedTrade(
        trade_type=trade.trade_type,
        outcome=trade.outcome,
        amount=trade.amount,
        id=id,
    )

This addition would make the method more robust against potential misuse.

prediction_market_agent_tooling/markets/manifold/manifold.py (1)

52-61: LGTM! Consider adding a type hint for bet.

The changes to the place_bet method align well with the PR objectives. Returning the bet ID improves traceability and allows for easier matching with AgentMarket.get_bets_made_since. The implementation is clean and maintains existing error handling.

Consider adding a type hint for the bet variable to improve code readability:

-    bet = place_bet(
+    bet: Bet = place_bet(
         amount=Mana(amount.amount),
         market_id=self.id,
         outcome=outcome,
         manifold_api_key=APIKeys().manifold_api_key,
     )

This assumes there's a Bet class or type alias defined somewhere in the codebase. If not, you may need to import it or use a more specific type.

prediction_market_agent_tooling/tools/langfuse_client_utils.py (1)

110-113: LGTM: Update to trace_to_trades function is correct and consistent.

The change in the return type and implementation of the trace_to_trades function aligns well with the PR objectives and the previous updates. The function now correctly returns a list of PlacedTrade objects, enhancing the specificity of the trade data.

Consider adding error handling to catch potential validation errors:

 def trace_to_trades(trace: TraceWithDetails) -> list[PlacedTrade]:
     assert trace.output is not None, "Trace output is None"
     assert trace.output["trades"] is not None, "Trace output trades is None"
-    return [PlacedTrade.model_validate(t) for t in trace.output["trades"]]
+    placed_trades = []
+    for t in trace.output["trades"]:
+        try:
+            placed_trades.append(PlacedTrade.model_validate(t))
+        except ValueError as e:
+            # Log the error or handle it as appropriate for your use case
+            print(f"Error validating trade: {e}")
+    return placed_trades

This change would make the function more robust by handling potential validation errors for individual trades without failing the entire process.

prediction_market_agent_tooling/markets/manifold/api.py (1)

Line range hint 113-134: Approve changes with a minor suggestion for error handling.

The changes to the place_bet function align well with the PR objectives. The function now returns a ManifoldBet object, which includes the bet ID, enhancing traceability as requested in issue #422.

Consider updating the error message in the else clause to include the new return type:

-        raise Exception(
+        raise RuntimeError(
-            f"Placing bet failed: {response.status_code} {response.reason} {response.text}"
+            f"Failed to place bet and retrieve ManifoldBet: {response.status_code} {response.reason} {response.text}"
         )

This change would make the error message more specific and consistent with the new function behavior.

prediction_market_agent_tooling/markets/agent_market.py (3)

169-170: Approve the signature change and suggest docstring update.

The change from None to str return type aligns with the PR objectives to return an ID for trades. This change will allow subclasses to implement the method to return a unique identifier for the placed bet.

Consider updating the method's docstring to reflect the new return value:

def place_bet(self, outcome: bool, amount: BetAmount) -> str:
    """
    Place a bet on the market.

    Args:
        outcome (bool): The outcome to bet on.
        amount (BetAmount): The amount to bet.

    Returns:
        str: A unique identifier for the placed bet.

    Raises:
        NotImplementedError: This method should be implemented by subclasses.
    """
    raise NotImplementedError("Subclasses must implement this method")

172-173: Approve the signature change and suggest docstring update.

The change from None to str return type and the updated implementation correctly align with the changes made to place_bet and the PR objectives.

Consider updating the method's docstring to reflect the new return value:

def buy_tokens(self, outcome: bool, amount: TokenAmount) -> str:
    """
    Buy tokens for a specific outcome.

    Args:
        outcome (bool): The outcome to buy tokens for.
        amount (TokenAmount): The amount of tokens to buy.

    Returns:
        str: A unique identifier for the token purchase transaction.
    """
    return self.place_bet(outcome=outcome, amount=amount)

175-176: Approve the signature change and suggest docstring update.

The change from None to str return type aligns with the PR objectives to return an ID for trades. This change will allow subclasses to implement the method to return a unique identifier for the token sale transaction.

Consider updating the method's docstring to reflect the new return value:

def sell_tokens(self, outcome: bool, amount: TokenAmount) -> str:
    """
    Sell tokens for a specific outcome.

    Args:
        outcome (bool): The outcome to sell tokens for.
        amount (TokenAmount): The amount of tokens to sell.

    Returns:
        str: A unique identifier for the token sale transaction.

    Raises:
        NotImplementedError: This method should be implemented by subclasses.
    """
    raise NotImplementedError("Subclasses must implement this method")
prediction_market_agent_tooling/markets/omen/data_models.py (1)

Line range hint 385-460: Summary: Unique ID implementation achieved, but class-level comment needs updating.

The changes successfully implement a unique identifier for bets using the transaction hash, which aligns with the PR objectives. However, there's an inconsistency between the comment on the id field in the OmenBet class and its actual usage in the to_bet and to_generic_resolved_bet methods.

To resolve this inconsistency, consider one of the following actions:

  1. Update the comment on the id field to reflect its actual usage as the transaction hash.
  2. Modify the implementation in to_bet and to_generic_resolved_bet methods to use the ID as described in the comment (concatenation of FPMM contract ID, trader ID, and nonce).

Please choose the approach that best fits the intended design and update accordingly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ca6d9cb and 6939c86.

🔇 Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (10)
  • prediction_market_agent_tooling/deploy/agent.py (3 hunks)
  • prediction_market_agent_tooling/markets/agent_market.py (1 hunks)
  • prediction_market_agent_tooling/markets/data_models.py (2 hunks)
  • prediction_market_agent_tooling/markets/manifold/api.py (3 hunks)
  • prediction_market_agent_tooling/markets/manifold/manifold.py (1 hunks)
  • prediction_market_agent_tooling/markets/omen/data_models.py (3 hunks)
  • prediction_market_agent_tooling/markets/omen/omen.py (11 hunks)
  • prediction_market_agent_tooling/markets/polymarket/polymarket.py (1 hunks)
  • prediction_market_agent_tooling/tools/langfuse_client_utils.py (3 hunks)
  • tests_integration/markets/omen/test_get_bets.py (1 hunks)
🔇 Additional comments not posted (25)
tests_integration/markets/omen/test_get_bets.py (3)

1-12: LGTM: Imports and test decorator are appropriate.

The imports cover all necessary modules and classes for the test. The @pytest.mark.skipif decorator is correctly used to conditionally skip the test based on RUN_PAID_TESTS, which is a good practice for tests that incur costs.


25-31: LGTM: Bet retrieval and sorting are well-implemented.

The test correctly retrieves bets made since the initial placement and sorts them by creation time. This approach ensures a consistent order for subsequent assertions, which is crucial for reliable testing.


1-34: Overall, the test implementation effectively addresses the PR objectives.

This integration test provides good coverage for the new functionality of adding unique IDs to bets and retrieving them from the subgraph. It successfully verifies that:

  1. Placed bets receive unique IDs.
  2. Bets can be retrieved from the subgraph after placement.
  3. Retrieved bet IDs match those of the placed bets.

The test structure is clear and follows good practices, such as using tiny bet amounts to minimize costs. With the suggested improvements (more robust waiting for indexing, additional assertion for bet order), this test will provide a reliable verification of the new bet ID functionality.

prediction_market_agent_tooling/markets/polymarket/polymarket.py (1)

49-50: Verify parent class and usage of place_bet method

The change in the place_bet method signature may have implications on other parts of the system:

  1. Ensure that the parent AgentMarket class has a compatible place_bet method signature to maintain consistency in the inheritance hierarchy.
  2. Verify that all other parts of the system that use the place_bet method are updated to handle the returned string ID.

Run the following script to check for potential inconsistencies:

This script will help identify any potential issues with the parent class implementation and usage of the place_bet method throughout the codebase.

prediction_market_agent_tooling/markets/data_models.py (1)

Line range hint 40-142: Overall approval with minor suggestions for improvement.

The changes in this file effectively address the PR objectives and the linked issue #422. The addition of unique identifiers to both Bet and PlacedTrade classes, along with the from_trade method, enhances the functionality and traceability of the prediction market system.

Key points:

  1. The id field has been consistently added to both Bet and PlacedTrade classes.
  2. The PlacedTrade class effectively extends Trade with the new identifier.
  3. The from_trade method provides a convenient way to convert Trade instances to PlacedTrade.

The suggestions provided in the previous comments are minor and aimed at improving clarity, consistency, and robustness. Overall, these changes represent a solid improvement to the data models.

prediction_market_agent_tooling/markets/manifold/manifold.py (2)

Line range hint 1-61: Overall, the changes look good and align with the PR objectives.

The modification to the place_bet method improves traceability by returning a bet ID. This change supports the goal of matching bets with those returned from AgentMarket.get_bets_made_since. The implementation is clean and maintains existing error handling.

Remember to:

  1. Add the suggested type hint for improved readability.
  2. Run the verification script to identify and update any affected parts of the codebase.
  3. Update tests if necessary to account for the new return value of place_bet.

52-61: Verify the impact of the return type change.

The place_bet method now returns a string ID instead of None. This change might affect other parts of the codebase that call this method.

Please run the following script to identify potential areas that might need updates:

Review the results to ensure that all usages of place_bet are updated to handle the new return value correctly.

✅ Verification successful

Return type change verified successfully. No usages of place_bet with the previous return type were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find usages of ManifoldAgentMarket.place_bet method

# Search for ManifoldAgentMarket.place_bet usage
echo "Searching for ManifoldAgentMarket.place_bet usage:"
rg --type python "ManifoldAgentMarket.*place_bet" -A 5

# Search for potential variable assignments or assertions related to place_bet
echo "\nSearching for potential variable assignments or assertions:"
rg --type python "place_bet\(.*\).*=" -A 5
rg --type python "assert.*place_bet\(.*\).*None" -A 5

Length of output: 494


Script:

#!/bin/bash
# Description: Find usages of ManifoldAgentMarket.place_bet method in .py files

# Search for ManifoldAgentMarket.place_bet usage
echo "Searching for ManifoldAgentMarket.place_bet usage in .py files:"
rg "ManifoldAgentMarket.*place_bet" --type py -A 5

# Search for potential variable assignments related to place_bet
echo "\nSearching for potential variable assignments related to place_bet:"
rg "place_bet\(.*\).*=" --type py -A 5

# Search for assertions related to place_bet returning None
echo "\nSearching for assertions related to place_bet returning None:"
rg "assert.*place_bet\(.*\).*None" --type py -A 5

Length of output: 566

prediction_market_agent_tooling/tools/langfuse_client_utils.py (4)

10-10: LGTM: Import of PlacedTrade is correct and aligns with PR objectives.

The addition of PlacedTrade to the imports is consistent with the goal of transitioning from generic Trade representations to more specific PlacedTrade instances. This change supports the enhancement of traceability in the betting system.


26-26: LGTM: Update to buy_trade property return type is correct and consistent.

The change of the buy_trade property's return type from Trade to PlacedTrade is consistent with the previous updates and aligns with the PR objectives. This modification ensures type consistency throughout the class and improves the specificity of the returned trade data.


Line range hint 1-153: Summary: Changes in langfuse_client_utils.py are well-implemented and align with PR objectives.

The modifications in this file successfully transition from generic Trade to more specific PlacedTrade objects. These changes enhance the traceability and functionality of the betting system, which aligns well with the PR objectives. The updates are consistent throughout the file, affecting imports, class attributes, and function signatures appropriately.

Key points:

  1. Import of PlacedTrade is correctly added.
  2. ProcessMarketTrace class now uses PlacedTrade instead of Trade.
  3. trace_to_trades function is updated to return list[PlacedTrade].

These changes contribute to the overall goal of adding a unique identifier to the Bet class and improving the matching of bets with langfuse traces. The code quality is good, with only a minor suggestion for improved error handling in the trace_to_trades function.


23-23: LGTM: Update to trades attribute type is correct.

The change from list[Trade] to list[PlacedTrade] for the trades attribute is consistent with the PR objectives and the import changes. This update enhances the specificity and traceability of trade data within the ProcessMarketTrace class.

To ensure this change doesn't introduce inconsistencies, please run the following script to check for any remaining usage of the generic Trade type in relation to this class:

prediction_market_agent_tooling/markets/agent_market.py (1)

169-176: Summary of changes and their impact

The modifications to place_bet, buy_tokens, and sell_tokens methods in the AgentMarket class align well with the PR objectives. These changes introduce the return of unique identifiers (as strings) for trade operations, which will facilitate matching trades with bets retrieved from AgentMarket.get_bets_made_since.

Key improvements:

  1. Enhanced traceability of betting and trading actions.
  2. Consistent API changes across related methods.
  3. Maintained abstraction in the base class, allowing for proper implementation in subclasses.

These changes lay a solid foundation for improved bet matching and analysis in the prediction market agent tooling framework.

prediction_market_agent_tooling/markets/omen/data_models.py (3)

Line range hint 434-441: Approved: Unique ID implemented, but inconsistent with class-level comment.

The implementation of a unique identifier for each bet using the transaction hash is a good practice and aligns with the PR objectives. However, this usage is inconsistent with the comment on the id field in the OmenBet class, which describes a different composition for the ID.

To verify the usage of transactionHash as the ID, please run the following script:

#!/bin/bash
# Description: Check the usage of transactionHash as the ID in the to_bet method
# Expected result: Confirm that transactionHash is used as the ID

# Search for the to_bet method in the OmenBet class
rg --type python -A 10 "def to_bet\(" prediction_market_agent_tooling/markets/omen/data_models.py

Line range hint 449-460: Approved: Consistent ID implementation for resolved bets, but class-level comment inconsistency persists.

The implementation of a unique identifier for resolved bets using the transaction hash is consistent with the to_bet method and aligns with the PR objectives. However, the inconsistency with the comment on the id field in the OmenBet class remains.

To verify the consistent usage of transactionHash as the ID in both methods, please run the following script:

#!/bin/bash
# Description: Check the consistent usage of transactionHash as the ID in both to_bet and to_generic_resolved_bet methods
# Expected result: Confirm that transactionHash is used as the ID in both methods

# Search for both to_bet and to_generic_resolved_bet methods in the OmenBet class
rg --type python -A 15 "def to_(bet|generic_resolved_bet)\(" prediction_market_agent_tooling/markets/omen/data_models.py

385-386: Approved: Clarification on id composition is helpful, but usage inconsistency noted.

The added comment provides valuable insight into the composition of the id field, which aligns with the PR objective of adding a unique identifier to the Bet class. However, there seems to be an inconsistency between this comment and the actual usage of the id in the to_bet and to_generic_resolved_bet methods below, where transactionHash is used instead.

To verify the actual composition of the id, please run the following script:

✅ Verification successful

Verified: id field composition and usage are consistent and correctly implemented.
The id field in the OmenBet class is properly defined as a concatenation of the FPMM contract ID, trader ID, and nonce. Its usage across methods aligns with the intended unique identifier functionality, ensuring consistency with the provided comment.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the actual composition of the OmenBet id field
# Expected result: Find the implementation details of the id field

# Search for the OmenBet class definition and its id field
rg --type python -A 10 "class OmenBet\(" prediction_market_agent_tooling/markets/omen/data_models.py

# Search for any usage or assignment of the id field within the OmenBet class
rg --type python "self\.id" prediction_market_agent_tooling/markets/omen/data_models.py

Length of output: 340


Script:

#!/bin/bash
# Description: Check the actual composition of the OmenBet id field
# Expected result: Find the implementation details of the id field

# Search for the OmenBet class definition and its id field
rg --type py -A 15 "class OmenBet\(" prediction_market_agent_tooling/markets/omen/data_models.py

# Search for any usage or assignment of the id field within the OmenBet class
rg --type py "self\.id" prediction_market_agent_tooling/markets/omen/data_models.py

Length of output: 1197

prediction_market_agent_tooling/markets/omen/omen.py (8)

Line range hint 192-207: LGTM: Return type updated consistently.

The place_bet function has been updated to return a str instead of None, which aligns with the PR objectives. This change is consistent with other modified functions in the file. The implementation correctly passes all necessary parameters to binary_omen_buy_outcome_tx.


Line range hint 215-221: LGTM: Consistent return type update.

The buy_tokens function has been updated to return a str, maintaining consistency with the place_bet function. The implementation correctly returns the result of self.place_bet, passing all necessary parameters.


Line range hint 248-268: LGTM: Consistent return type update.

The sell_tokens function has been updated to return a str, maintaining consistency with other modified functions in the file. The implementation correctly returns the result of binary_omen_sell_outcome_tx, passing all necessary parameters.


Line range hint 670-715: LGTM: Return type updated consistently.

The omen_buy_outcome_tx function has been updated to return a str (the transaction hash), which aligns with the PR objectives and is consistent with other modified functions. The implementation correctly returns the transaction hash as a hexadecimal string.

Note: The previous review comment about accessing tx_receipt as a dict key instead of a property has been addressed in this implementation.


Line range hint 724-733: LGTM: Consistent return type update.

The binary_omen_buy_outcome_tx function has been updated to return a str, maintaining consistency with the omen_buy_outcome_tx function. The implementation correctly returns the result of omen_buy_outcome_tx, passing all necessary parameters.


Line range hint 742-806: LGTM: Return type updated consistently.

The omen_sell_outcome_tx function has been updated to return a str (the transaction hash), which aligns with the PR objectives and is consistent with the omen_buy_outcome_tx function. The implementation correctly returns the transaction hash as a hexadecimal string.


Line range hint 815-824: LGTM: Consistent return type update.

The binary_omen_sell_outcome_tx function has been updated to return a str, maintaining consistency with the omen_sell_outcome_tx function. The implementation correctly returns the result of omen_sell_outcome_tx, passing all necessary parameters.


Line range hint 192-824: Summary: Consistent implementation of trade ID returns.

The changes in this file successfully implement the PR objective of returning IDs for trades. All modified functions (place_bet, buy_tokens, sell_tokens, omen_buy_outcome_tx, binary_omen_buy_outcome_tx, omen_sell_outcome_tx, and binary_omen_sell_outcome_tx) have been updated to return a str instead of None. The implementations consistently return transaction hashes or results from other functions that return transaction hashes.

These modifications enhance the functionality of the trading system by providing unique identifiers for trades, which will facilitate matching with bets retrieved from AgentMarket.get_bets_made_since. The changes are well-implemented and maintain consistency throughout the file.

prediction_market_agent_tooling/deploy/agent.py (2)

481-481: Verify that placed_trades is correctly populated

Ensure that placed_trades contains all the expected PlacedTrade instances before creating the ProcessedMarket. If no trades were placed or an error occurred, placed_trades might be empty, which could affect downstream processes.


114-114: Ensure consistent updates when changing ProcessedMarket.trades type

The trades attribute of ProcessedMarket has been updated to list[PlacedTrade]. Please verify that all instances where ProcessedMarket is instantiated or where the trades attribute is accessed are updated accordingly to prevent any type mismatches or runtime errors.

Run the following script to check for usages of ProcessedMarket with outdated trades types:

✅ Verification successful

ProcessedMarket.trades type update verified

All instances of ProcessedMarket use the updated list[PlacedTrade] type for the trades attribute.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Find all instances of `ProcessedMarket` that may still use `list[Trade]`.

rg --type py --context 5 'ProcessedMarket\('

Length of output: 1777

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
tests_integration_with_local_chain/markets/omen/test_omen.py (3)

318-318: LGTM! Consider adding a comment for clarity.

The change to capture the buy_id returned by place_bet is good. It allows for transaction verification later in the test.

Consider adding a brief comment explaining the purpose of capturing the buy_id:

# Capture the transaction ID for later verification
buy_id = market.place_bet(outcome=outcome, amount=bet_amount, web3=local_web3)

335-341: LGTM! Consider extracting the verification logic into a helper function.

The added code block to verify the validity of buy_id and sell_id is a good addition to the test. It ensures that the transactions are properly recorded on the blockchain and associated with the correct address.

Consider extracting the verification logic into a helper function to improve readability and reusability:

def verify_transaction(web3: Web3, tx_id: str, expected_from_address: ChecksumAddress) -> None:
    tx = web3.eth.get_transaction(tx_id)
    assert tx is not None, f"Transaction {tx_id} not found"
    assert tx["from"] == expected_from_address, f"Transaction {tx_id} not from expected address"

# Usage in the test
verify_transaction(local_web3, buy_id, api_keys.bet_from_address)
verify_transaction(local_web3, sell_id, api_keys.bet_from_address)

This refactoring would make the test more readable and allow for easy reuse of the verification logic in other tests if needed.


Line range hint 318-341: Overall, the changes improve test coverage and robustness.

The modifications to the test_omen_buy_and_sell_outcome function enhance the test by verifying the validity of transaction IDs returned by place_bet and sell_tokens methods. This additional check ensures that these critical operations are correctly recorded on the blockchain, improving the overall reliability of the Omen prediction market system testing.

Consider implementing similar transaction ID verification in other relevant tests throughout the codebase to maintain consistency and improve the overall test suite's robustness.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 6939c86 and 12cf490.

📒 Files selected for processing (2)
  • prediction_market_agent_tooling/markets/omen/data_models.py (3 hunks)
  • tests_integration_with_local_chain/markets/omen/test_omen.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • prediction_market_agent_tooling/markets/omen/data_models.py
🔇 Additional comments not posted (1)
tests_integration_with_local_chain/markets/omen/test_omen.py (1)

Line range hint 324-328: LGTM! Capturing sell_id is consistent with buy_id.

The change to capture the sell_id returned by sell_tokens is good. It maintains consistency with the buy_id capture and allows for transaction verification later in the test.

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.

Add a unique id to Bet class to make matching bets with langfuse traces easier
3 participants