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

Post order using cow-py #580

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

Post order using cow-py #580

wants to merge 7 commits into from

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Jan 10, 2025

No description provided.

Copy link

coderabbitai bot commented Jan 10, 2025

Walkthrough

The pull request introduces enhancements to the prediction market agent tooling, focusing on token swap functionality using the CoW protocol. The changes include adding a new method to generate Ethereum accounts from private keys, implementing a comprehensive token swap mechanism with asynchronous status checking, and creating a corresponding integration test to validate the swap functionality.

Changes

File Change Summary
prediction_market_agent_tooling/config.py Added get_account() method to APIKeys class to generate a LocalAccount from a private key
prediction_market_agent_tooling/tools/cow/cow_order.py Introduced two methods: swap_tokens_waiting() and swap_tokens_waiting_async() for handling token swaps with status monitoring
tests_integration_with_local_chain/tools/test_cow_order.py Added test_swap_tokens_waiting() integration test to verify token swap functionality

Sequence Diagram

sequenceDiagram
    participant User
    participant SwapFunction as swap_tokens_waiting()
    participant CoWSwapVault as CoW Swap Vault Relayer
    participant OrderAPI as CoW Order API

    User->>SwapFunction: Initiate token swap
    SwapFunction->>CoWSwapVault: Approve token access
    SwapFunction->>OrderAPI: Submit swap order
    SwapFunction->>OrderAPI: Periodically check order status
    alt Order Completed
        OrderAPI-->>SwapFunction: Return order metadata
        SwapFunction-->>User: Swap successful
    else Order Timeout
        SwapFunction-->>User: Raise TimeoutError
    end
Loading
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🧹 Nitpick comments (3)
prediction_market_agent_tooling/tools/cow_order.py (1)

107-107: Verify the signature before submission

After signing the order, consider verifying the signature to ensure it's correct before posting the order. This can prevent issues related to invalid signatures.

tests_integration_with_local_chain/tools/test_cow_order.py (1)

13-25: Enhance test reliability by mocking external dependencies

The test currently expects an exception due to insufficient balance, which depends on external conditions. Consider mocking the external API calls or setting up a controlled test environment to make the test deterministic and reliable.

prediction_market_agent_tooling/config.py (1)

189-194: Cache the LocalAccount instance

Repeatedly creating a LocalAccount can be inefficient. Cache the account instance after the first creation to improve performance.

Apply this diff to cache the account:

def get_account(self) -> LocalAccount:
    if not hasattr(self, "_local_account"):
        self._local_account = Account.from_key(
            self.bet_from_private_key.get_secret_value()
        )
    return self._local_account
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b81a3f7 and 05c64c3.

📒 Files selected for processing (3)
  • prediction_market_agent_tooling/config.py (2 hunks)
  • prediction_market_agent_tooling/tools/cow_order.py (1 hunks)
  • tests_integration_with_local_chain/tools/test_cow_order.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: pytest - Python 3.12.x - Unit Tests
  • GitHub Check: pytest - Python 3.11.x - Unit Tests
  • GitHub Check: pytest - Python 3.10.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.10.x - Integration Tests
  • GitHub Check: pytest - Python 3.10.x - Unit Tests
  • GitHub Check: mypy
🔇 Additional comments (3)
prediction_market_agent_tooling/tools/cow_order.py (3)

66-66: Handle potential exceptions when retrieving the account

The get_account() method may raise an exception if the private key is missing or invalid. Consider adding error handling to manage this scenario gracefully.


80-86: Validate token addresses before use

Ensure that sell_token and buy_token are valid and checksummed addresses before proceeding. This helps prevent errors due to incorrect address formats.


130-152: Ensure all required order fields are accurate

When creating OrderCreation, double-check that all fields are correctly populated and formatted according to the API requirements. Missing or incorrect fields may lead to order rejection.

Comment on lines 73 to 78
ContractERC20OnGnosisChain(address=sell_token).approve(
api_keys,
Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
amount_wei=amount_wei,
web3=web3,
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add error handling for token approval

The approve function may fail due to various reasons (e.g., network issues, insufficient funds). It's recommended to handle exceptions to ensure the approval process is robust.

Apply this diff to add error handling:

try:
    ContractERC20OnGnosisChain(address=sell_token).approve(
        api_keys,
        Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
        amount_wei=amount_wei,
        web3=web3,
    )
except Exception as e:
    # Handle exception appropriately
    raise RuntimeError(f"Token approval failed: {e}")

Comment on lines 49 to 53
return asyncio.run(
swap_tokens_async(
amount, sell_token, buy_token, api_keys, chain, app_data, env, web3
)
)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using asyncio.run() in libraries

Using asyncio.run() within library code can cause issues if the caller is already running an event loop (e.g., in an asynchronous context). Consider refactoring swap_tokens to be asynchronous or providing separate synchronous and asynchronous interfaces.

Apply this diff to refactor the function:

-def swap_tokens(
+async def swap_tokens(
     amount: xDai,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     api_keys: APIKeys,
     chain: Chain = Chain.GNOSIS,
     app_data: str = ZERO_APP_DATA,
     env: Envs = "prod",
     web3: Web3 | None = None,
 ) -> CompletedOrder:
-    # CoW library uses async, so we need to wrap the call in asyncio.run for us to use it.
-    return asyncio.run(
-        swap_tokens_async(
-            amount, sell_token, buy_token, api_keys, chain, app_data, env, web3
-        )
-    )
+    return await swap_tokens_async(
+        amount, sell_token, buy_token, api_keys, chain, app_data, env, web3
+    )
📝 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
return asyncio.run(
swap_tokens_async(
amount, sell_token, buy_token, api_keys, chain, app_data, env, web3
)
)
async def swap_tokens(
amount: xDai,
sell_token: ChecksumAddress,
buy_token: ChecksumAddress,
api_keys: APIKeys,
chain: Chain = Chain.GNOSIS,
app_data: str = ZERO_APP_DATA,
env: Envs = "prod",
web3: Web3 | None = None,
) -> CompletedOrder:
return await swap_tokens_async(
amount, sell_token, buy_token, api_keys, chain, app_data, env, web3
)

@@ -184,6 +186,12 @@ def sqlalchemy_db_url(self) -> SecretStr:
self.SQLALCHEMY_DB_URL, "SQLALCHEMY_DB_URL missing in the environment."
)

def get_account(self) -> LocalAccount:
acc: LocalAccount = Account.from_key(
self.bet_from_private_key.get_secret_value()
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Secure handling of private keys

Ensure that the private key is never logged or exposed in error messages. Consider adding validation to check if the private key is in the correct format and handle any exceptions securely.

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

🧹 Nitpick comments (1)
tests_integration_with_local_chain/tools/test_cow_order.py (1)

17-18: Initialize contract addresses outside function call for clarity

Passing function calls directly as arguments can make the code harder to read and debug, especially if an exception occurs during initialization. Initializing sell_token and buy_token addresses before the function call improves readability and error handling.

Refactor as follows:

def test_swap_tokens_waiting(local_web3: Web3, test_keys: APIKeys) -> None:
    sell_token_address = WrappedxDaiContract().address
    buy_token_address = sDaiContract().address

    with pytest.raises(InsufficientBalanceError) as e:
        swap_tokens_waiting(
            amount=xdai_type(0.1),
            sell_token=sell_token_address,
            buy_token=buy_token_address,
            api_keys=test_keys,
            env="staging",
            web3=local_web3,
        )
    # Rest of the test code...
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 05c64c3 and 0ce94cb.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (2)
  • prediction_market_agent_tooling/tools/cow/cow_order.py (1 hunks)
  • tests_integration_with_local_chain/tools/test_cow_order.py (1 hunks)
🔇 Additional comments (2)
prediction_market_agent_tooling/tools/cow/cow_order.py (1)

33-33: Ensure type hint compatibility with Python versions below 3.10

The type hint Web3 | None uses the union operator |, which is only supported in Python 3.10 and above. If your project targets earlier Python versions, consider using Optional[Web3] from the typing module for compatibility.

Apply this diff for compatibility:

+from typing import Optional
 from web3 import Web3

 def swap_tokens_waiting(
     amount: xDai,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     api_keys: APIKeys,
     chain: Chain = Chain.GNOSIS,
     env: Envs = "prod",
-    web3: Web3 | None = None,
+    web3: Optional[Web3] = None,
 ) -> OrderMetaData:

Please verify the project's Python version compatibility requirements.

tests_integration_with_local_chain/tools/test_cow_order.py (1)

14-15: 🛠️ Refactor suggestion

Catch specific exceptions instead of the base Exception

Using pytest.raises(Exception) catches all exceptions, which could mask unexpected errors. It's better to catch the specific exception you expect, ensuring the test only passes when the intended error occurs.

Apply this diff to catch a specific exception:

 def test_swap_tokens_waiting(local_web3: Web3, test_keys: APIKeys) -> None:
-    with pytest.raises(Exception) as e:
+    from cow_py.exceptions import InsufficientBalanceError
+    with pytest.raises(InsufficientBalanceError) as e:
         swap_tokens_waiting(
             amount=xdai_type(0.1),
             sell_token=WrappedxDaiContract().address,
             buy_token=sDaiContract().address,
             api_keys=test_keys,
             env="staging",
             web3=local_web3,
         )
     # This is raised in `post_order`, which is the last call when swapping tokens.
     # Anvil's accounts don't have any balance on the real chain, so this is expected.
     # It tests that all the logic behind calling CoW APIs is working correctly.
-    assert "InsufficientBalance" in str(e)
+    assert "InsufficientBalance" in str(e.value)

Please confirm that InsufficientBalanceError is the correct exception class raised by the swap_tokens_waiting function. If not, replace it with the appropriate exception.

Comment on lines +74 to +77
async with httpx.AsyncClient() as client:
response = await client.get(order.url)
order_metadata = OrderMetaData.model_validate(response.json())

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add exception handling for HTTP request failures

Currently, the HTTP GET request to order.url does not handle potential exceptions. Network errors like timeouts or connection issues could raise unhandled exceptions, causing the application to crash. It's important to handle httpx.RequestError to maintain application stability.

Apply this diff to add exception handling:

         while True:
             async with httpx.AsyncClient() as client:
+                try:
                     response = await client.get(order.url)
                     order_metadata = OrderMetaData.model_validate(response.json())
+                except httpx.RequestError as e:
+                    # Handle the exception (e.g., log the error or retry)
+                    print(f"Network error occurred: {e}")
+                    await asyncio.sleep(3.14)
+                    continue

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

Comment on lines +46 to +51
# CoW library uses async, so we need to wrap the call in asyncio.run for us to use it.
return asyncio.run(
swap_tokens_waiting_async(
amount_wei, sell_token, buy_token, account, chain, env
)
)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using asyncio.run() inside library code to prevent event loop conflicts

Using asyncio.run() within a library function like swap_tokens_waiting can lead to issues if the caller is already running an event loop (common in asynchronous applications). This can cause a RuntimeError due to the event loop being already running. Instead, consider making swap_tokens_waiting an asynchronous function or provide both synchronous and asynchronous interfaces.

Apply this diff to refactor the function:

-def swap_tokens_waiting(
+async def swap_tokens_waiting(
     amount: xDai,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     api_keys: APIKeys,
     chain: Chain = Chain.GNOSIS,
     env: Envs = "prod",
     web3: Web3 | None = None,
 ) -> OrderMetaData:
     amount_wei = xdai_to_wei(amount)
     account = api_keys.get_account()

     # Approve the CoW Swap Vault Relayer to get the sell token.
     ContractERC20OnGnosisChain(address=sell_token).approve(
         api_keys,
         Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
         amount_wei=amount_wei,
         web3=web3,
     )

     # CoW library uses async, so we need to call the async function directly.
-    return asyncio.run(
-        swap_tokens_waiting_async(
-            amount_wei, sell_token, buy_token, account, chain, env
-        )
-    )
+    return await swap_tokens_waiting_async(
+        amount_wei, sell_token, buy_token, account, chain, env
+    )
📝 Committable suggestion

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

Suggested change
# CoW library uses async, so we need to wrap the call in asyncio.run for us to use it.
return asyncio.run(
swap_tokens_waiting_async(
amount_wei, sell_token, buy_token, account, chain, env
)
)
async def swap_tokens_waiting(
amount: xDai,
sell_token: ChecksumAddress,
buy_token: ChecksumAddress,
api_keys: APIKeys,
chain: Chain = Chain.GNOSIS,
env: Envs = "prod",
web3: Web3 | None = None,
) -> OrderMetaData:
amount_wei = xdai_to_wei(amount)
account = api_keys.get_account()
# Approve the CoW Swap Vault Relayer to get the sell token.
ContractERC20OnGnosisChain(address=sell_token).approve(
api_keys,
Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
amount_wei=amount_wei,
web3=web3,
)
# CoW library uses async, so we need to call the async function directly.
return await swap_tokens_waiting_async(
amount_wei, sell_token, buy_token, account, chain, env
)

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

♻️ Duplicate comments (2)
prediction_market_agent_tooling/tools/cow/cow_order.py (2)

40-45: ⚠️ Potential issue

Avoid using asyncio.run() inside library code to prevent event loop conflicts

Using asyncio.run() within a library function can cause RuntimeError if the caller is already running an event loop.

Apply this diff to refactor the function:

-def swap_tokens_waiting(
+async def swap_tokens_waiting(
     amount: xDai,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     api_keys: APIKeys,
     chain: Chain = Chain.GNOSIS,
     env: Envs = "prod",
     web3: Web3 | None = None,
 ) -> OrderMetaData:
     amount_wei = xdai_to_wei(amount)
     account = api_keys.get_account()

     # Approve the CoW Swap Vault Relayer to get the sell token.
     ContractERC20OnGnosisChain(address=sell_token).approve(
         api_keys,
         Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
         amount_wei=amount_wei,
         web3=web3,
     )

-    return asyncio.run(
-        swap_tokens_waiting_async(
-            amount_wei, sell_token, buy_token, account, chain, env
-        )
-    )
+    return await swap_tokens_waiting_async(
+        amount_wei, sell_token, buy_token, account, chain, env
+    )

68-71: ⚠️ Potential issue

Add exception handling for HTTP request failures

The HTTP GET request lacks error handling for network issues.

Apply this diff to add exception handling:

         while True:
             async with httpx.AsyncClient() as client:
+                try:
                     response = await client.get(order.url)
                     order_metadata = OrderMetaData.model_validate(response.json())
+                except httpx.RequestError as e:
+                    print(f"Network error occurred: {e}")
+                    await asyncio.sleep(3.14)
+                    continue
🧹 Nitpick comments (2)
prediction_market_agent_tooling/tools/cow/cow_order.py (2)

82-82: Implement exponential backoff for polling

The constant sleep time of 3.14 seconds could be inefficient and may cause unnecessary load on the server.

Consider implementing exponential backoff:

+    retry_count = 0
+    base_delay = 1.0
+    max_delay = 10.0
     while True:
         # ... existing code ...
-        await asyncio.sleep(3.14)
+        delay = min(base_delay * (2 ** retry_count), max_delay)
+        retry_count += 1
+        await asyncio.sleep(delay)

79-80: Enhance timeout error handling

The timeout error could provide more context about the order status.

Consider enhancing the error message:

         if utcnow() - start_time > timeout:
-            raise TimeoutError("Timeout waiting for order to be completed.")
+            raise TimeoutError(
+                f"Order {order.uid} timed out after {timeout.seconds}s. "
+                f"Last known status: {order_metadata.status}"
+            )
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0ce94cb and d16a7e5.

📒 Files selected for processing (1)
  • prediction_market_agent_tooling/tools/cow/cow_order.py (1 hunks)
🔇 Additional comments (1)
prediction_market_agent_tooling/tools/cow/cow_order.py (1)

5-8: Verify cow-py package availability

The code depends on the cow-py package which, according to the PR objectives, is not yet released on PyPI. This could cause deployment issues.

Run this script to check package availability:

✅ Verification successful

Package installation is configured but could be improved

The cow-py package is properly configured as a git dependency in pyproject.toml, but consider these improvements:

  • Use HTTPS URL instead of SSH to improve compatibility
  • Reference the official repository (cowdao-grants/cow-py) instead of a fork
  • Pin to a specific commit or tag instead of the main branch for better stability
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if cow-py is available on PyPI
curl -s https://pypi.org/pypi/cow-py/json || echo "Package not found on PyPI"

# Check if there are any pending PRs or issues about the PyPI release
gh api graphql -f query='
{
  repository(owner: "cowdao-grants", name: "cow-py") {
    issues(first: 5, states: OPEN, labels: ["pypi", "release"]) {
      nodes {
        title
        url
      }
    }
  }
}'

Length of output: 327


Script:

#!/bin/bash
# Check for requirements files
fd requirements.txt

# Check for setup.py or pyproject.toml
fd "setup.py|pyproject.toml"

# Check README for installation instructions
fd "README.md" --exec cat {} \; | grep -A 5 -i "install"

# Check if cow-py is installed from git
fd "requirements|setup.py|pyproject.toml" --exec grep -l "cow-py\|cow_py" {}

Length of output: 1265


Script:

#!/bin/bash
# Display the dependencies section from pyproject.toml
cat pyproject.toml | grep -A 20 "\[tool.poetry.dependencies\]"

Length of output: 613


Script:

#!/bin/bash
# Display the entire pyproject.toml
cat pyproject.toml

Length of output: 2244

pyproject.toml Outdated
@@ -54,6 +54,8 @@ pinatapy-vourhey = "^0.2.0"
hishel = "^0.0.31"
pytest-postgresql = "^6.1.1"
optuna = { version = "^4.1.0", optional = true}
httpx = "^0.25.2"
cow-py = {git = "https://github.com/kongzii/cow-py.git", branch = "main"}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

Need to wait until cow-py is properly released, but otherwise good to review

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

♻️ Duplicate comments (2)
prediction_market_agent_tooling/tools/cow/cow_order.py (2)

41-46: ⚠️ Potential issue

Avoid using asyncio.run() inside library code.

Using asyncio.run() within a library function can cause RuntimeError if the caller is already running an event loop. The function should be made async to allow callers to manage their own event loops.

-def swap_tokens_waiting(
+async def swap_tokens_waiting(
     amount: xDai,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     api_keys: APIKeys,
     chain: Chain = Chain.GNOSIS,
     env: Envs = "prod",
     web3: Web3 | None = None,
 ) -> OrderMetaData:
     amount_wei = xdai_to_wei(amount)
     account = api_keys.get_account()

     # Approve the CoW Swap Vault Relayer to get the sell token.
     ContractERC20OnGnosisChain(address=sell_token).approve(
         api_keys,
         Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value),
         amount_wei=amount_wei,
         web3=web3,
     )

-    return asyncio.run(
-        swap_tokens_waiting_async(
-            amount_wei, sell_token, buy_token, account, chain, env
-        )
-    )
+    return await swap_tokens_waiting_async(
+        amount_wei, sell_token, buy_token, account, chain, env
+    )

70-73: ⚠️ Potential issue

Add exception handling for HTTP request failures.

The HTTP GET request should handle potential network errors to maintain application stability.

         while True:
             async with httpx.AsyncClient() as client:
+                try:
                     response = await client.get(order.url)
                     order_metadata = OrderMetaData.model_validate(response.json())
+                except httpx.RequestError as e:
+                    logger.warning(f"Network error occurred: {e}")
+                    await asyncio.sleep(3.14)
+                    continue
🧹 Nitpick comments (1)
prediction_market_agent_tooling/tools/cow/cow_order.py (1)

84-84: Make the polling interval configurable.

The sleep duration of 3.14 seconds is hardcoded. Consider making it configurable through a parameter with a default value.

 async def swap_tokens_waiting_async(
     amount_wei: Wei,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     account: LocalAccount,
     chain: Chain,
     env: Envs,
-    timeout: timedelta = timedelta(seconds=60),
+    timeout: timedelta = timedelta(seconds=60),
+    polling_interval: float = 3.14,
 ) -> OrderMetaData:
     # ... rest of the implementation ...
-        await asyncio.sleep(3.14)
+        await asyncio.sleep(polling_interval)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d16a7e5 and ea544b0.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (1)
  • prediction_market_agent_tooling/tools/cow/cow_order.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: pytest - Python 3.12.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.12.x - Unit Tests
  • GitHub Check: pytest - Python 3.11.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.11.x - Unit Tests
  • GitHub Check: pytest - Python 3.10.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.10.x - Unit Tests
🔇 Additional comments (2)
prediction_market_agent_tooling/tools/cow/cow_order.py (2)

1-19: LGTM! Well-organized imports.

The imports are logically grouped and include all necessary dependencies for the token swap functionality.


49-83: LGTM! Well-implemented timeout mechanism.

The implementation includes a proper timeout mechanism with clear status checking logic. The use of OrderStatus enum for state management and the timeout implementation are particularly well done.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (3)
prediction_market_agent_tooling/tools/cow/cow_order.py (3)

41-41: Update the comment to accurately reflect the async handling recommendation.

The current comment suggests that wrapping with asyncio.run() is the solution, which is misleading. Instead, the comment should explain that the function should be async to allow proper integration with existing event loops.

-    # CoW library uses async, so we need to wrap the call in asyncio.run for us to use it.
+    # CoW library uses async, so this function should also be async to properly integrate with existing event loops.

84-84: Make the polling interval configurable and implement exponential backoff.

The current implementation uses a fixed sleep duration of 3.14 seconds. Consider:

  1. Making the polling interval configurable through a parameter
  2. Implementing exponential backoff to reduce unnecessary API calls
 async def swap_tokens_waiting_async(
     amount_wei: Wei,
     sell_token: ChecksumAddress,
     buy_token: ChecksumAddress,
     account: LocalAccount,
     chain: Chain,
     env: Envs,
     timeout: timedelta = timedelta(seconds=60),
+    initial_poll_interval: float = 1.0,
+    max_poll_interval: float = 15.0,
 ) -> OrderMetaData:
     order = await swap_tokens(
         amount=amount_wei,
         sell_token=sell_token,
         buy_token=buy_token,
         account=account,
         chain=chain,
         env=env,
     )
     logger.info(f"Order created: {order}")
     start_time = utcnow()
+    current_interval = initial_poll_interval

     while True:
         async with httpx.AsyncClient() as client:
             response = await client.get(order.url)
             order_metadata = OrderMetaData.model_validate(response.json())

         if order_metadata.status in (
             OrderStatus.fulfilled,
             OrderStatus.cancelled,
             OrderStatus.expired,
         ):
             return order_metadata

         if utcnow() - start_time > timeout:
             raise TimeoutError("Timeout waiting for order to be completed.")

-        await asyncio.sleep(3.14)
+        await asyncio.sleep(current_interval)
+        current_interval = min(current_interval * 2, max_poll_interval)

70-71: Validate the order URL before making the request.

While the URL comes from the CoW API, it's good practice to validate URLs before making requests to prevent potential security issues.

+from urllib.parse import urlparse
+
+def is_valid_order_url(url: str) -> bool:
+    try:
+        result = urlparse(url)
+        return all([result.scheme in ("http", "https"), result.netloc])
+    except Exception:
+        return False

 async def swap_tokens_waiting_async(...):
     # ...
     while True:
         async with httpx.AsyncClient() as client:
+            if not is_valid_order_url(order.url):
+                raise ValueError(f"Invalid order URL: {order.url}")
             response = await client.get(order.url)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ea544b0 and 5a26dd5.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (1)
  • prediction_market_agent_tooling/tools/cow/cow_order.py (1 hunks)
🔇 Additional comments (3)
prediction_market_agent_tooling/tools/cow/cow_order.py (3)

1-19: LGTM! Well-organized imports.

The imports are properly structured, separating external and internal dependencies, with all necessary modules included for the functionality.


41-46: Avoid using asyncio.run() inside library code.

Using asyncio.run() within a library function can lead to issues if the caller is already running an event loop. This can cause a RuntimeError.


70-73: Add exception handling for HTTP request failures.

The HTTP GET request to order.url should handle potential network errors to maintain application stability.

Comment on lines +23 to +25
# This is raised in `post_order` which is last call when swapping tokens, anvil's accounts don't have any balance on real chain, so this is expected,
# but still, it tests that all the logic behind calling CoW APIs is working correctly.
assert "InsufficientBalance" in str(e)
Copy link
Contributor

Choose a reason for hiding this comment

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

Nice!

Comment on lines +81 to +84
if utcnow() - start_time > timeout:
raise TimeoutError("Timeout waiting for order to be completed.")

await asyncio.sleep(3.14)
Copy link
Contributor

Choose a reason for hiding this comment

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

I would log something so that the user knows it's in process.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants