Skip to content

Comments

FSCA agent base created#926

Open
TS9001 wants to merge 9 commits intomainfrom
tom/FSCA_agent
Open

FSCA agent base created#926
TS9001 wants to merge 9 commits intomainfrom
tom/FSCA_agent

Conversation

@TS9001
Copy link
Contributor

@TS9001 TS9001 commented Jul 16, 2025

No description provided.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 16, 2025

Walkthrough

A new deployable arbitrage trading agent for Seer prediction markets is introduced, capable of exploiting probability imbalances by minting or merging complete sets of outcome tokens. The agent, its registration, and comprehensive unit tests for its core arbitrage sizing and market processing logic are added. Additionally, a minimal test market class is introduced for benchmarking. No existing core logic is modified except for test-related imports.

Changes

Cohort / File(s) Change Summary
Full Set Collective Arbitrage Agent Implementation
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
Adds a deployable arbitrage agent class supporting Seer markets. Implements logic to detect and exploit arbitrage when outcome probabilities sum ≠ 1, with robust configuration, trade sizing, execution, and logging. Introduces enums, methods for arbitrage type handling, and safe trading/minting of complete sets.
Agent Registration
prediction_market_agent/run_agent.py
Registers the new arbitrage agent in the agent runner. Adds enum member for the agent and maps it to the deployable agent class. No other changes to logic or flow.
Unit Tests: Arbitrage Sizing
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py
Introduces a realistic Uniswap V3-style mock market and extensive tests for the agent’s _max_sets method. Covers under/over-estimated probabilities, liquidity, fees, edge cases, and validates arbitrage sizing, marginal cost/revenue crossing, and probability convergence.
Unit Tests: Market Processing
tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py
Adds tests for the agent’s process_market method. Uses mocks to simulate buy/sell trade execution for both under- and over-estimated scenarios. Verifies correct trade generation, reasoning, and internal method calls.
Test Market Utility
prediction_market_agent/utils/test_markets.py
Adds TestAgentMarket class as a minimal concrete implementation of AgentMarket for testing and benchmarking purposes with stubbed methods and properties.
Benchmark Import Adjustments
prediction_market_agent/agents/known_outcome_agent/benchmark.py, prediction_market_agent/agents/think_thoroughly_agent/benchmark.py
Modifies imports and return types to use TestAgentMarket instead of AgentMarket for benchmarking markets, enabling use of the new test market class without changing method signatures or parameters.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~40 minutes

Suggested reviewers

  • gabrielfior

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch tom/FSCA_agent

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

@TS9001 TS9001 marked this pull request as ready for review July 30, 2025 11:27
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (4)
tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py (1)

119-119: Add newline at end of file.

-    arbitrage_overestimated_mock.assert_called_once_with(mock_market)
+    arbitrage_overestimated_mock.assert_called_once_with(mock_market)
+
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (2)

280-280: Replace lambda expressions with named functions.

For better readability and debugging, use named functions instead of lambdas.

-            good = lambda q: q < target
+            def good(q: float) -> bool:
+                return q < target
-            good = lambda q: q > target
+            def good(q: float) -> bool:
+                return q > target

Also applies to: 292-292


360-362: Remove redundant logging inside the loop.

This log message is redundant as it repeats the same information from line 348 for each iteration.

                    if trade_type == TradeType.BUY:
-                        logger.info(
-                            f"Buying {quantity} complete sets for market {market.question}"
-                        )
                        amount_usd = USD(quantity)
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1)

850-850: Add newline at end of file.

-    assert N == 0, "Should find no arbitrage despite high fees"
+    assert N == 0, "Should find no arbitrage despite high fees"
+
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1bff63a and b71d665.

📒 Files selected for processing (4)
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1 hunks)
  • prediction_market_agent/run_agent.py (3 hunks)
  • tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1 hunks)
  • tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the `prediction_market_agent` codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the `answer_binary_market` method is correctly positioned outside the `if`-`else` blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#637
File: prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py:94-103
Timestamp: 2025-01-14T09:51:43.292Z
Learning: In the NFT Treasury game, agents can have seemingly contradictory instructions (e.g., being sellers while also being instructed to never sell) as this is an intentional game design choice that creates more complex agent interactions and behaviors.
prediction_market_agent/run_agent.py (7)

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py (4)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (11)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: evangriffiths
PR: #503
File: prediction_market_agent/agents/replicate_to_omen_agent/deploy.py:68-70
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The function omen_finalize_and_resolve_and_claim_back_all_markets_based_on_others_tx includes the realitio_bond parameter.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-03T10:53:21.330Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T10:04:32.530Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

🧬 Code Graph Analysis (1)
prediction_market_agent/run_agent.py (1)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1)
  • DeployableFullSetCollectiveArbitrageAgent (47-417)
🪛 Ruff (0.12.2)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py

233-233: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)


280-280: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)


292-292: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)


415-415: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

🔇 Additional comments (2)
prediction_market_agent/run_agent.py (1)

34-36: Integration looks good!

The new agent is properly integrated following the established pattern in the codebase.

Also applies to: 162-162, 220-220

tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1)

32-87: Excellent realistic market mock implementation!

The RealisticUniswapV3MockMarket class provides a sophisticated simulation of Uniswap V3 mechanics with proper price impact and liquidity dynamics. The workaround for Pydantic's attribute validation is well-documented and appropriate.

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

♻️ Duplicate comments (3)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (3)

226-226: Fix typo in TODO comment and track the missing functionality.

-            # TODDO MINT SHOULD RETURN SOMETHING FOR PLACED TRADES
+            # TODO: MINT SHOULD RETURN SOMETHING FOR PLACED TRADES

This TODO indicates that the minting operation doesn't return trade information, which means the arbitrage trades are not fully tracked. This could impact reporting and reconciliation.

Would you like me to create an issue to track implementing proper trade returns from the mint operation?


235-235: Use proper exception chaining.

-            raise ValueError(f"Failed to execute over-estimated arbitrage: {e}") from e
+            raise ValueError(f"Failed to execute over-estimated arbitrage: {e}") from e

417-419: Use proper exception chaining.

-            raise ValueError(
-                f"Failed to execute complete set {action_lower}: {e}"
-            ) from e
+            raise ValueError(
+                f"Failed to execute complete set {action_lower}: {e}"
+            ) from e
🧹 Nitpick comments (1)
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1)

73-79: Consider using private attributes instead of bypassing Pydantic validation.

The current approach of using object.__setattr__ to bypass Pydantic's attribute guard is fragile and could break with future Pydantic updates. Consider using private attributes with property decorators for a cleaner implementation:

 class RealisticUniswapV3MockMarket(SeerAgentMarket):
     """
     Realistic mock for SeerAgentMarket with Uniswap V3 pricing mechanics.
     Simulates actual price impact and liquidity dynamics.
     """
 
-    # These are helper attributes, NOT Pydantic model fields
-    # Using ClassVar tells Pydantic to ignore them during validation
-    liquidity_per_outcome: t.ClassVar[float]
-    collateral_token_usd_price: t.ClassVar[float]
+    _liquidity_per_outcome: float
+    _collateral_token_usd_price: float
+
+    class Config:
+        underscore_attrs_are_private = True

Then update the initialization:

-        # 2. Attach helper attributes *after* BaseModel setup, bypassing its
-        #    attribute guard. The annotations above keep the type checker happy.
-        object.__setattr__(self, "liquidity_per_outcome", liquidity_per_outcome)
-        object.__setattr__(
-            self, "collateral_token_usd_price", collateral_token_usd_price
-        )
+        self._liquidity_per_outcome = liquidity_per_outcome
+        self._collateral_token_usd_price = collateral_token_usd_price

And update references throughout the class to use self._liquidity_per_outcome and self._collateral_token_usd_price.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b71d665 and 1a01079.

📒 Files selected for processing (4)
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1 hunks)
  • prediction_market_agent/run_agent.py (3 hunks)
  • tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (1 hunks)
  • tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • prediction_market_agent/run_agent.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the `prediction_market_agent` codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the `answer_binary_market` method is correctly positioned outside the `if`-`else` blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#637
File: prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py:94-103
Timestamp: 2025-01-14T09:51:43.292Z
Learning: In the NFT Treasury game, agents can have seemingly contradictory instructions (e.g., being sellers while also being instructed to never sell) as this is an intentional game design choice that creates more complex agent interactions and behaviors.
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (4)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T10:04:32.530Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (13)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: evangriffiths
PR: #503
File: prediction_market_agent/agents/replicate_to_omen_agent/deploy.py:68-70
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The function omen_finalize_and_resolve_and_claim_back_all_markets_based_on_others_tx includes the realitio_bond parameter.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-03T10:53:21.330Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T10:04:32.530Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: kongzii
PR: #301
File: prediction_market_agent/agents/microchain_agent/utils.py:122-142
Timestamp: 2024-07-03T06:52:20.555Z
Learning: The function name and docstring for get_function_useage_from_history in prediction_market_agent/agents/microchain_agent/utils.py should use "usage" instead of "useage".

🪛 Ruff (0.12.2)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py

282-282: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)


294-294: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: test-build-image
  • GitHub Check: pytest-docker
  • GitHub Check: pytest - Integration with Local Chain
  • GitHub Check: pytest - Unit Tests
  • GitHub Check: mypy
🔇 Additional comments (10)
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (6)

281-367: Well-structured test for marginal cost pivot detection.

The test comprehensively validates the agent's ability to find the optimal arbitrage quantity where marginal cost crosses 1.0. The assertions correctly verify the boundary conditions and the improvement in market efficiency after arbitrage.


460-499: Good edge case test for balanced markets.

The test correctly verifies that the agent doesn't find arbitrage opportunities when probabilities are already balanced at 1.0.


506-591: Comprehensive test for mint-and-sell arbitrage.

The test correctly validates the agent's ability to identify profitable minting opportunities when probabilities are overestimated. The marginal revenue boundary conditions are properly verified.


593-681: Good test design for price impact scenarios.

The test effectively validates arbitrage sizing under realistic market conditions with lower liquidity and higher fees. The assertions correctly verify that price impact limits arbitrage opportunities.


688-724: Important edge case test for zero liquidity.

The test properly handles the edge case of markets with no liquidity, ensuring the agent gracefully returns 0 instead of attempting invalid trades.


726-819: Effective stress test with extreme probability imbalances.

The test validates the agent's robustness when handling markets with extreme underestimation (15% total probability). Good use of high liquidity to ensure the extreme case is testable.

prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (4)

83-159: Well-structured market processing with comprehensive validation.

The method properly validates market conditions before attempting arbitrage, including checks for outcome token pool data, multiresult markets, and missing outcomes. The arbitrage detection logic correctly identifies opportunities based on probability sum deviations.


239-306: Robust binary search implementation for optimal arbitrage sizing.

The method effectively finds the maximum profitable arbitrage quantity using binary search on marginal cost/revenue functions. The handling of edge cases (empty pools, zero probabilities) and the early termination conditions are well-implemented.


308-337: Correct implementation of marginal pricing formulas.

The method accurately calculates marginal cost and revenue based on the Uniswap V3 constant product formula, with proper handling of fees and edge cases.


373-383: Proper position validation before selling.

The code correctly validates the user's current position before attempting to sell tokens, preventing overselling by using the minimum of the requested quantity and the actual holdings.

Comment on lines +413 to +457
# 4) Compute the marginal cost at N, N - 1, and N + 1
mc_at_N = agent._get_marginal_quote(
N, k, pools, mock_market.fees, mock_market, CalculationType.COST
)
mc_below = (
agent._get_marginal_quote(
N - 1, k, pools, mock_market.fees, mock_market, CalculationType.COST
)
if N > 0
else None
)
mc_above = agent._get_marginal_quote(
N + 1, k, pools, mock_market.fees, mock_market, CalculationType.COST
)

# 5) Assert that mc crosses 1.0 exactly at N
assert (
mc_below is None or mc_below < 1.0
), f"Marginal cost just below N should be <1 (got {mc_below:.4f})"
# At N it should be right at or just under 1.0 (within a tiny epsilon)
assert (
pytest.approx(1.0, rel=1e-2) == mc_at_N
), f"Marginal cost at N should be ≈1 (got {mc_at_N:.4f})"
# One more set should push marginal cost above 1
assert mc_above > 1.0, f"Marginal cost above N should be >1 (got {mc_above:.4f})"

# 6) Compute implied probabilities before & after
# m_i = k_i / x_i^2 ; then normalize
def implied_probs(pools_dict: dict[OutcomeStr, float]) -> dict[OutcomeStr, float]:
m = {o: k[o] / (pools_dict[o] ** 2) for o in pools_dict}
total = sum(m.values())
return {o: m[o] / total for o in m}

# original pools and probs
orig_sum = sum(probs.values())

# new pools after buying N sets
pools_after = {o: pools[o] - N for o in pools}
new_probs = implied_probs(pools_after)
new_sum = sum(new_probs.values())

# 7) Assert that the sum has moved closer to 1
assert abs(1.0 - new_sum) < abs(
1.0 - orig_sum
), f"After buying, |1−{new_sum:.4f}| should be < |1−{orig_sum:.4f}|"
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

Extract duplicated test logic into helper functions.

The marginal cost verification and implied probability calculation logic is duplicated across multiple tests. Consider extracting these into helper functions to improve maintainability:

def verify_marginal_cost_at_pivot(
    agent: DeployableFullSetCollectiveArbitrageAgent,
    N: int,
    k: dict[OutcomeStr, float],
    pools: dict[OutcomeStr, float],
    market: SeerAgentMarket,
) -> None:
    """Verify that marginal cost crosses 1.0 at the optimal N."""
    mc_at_N = agent._get_marginal_quote(
        N, k, pools, market.fees, market, CalculationType.COST
    )
    mc_below = (
        agent._get_marginal_quote(
            N - 1, k, pools, market.fees, market, CalculationType.COST
        )
        if N > 0
        else None
    )
    mc_above = agent._get_marginal_quote(
        N + 1, k, pools, market.fees, market, CalculationType.COST
    )
    
    assert (
        mc_below is None or mc_below < 1.0
    ), f"Marginal cost just below N should be <1 (got {mc_below:.4f})"
    assert (
        pytest.approx(1.0, rel=1e-2) == mc_at_N
    ), f"Marginal cost at N should be ≈1 (got {mc_at_N:.4f})"
    assert mc_above > 1.0, f"Marginal cost above N should be >1 (got {mc_above:.4f})"

def verify_probability_improvement(
    k: dict[OutcomeStr, float],
    pools: dict[OutcomeStr, float],
    N: int,
    orig_probs: dict[OutcomeStr, float],
) -> None:
    """Verify that probabilities move closer to 1 after arbitrage."""
    def implied_probs(pools_dict: dict[OutcomeStr, float]) -> dict[OutcomeStr, float]:
        m = {o: k[o] / (pools_dict[o] ** 2) for o in pools_dict}
        total = sum(m.values())
        return {o: m[o] / total for o in m}
    
    orig_sum = sum(orig_probs.values())
    pools_after = {o: pools[o] - N for o in pools}
    new_probs = implied_probs(pools_after)
    new_sum = sum(new_probs.values())
    
    assert abs(1.0 - new_sum) < abs(
        1.0 - orig_sum
    ), f"After buying, |1−{new_sum:.4f}| should be < |1−{orig_sum:.4f}|"
🤖 Prompt for AI Agents
In tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py
around lines 413 to 457, the marginal cost verification and implied probability
calculation logic is duplicated across tests. Extract this duplicated logic into
two helper functions: one to verify that marginal cost crosses 1.0 at the
optimal N by checking marginal costs at N, N-1, and N+1; and another to verify
that probabilities move closer to 1 after arbitrage by computing implied
probabilities before and after buying N sets and asserting improvement. Replace
the inline duplicated code with calls to these helper functions to improve
maintainability.

Comment on lines +831 to +842
def mock_get_sell_price(
market: SeerAgentMarket,
outcome: OutcomeStr,
tokens_to_sell_wei: Wei,
from_address: ChecksumAddress,
) -> Wei:
# Convert wei to tokens and get sell value
tokens_to_sell = OutcomeToken(tokens_to_sell_wei.value / 10**18)
collateral_received = market.get_sell_value_of_outcome_token(
outcome, tokens_to_sell
)
return Wei(int(collateral_received.value * 10**18))
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

Remove unused mock function.

The mock_get_sell_price function is defined but never used in this test. Either use it or remove it to keep the test clean:

-    # Mock the precise pricing method for selling
-    def mock_get_sell_price(
-        market: SeerAgentMarket,
-        outcome: OutcomeStr,
-        tokens_to_sell_wei: Wei,
-        from_address: ChecksumAddress,
-    ) -> Wei:
-        # Convert wei to tokens and get sell value
-        tokens_to_sell = OutcomeToken(tokens_to_sell_wei.value / 10**18)
-        collateral_received = market.get_sell_value_of_outcome_token(
-            outcome, tokens_to_sell
-        )
-        return Wei(int(collateral_received.value * 10**18))
-
📝 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
def mock_get_sell_price(
market: SeerAgentMarket,
outcome: OutcomeStr,
tokens_to_sell_wei: Wei,
from_address: ChecksumAddress,
) -> Wei:
# Convert wei to tokens and get sell value
tokens_to_sell = OutcomeToken(tokens_to_sell_wei.value / 10**18)
collateral_received = market.get_sell_value_of_outcome_token(
outcome, tokens_to_sell
)
return Wei(int(collateral_received.value * 10**18))
🤖 Prompt for AI Agents
In tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py
between lines 831 and 842, the function mock_get_sell_price is defined but never
used. To clean up the test code, remove the entire mock_get_sell_price function
definition since it serves no purpose and is not called anywhere in the test.

Comment on lines 69 to 81
def get_markets(
self,
market_type: MarketType,
) -> t.Sequence[SeerAgentMarket]:
# Fetch all markets to choose from
available_markets = SeerAgentMarket.get_markets(
limit=5,
# sort_by=self.get_markets_sort_by,
sort_by=SortBy.HIGHEST_LIQUIDITY,
filter_by=self.get_markets_filter_by,
created_after=self.trade_on_markets_created_after,
)
return available_markets
Copy link
Contributor

Choose a reason for hiding this comment

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

Does this need to be overriden? I would've expected the logic from SeerAgentMarket to be enough

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yep !00%true, gone.

)
return available_markets

def process_market(
Copy link
Contributor

Choose a reason for hiding this comment

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

You can override the method before_process_market and pack the logic there - this way, I believe you can avoid placing the trades manually.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yep, i overriden it and placed all validations there...

Comment on lines 219 to 221
mint_full_set_for_market(
market_collateral_token=collateral_token_address,
market_id=Web3.to_checksum_address(market.id),
Copy link
Contributor

Choose a reason for hiding this comment

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

Why do you have to manually mint here? I expected the auto_deposit logic to be able to handle all kinds of trades (including the ones generated here).

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Absolutely true, I have removed it and left comment, originally it was there to see if everything works transparently.

low, high = high, high * 2.0
good = lambda q: q > target

# --- Binary search ---
Copy link
Contributor

Choose a reason for hiding this comment

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

Any reason for not using bisect?

Copy link
Contributor Author

@TS9001 TS9001 Jul 31, 2025

Choose a reason for hiding this comment

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

Lets discuss this offline.

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

🧹 Nitpick comments (1)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1)

234-301: Sophisticated optimal sizing calculation with binary search.

The _max_sets method implements a mathematically sound approach:

  • Uses marginal cost/revenue functions
  • Employs binary search for efficiency
  • Handles edge cases (empty pools, zero probabilities)
  • Sets appropriate search bounds

However, there are lambda expressions that should be refactored per static analysis hints.

Replace lambda expressions with proper function definitions for better readability:

-            good = lambda q: q < target
+            def good(q: float) -> bool:
+                return q < target
-            good = lambda q: q > target
+            def good(q: float) -> bool:
+                return q > target
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1a01079 and 2c1be90.

📒 Files selected for processing (1)
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the `prediction_market_agent` codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the `answer_binary_market` method is correctly positioned outside the `if`-`else` blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#637
File: prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py:94-103
Timestamp: 2025-01-14T09:51:43.292Z
Learning: In the NFT Treasury game, agents can have seemingly contradictory instructions (e.g., being sellers while also being instructed to never sell) as this is an intentional game design choice that creates more complex agent interactions and behaviors.
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (13)

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In prediction_market_agent/agents/metaculus_agent/deploy.py, the return answer statement in the answer_binary_market method is correctly positioned outside the if-else blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Learnt from: kongzii
PR: #529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the prediction_market_agent codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If #253 is resolved, the dummy build_agent could be replaced with build_agent_functions.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: kongzii
PR: #337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the prediction_market_agent/agents/microchain_agent/prompts.py file.

Learnt from: evangriffiths
PR: #503
File: prediction_market_agent/agents/replicate_to_omen_agent/deploy.py:68-70
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The function omen_finalize_and_resolve_and_claim_back_all_markets_based_on_others_tx includes the realitio_bond parameter.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-03T10:53:21.330Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In think_thoroughly_agent.py, the function convert_to_utc_datetime is imported from prediction_market_agent_tooling.tools.utils.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T10:04:32.530Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: evangriffiths
PR: #501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In prediction_market_agent/agents/goal_manager.py, when reviewing the method get_unique_evaluated_goals, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Learnt from: kongzii
PR: #301
File: prediction_market_agent/agents/microchain_agent/utils.py:122-142
Timestamp: 2024-07-03T06:52:20.555Z
Learning: The function name and docstring for get_function_useage_from_history in prediction_market_agent/agents/microchain_agent/utils.py should use "usage" instead of "useage".

🧬 Code Graph Analysis (1)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (4)
prediction_market_agent/utils.py (1)
  • APIKeys (27-111)
tests/agents/full_set_collective_arbitrage_agent/test_process_market_arbitrage.py (1)
  • agent (36-38)
tests/agents/full_set_collective_arbitrage_agent/test_max_sets_to_buy.py (2)
  • agent (262-273)
  • get_sell_value_of_outcome_token (143-170)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/agent_db.py (1)
  • api_keys (32-36)
🪛 Ruff (0.12.2)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py

277-277: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)


289-289: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
  • GitHub Check: test-build-image
  • GitHub Check: pytest - Integration with Local Chain
  • GitHub Check: pytest-docker
  • GitHub Check: mypy
  • GitHub Check: pytest - Unit Tests
🔇 Additional comments (10)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (10)

1-33: LGTM! Well-structured imports and dependencies.

The imports are properly organized and include all necessary components for the arbitrage agent functionality. The dependencies on prediction market agent tooling, web3, and contract interfaces are appropriate for a Seer market arbitrage agent.


35-43: Clean enum definitions for arbitrage strategy types.

The enum definitions clearly distinguish between under-estimated and over-estimated probability scenarios, and between cost and revenue calculations. This provides good type safety and code clarity.


45-58: Configuration parameters are well-defined.

The agent properly restricts itself to Seer markets and sets reasonable default limits for trading amounts. The epsilon value and maximum trade amounts provide good risk controls.


60-66: Proper market type validation in run method.

The validation ensures the agent only operates on supported markets, preventing misuse on incompatible market types.


67-99: Comprehensive market validation logic.

The before_process_market method performs thorough validation:

  • Ensures market is SeerAgentMarket type
  • Checks for complete outcome token pool data
  • Excludes multiresult markets (appropriate for this arbitrage strategy)
  • Validates all outcomes are present in token pools

This prevents the agent from attempting arbitrage on incompatible markets.


100-154: Solid arbitrage detection and execution logic.

The process_market method correctly:

  • Identifies probability sum deviations using epsilon threshold
  • Executes different strategies for under/over-estimated probabilities
  • Handles exceptions gracefully with proper logging
  • Returns structured results with reasoning

The logic follows the arbitrage principle of exploiting probability imbalances.


156-174: Well-implemented merge arbitrage strategy.

The merge method properly:

  • Calculates optimal set size using cost-based calculation
  • Respects maximum trade limits
  • Executes buy-then-sell strategy for complete sets
  • Only proceeds with sells if buys were successful

This implements the correct strategy for under-estimated probabilities.


176-232: Robust over-estimated arbitrage implementation.

The _arbitrage_overestimated method handles:

  • Revenue-based optimal sizing calculation
  • Balance verification and scaling
  • Complete set minting via external contract
  • Proper error handling with exception chaining

The balance check and scaling logic prevents failed transactions due to insufficient funds.


303-332: Accurate marginal quote calculation.

The _get_marginal_quote method correctly implements:

  • Uniswap V3-style pricing with k=p*pool² formula
  • Proper fee application (proportional and absolute)
  • Different logic for cost vs revenue calculations
  • Infinity handling for insufficient liquidity

The mathematical model appears sound for the intended arbitrage strategy.


333-416: Comprehensive trade execution with proper error handling.

The _trade_complete_sets method:

  • Handles both buy and sell operations
  • Skips zero-probability outcomes appropriately
  • Tracks failed trades and lost amounts
  • Provides detailed logging for monitoring
  • Uses proper exception chaining

The position checking for sells and amount calculations appear correct.

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 (2)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (2)

220-220: Exception chaining issue already flagged.

This line has proper exception chaining implemented, addressing the previous review feedback.


402-404: Exception chaining properly implemented.

The exception chaining with from e correctly preserves the original exception context, addressing previous review feedback.

🧹 Nitpick comments (4)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (2)

208-210: Remove unused variable assignment.

The collateral_token_address variable is assigned but never used, as indicated by static analysis.

-            collateral_token_address = Web3.to_checksum_address(
-                market.get_collateral_token_contract().address
-            )

267-267: Consider replacing lambda expressions with proper functions.

Static analysis suggests replacing lambda expressions with def statements for better readability and debugging.

-            good = lambda q: q < target
+            def good(q):
+                return q < target
-            good = lambda q: q > target
+            def good(q):
+                return q > target

Also applies to: 279-279

prediction_market_agent/agents/think_thoroughly_agent/benchmark.py (1)

41-58: TestAgentMarket usage improves benchmark testability.

The change from abstract AgentMarket to concrete TestAgentMarket provides a working implementation for benchmarking without external dependencies.

Consider updating the return type annotation for consistency:

-def build_binary_agent_market_from_question(question: str) -> AgentMarket:
+def build_binary_agent_market_from_question(question: str) -> TestAgentMarket:
prediction_market_agent/agents/known_outcome_agent/benchmark.py (1)

50-64: TestAgentMarket provides concrete implementation for testing.

The change enables proper benchmark testing with a concrete market implementation instead of relying on abstract classes.

Consider updating the return type annotation for consistency:

-    def to_market(self) -> AgentMarket:
+    def to_market(self) -> TestAgentMarket:
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2c1be90 and de1fa77.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (4)
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (1 hunks)
  • prediction_market_agent/agents/known_outcome_agent/benchmark.py (2 hunks)
  • prediction_market_agent/agents/think_thoroughly_agent/benchmark.py (2 hunks)
  • prediction_market_agent/utils/test_markets.py (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • prediction_market_agent/utils/test_markets.py
🧰 Additional context used
🧠 Learnings (9)
📓 Common learnings
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-10-08T17:30:32.487Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the `prediction_market_agent` codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the `answer_binary_market` method is correctly positioned outside the `if`-`else` blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-07-26T08:54:53.258Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.
📚 Learning: in `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the ...
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:68-82
Timestamp: 2024-10-24T08:54:37.016Z
Learning: In `prediction_market_agent/agents/metaculus_agent/deploy.py`, the `return answer` statement in the `answer_binary_market` method is correctly positioned outside the `if`-`else` blocks. Ensure to double-check code indentation and control flow before suggesting changes related to unreachable code or indentation issues.

Applied to files:

  • prediction_market_agent/agents/think_thoroughly_agent/benchmark.py
  • prediction_market_agent/agents/known_outcome_agent/benchmark.py
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: in `think_thoroughly_agent.py`, the function `convert_to_utc_datetime` is imported from `prediction_...
Learnt from: evangriffiths
PR: gnosis/prediction-market-agent#491
File: prediction_market_agent/agents/think_thoroughly_agent/think_thoroughly_agent.py:287-287
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In `think_thoroughly_agent.py`, the function `convert_to_utc_datetime` is imported from `prediction_market_agent_tooling.tools.utils`.

Applied to files:

  • prediction_market_agent/agents/think_thoroughly_agent/benchmark.py
  • prediction_market_agent/agents/known_outcome_agent/benchmark.py
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: if https://github.com//issues/253 is resolved, the dummy build_agent c...
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: scripts/deployed_general_agent_viewer.py:131-131
Timestamp: 2024-07-03T06:57:12.034Z
Learning: If https://github.com/gnosis/prediction-market-agent/issues/253 is resolved, the dummy build_agent could be replaced with `build_agent_functions`.

Applied to files:

  • prediction_market_agent/agents/think_thoroughly_agent/benchmark.py
  • prediction_market_agent/agents/known_outcome_agent/benchmark.py
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: in the `prediction_market_agent` codebase, prioritize readability over concise code, even when conci...
Learnt from: kongzii
PR: gnosis/prediction-market-agent#529
File: prediction_market_agent/agents/metaculus_agent/deploy.py:57-62
Timestamp: 2024-10-24T08:55:13.200Z
Learning: In the `prediction_market_agent` codebase, prioritize readability over concise code, even when concise versions are functionally equivalent.

Applied to files:

  • prediction_market_agent/agents/think_thoroughly_agent/benchmark.py
  • prediction_market_agent/agents/known_outcome_agent/benchmark.py
  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: the user is interested in exploring the possibility of supporting multiple function calls in a singl...
Learnt from: kongzii
PR: gnosis/prediction-market-agent#337
File: prediction_market_agent/agents/microchain_agent/prompts.py:11-11
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The user is interested in exploring the possibility of supporting multiple function calls in a single run for the agent in the `prediction_market_agent/agents/microchain_agent/prompts.py` file.

Applied to files:

  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: the function `omen_finalize_and_resolve_and_claim_back_all_markets_based_on_others_tx` includes the ...
Learnt from: evangriffiths
PR: gnosis/prediction-market-agent#503
File: prediction_market_agent/agents/replicate_to_omen_agent/deploy.py:68-70
Timestamp: 2024-10-16T07:08:04.738Z
Learning: The function `omen_finalize_and_resolve_and_claim_back_all_markets_based_on_others_tx` includes the `realitio_bond` parameter.

Applied to files:

  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: in `prediction_market_agent/agents/goal_manager.py`, when reviewing the method `get_unique_evaluated...
Learnt from: evangriffiths
PR: gnosis/prediction-market-agent#501
File: prediction_market_agent/agents/goal_manager.py:0-0
Timestamp: 2024-10-08T17:30:32.487Z
Learning: In `prediction_market_agent/agents/goal_manager.py`, when reviewing the method `get_unique_evaluated_goals`, avoid suggesting to replace lists with sets for uniqueness checks when the number of elements is small, as lists may be faster than sets in such cases.

Applied to files:

  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
📚 Learning: the function name and docstring for `get_function_useage_from_history` in `prediction_market_agent/a...
Learnt from: kongzii
PR: gnosis/prediction-market-agent#301
File: prediction_market_agent/agents/microchain_agent/utils.py:122-142
Timestamp: 2024-07-03T06:52:20.555Z
Learning: The function name and docstring for `get_function_useage_from_history` in `prediction_market_agent/agents/microchain_agent/utils.py` should use "usage" instead of "useage".

Applied to files:

  • prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py
🧬 Code Graph Analysis (2)
prediction_market_agent/agents/think_thoroughly_agent/benchmark.py (1)
prediction_market_agent/utils/test_markets.py (1)
  • TestAgentMarket (6-21)
prediction_market_agent/agents/known_outcome_agent/benchmark.py (1)
prediction_market_agent/utils/test_markets.py (1)
  • TestAgentMarket (6-21)
🪛 Ruff (0.12.2)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py

208-208: Local variable collateral_token_address is assigned to but never used

Remove assignment to unused variable collateral_token_address

(F841)


267-267: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)


279-279: Do not assign a lambda expression, use a def

Rewrite good as a def

(E731)

🔇 Additional comments (12)
prediction_market_agent/agents/full_set_collective_arbitrage_agent/deploy.py (10)

1-30: Imports look comprehensive and well-organized.

The imports properly cover all necessary components for the arbitrage agent implementation.


32-40: Enums provide clear type safety for arbitrage operations.

The ArbitrageType and CalculationType enums enhance code readability and type safety.


42-56: Class initialization properly configured for Seer markets.

The restriction to MarketType.SEER in supported_markets correctly limits the agent to markets where this arbitrage strategy is viable, addressing previous feedback about market compatibility.


57-62: Market type validation ensures safe operation.

The validation check prevents the agent from running on unsupported market types.


64-96: Comprehensive market validation prevents incompatible market processing.

The validation logic effectively filters out markets that cannot be processed by this arbitrage strategy, including multiresult markets and those missing complete outcome token data.


97-151: Core arbitrage detection logic correctly identifies opportunities.

The probability sum analysis with epsilon thresholds effectively identifies both under-estimated and over-estimated scenarios for arbitrage execution.


153-171: Merge arbitrage logic correctly implements buy-low-sell-high strategy.

The sequential execution of buy then sell trades ensures proper token availability, and trade size limits provide appropriate risk management.


224-291: Sophisticated binary search optimization for trade sizing.

The mathematical approach using binary search to find optimal trade quantities is well-implemented and handles edge cases appropriately.


293-322: Mathematical implementation of marginal quote calculation is sophisticated.

The marginal cost and revenue calculations properly account for market depth, fees, and liquidity constraints.


323-406: Comprehensive trade execution with proper error handling.

The method correctly handles both buy and sell operations for complete sets, with per-outcome error handling and detailed logging.

prediction_market_agent/agents/think_thoroughly_agent/benchmark.py (1)

33-33: Import addition supports benchmark testing improvements.

The addition of TestAgentMarket import enables the use of a concrete test market implementation for benchmarking.

prediction_market_agent/agents/known_outcome_agent/benchmark.py (1)

20-22: Import updates align with test market implementation pattern.

The import changes properly support the transition to using TestAgentMarket for benchmarking, consistent with other agent benchmark files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants