-
Notifications
You must be signed in to change notification settings - Fork 6
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
base: main
Are you sure you want to change the base?
Conversation
WalkthroughThe 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
Sequence DiagramsequenceDiagram
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
✨ Finishing Touches
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this 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 submissionAfter 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 dependenciesThe 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 theLocalAccount
instanceRepeatedly 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
📒 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 accountThe
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 useEnsure that
sell_token
andbuy_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 accurateWhen 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.
ContractERC20OnGnosisChain(address=sell_token).approve( | ||
api_keys, | ||
Web3.to_checksum_address(CowContractAddress.VAULT_RELAYER.value), | ||
amount_wei=amount_wei, | ||
web3=web3, | ||
) |
There was a problem hiding this comment.
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}")
return asyncio.run( | ||
swap_tokens_async( | ||
amount, sell_token, buy_token, api_keys, chain, app_data, env, web3 | ||
) | ||
) |
There was a problem hiding this comment.
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.
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() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
There was a problem hiding this 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 clarityPassing function calls directly as arguments can make the code harder to read and debug, especially if an exception occurs during initialization. Initializing
sell_token
andbuy_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
⛔ 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.10The 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 usingOptional[Web3]
from thetyping
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 suggestionCatch 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 theswap_tokens_waiting
function. If not, replace it with the appropriate exception.
async with httpx.AsyncClient() as client: | ||
response = await client.get(order.url) | ||
order_metadata = OrderMetaData.model_validate(response.json()) | ||
|
There was a problem hiding this comment.
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.
# 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 | ||
) | ||
) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
# 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 | |
) |
There was a problem hiding this 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 issueAvoid using
asyncio.run()
inside library code to prevent event loop conflictsUsing
asyncio.run()
within a library function can causeRuntimeError
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 issueAdd 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 pollingThe 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 handlingThe 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
📒 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 availabilityThe 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 inpyproject.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.tomlLength 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"} |
There was a problem hiding this comment.
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
There was a problem hiding this 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 issueAvoid using
asyncio.run()
inside library code.Using
asyncio.run()
within a library function can causeRuntimeError
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 issueAdd 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
⛔ 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.
There was a problem hiding this 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:
- Making the polling interval configurable through a parameter
- 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
⛔ 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 usingasyncio.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 aRuntimeError
.
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.
# 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) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice!
if utcnow() - start_time > timeout: | ||
raise TimeoutError("Timeout waiting for order to be completed.") | ||
|
||
await asyncio.sleep(3.14) |
There was a problem hiding this comment.
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.
No description provided.