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

Withdraw to keeping erc20 token on missing places #628

Merged
merged 7 commits into from
Feb 27, 2025
Merged

Conversation

kongzii
Copy link
Contributor

@kongzii kongzii commented Feb 26, 2025

deploy please

Copy link

coderabbitai bot commented Feb 26, 2025

Walkthrough

This pull request introduces a new method in the OmenPosition class to retrieve a collateral token contract, with appropriate imports and web3 handling. Additionally, multiple methods and scripts throughout the project have been updated to set the auto_withdraw and auto_deposit flags to True by default, automating token management processes. Enhancements include additional logging in the auto-withdraw routines and updated function signatures for better control flow and error handling during token operations.

Changes

File(s) Change Summary
prediction_market_agent_tooling/markets/omen/data_models.py Added method get_collateral_token_contract in OmenPosition with conditional web3 usage and necessary imports from prediction_market_agent_tooling.tools.contract.
prediction_market_agent_tooling/markets/omen/omen.py Updated signatures of methods (sell_tokens, omen_redeem_full_position_tx, omen_remove_fund_market_tx, redeem_from_all_user_positions), setting auto_withdraw=True by default and adjusting balance and withdrawal logic.
prediction_market_agent_tooling/tools/omen/sell_positions.py Changed default value of auto_withdraw parameter in the sell_all function from False to True.
prediction_market_agent_tooling/tools/tokens/auto_withdraw.py Enhanced auto_withdraw_collateral_token with additional logging, early return when amount_wei is zero, and usage of wei_to_xdai for logging and token swap details.
scripts/(bet_omen.py, create_market_omen.py, create_market_seer.py, create_markets_from_sheet_omen.py, sell_all_omen.py) Updated default values for auto_deposit and auto_withdraw parameters to True, modifying the default behavior for automatic deposits and withdrawals across market and betting scripts.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant OmenPos as OmenPosition
    participant ContractInit as ContractERC20OnGnosisChain
    participant GnosisHelper as to_gnosis_chain_contract

    Caller->>OmenPos: get_collateral_token_contract(web3?)
    alt web3 provided
        OmenPos->>OmenPos: Use provided web3 instance
    else no web3
        OmenPos->>ContractInit: get_web3()
    end
    OmenPos->>OmenPos: init_collateral_token_contract(checksummed address, web3)
    OmenPos->>GnosisHelper: to_gnosis_chain_contract(result)
    GnosisHelper-->>OmenPos: Contract instance
    OmenPos-->>Caller: Return ContractERC20OnGnosisChain instance
Loading
sequenceDiagram
    participant WithdrawFunc as auto_withdraw_collateral_token
    participant Logger as Logger
    participant Contract as collateral_token_contract

    WithdrawFunc->>WithdrawFunc: Check if amount_wei == 0
    alt amount_wei is 0
        WithdrawFunc->>Logger: Log warning (no withdrawal)
        WithdrawFunc-->>Caller: Return early
    else amount_wei not 0
        WithdrawFunc->>Contract: Check token type
        alt token is KEEPING_ERC20_TOKEN
            WithdrawFunc->>Logger: Log info (no withdrawal will occur)
        else
            WithdrawFunc->>Logger: Log info (executing withdrawal)
            alt Contract is ContractERC20BaseClass
                WithdrawFunc->>Logger: Log info (swapping tokens with details)
            end
        end
    end
Loading

Possibly related PRs

  • Small fixes and improvements #259: The changes in the main PR are related to the modifications in the sell_tokens method of the omen.py file, specifically regarding the default value of the auto_withdraw parameter, which is also altered in the retrieved PR.
  • Refactoring ERC-4626 and support at other places #325: The changes in the main PR, specifically the addition of the get_collateral_token_contract method in the OmenPosition class, are related to the modifications in the retrieved PR that involve the handling of collateral tokens and the introduction of the init_collateral_token_contract function, which is directly referenced in both PRs.
  • Create markets with sDai as collateral #320: The changes in the main PR, specifically the addition of the get_collateral_token_contract method in the OmenPosition class, are directly related to the modifications in the retrieved PR, which also introduces a get_collateral_token_contract method in the omen_contracts.py file, enhancing the management of collateral tokens.

Suggested reviewers

  • evangriffiths

Tip

CodeRabbit's docstrings feature is now available as part of our Pro Plan! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. We would love to hear your feedback on Discord.


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ce7c54e and 3ec1770.

📒 Files selected for processing (1)
  • prediction_market_agent_tooling/markets/omen/omen.py (10 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: pytest - Python 3.12.x - Integration with Local Chain
  • GitHub Check: pytest - Python 3.12.x - Integration Tests
  • 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 - Integration 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 (11)
prediction_market_agent_tooling/markets/omen/omen.py (11)

83-83: Import added for KEEPING_ERC20_TOKEN.

This import is used to access the ERC20 token balance in the get_trade_balance method.


197-197: Default auto-withdraw now set to True.

Changed the default behavior to automatically withdraw tokens after liquidating existing positions, which helps prevent tokens from being stuck in the contract.


262-262: Changed default parameter value for sell_tokens method.

The auto_withdraw parameter now defaults to True instead of False, ensuring consistent behavior with the changes made in the liquidate_existing_positions method.


409-417: Enhanced trade balance calculation to include ERC20 token balance.

The get_trade_balance method now correctly includes the balance of KEEPING_ERC20_TOKEN in addition to native token balance, providing a more accurate representation of total available funds.


1067-1067: Added auto_withdraw parameter with default True.

Adding this parameter to the omen_redeem_full_position_tx function enables automatic withdrawal of tokens after redeeming positions by default, while still allowing it to be disabled if needed.


1079-1079: Added collateral token contract retrieval.

This line retrieves the collateral token contract which is needed for the auto-withdraw functionality added below.


1103-1125: Added balance tracking and auto-withdraw functionality for position redemption.

This code enhances the redemption process by:

  1. Tracking the collateral token balance before and after redemption
  2. Calculating and logging the amount redeemed
  3. Automatically withdrawing the collateral tokens if auto_withdraw is enabled

This prevents tokens from getting stuck in the contract and improves visibility into redemption amounts.


1163-1163: Added auto_withdraw parameter with default True.

Similar to other methods, adding this parameter to omen_remove_fund_market_tx standardizes the behavior across the codebase, enabling automatic withdrawal by default.


1214-1228: Added balance tracking and auto-withdraw functionality for fund removal.

This change improves the fund removal process by:

  1. Calculating the exact balance difference after the operation
  2. Logging the amount withdrawn with proper token symbol
  3. Automatically withdrawing tokens if auto_withdraw is enabled

This ensures users don't leave funds in the contract after removing liquidity.


1233-1233: Added auto_withdraw parameter with default True.

Adding this parameter to redeem_from_all_user_positions maintains consistency with the other methods, enabling automatic withdrawal by default while preserving flexibility.


1259-1285: Added collateral token handling and auto-withdraw for all user positions.

This enhancement:

  1. Retrieves the specific collateral token contract for each position
  2. Tracks balance changes before and after redemption
  3. Logs the exact amount redeemed with proper token symbol
  4. Automatically withdraws tokens if the auto_withdraw flag is enabled

This change completes the systematic implementation of auto-withdrawal functionality across the entire redemption workflow.

✨ Finishing Touches
  • 📝 Generate Docstrings

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.
  • @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: 1

🧹 Nitpick comments (2)
scripts/create_markets_from_sheet_omen.py (1)

34-34: Changed default behavior for auto_deposit to True

This change enables automatic deposits by default when creating markets from a spreadsheet. This provides consistency with other market creation scripts and improves the user experience by automating token handling.

Note that the example command on lines 40-46 still includes the --auto-deposit flag which is now redundant since it's the default behavior.

-        --auto-deposit \
prediction_market_agent_tooling/markets/omen/omen.py (1)

1099-1099: Enhanced position redemption with balance tracking and auto-withdrawal

Added balance tracking before and after position redemption, along with logging and automatic withdrawal of the collateral token if auto_withdraw is enabled. This ensures users can see how much was redeemed and automatically have those tokens withdrawn to their account.

The implementation:

  1. Tracks original balance before redemption
  2. Calculates the difference after redemption
  3. Logs the amount redeemed with the token symbol
  4. Automatically withdraws the redeemed amount if enabled

Consider adding error handling around the auto-withdrawal process in case it fails, to ensure the redemption operation itself is still considered successful even if the withdrawal encounters issues.

Also applies to: 1107-1120

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2ab431 and e2e07b9.

⛔ Files ignored due to path filters (1)
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (9)
  • prediction_market_agent_tooling/markets/omen/data_models.py (2 hunks)
  • prediction_market_agent_tooling/markets/omen/omen.py (10 hunks)
  • prediction_market_agent_tooling/tools/omen/sell_positions.py (1 hunks)
  • prediction_market_agent_tooling/tools/tokens/auto_withdraw.py (3 hunks)
  • scripts/bet_omen.py (2 hunks)
  • scripts/create_market_omen.py (1 hunks)
  • scripts/create_market_seer.py (1 hunks)
  • scripts/create_markets_from_sheet_omen.py (1 hunks)
  • scripts/sell_all_omen.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 (25)
scripts/create_market_omen.py (1)

32-32: Changed default behavior for auto_deposit to True

This change makes automatic deposits the default behavior when creating a market on Omen. Users won't need to explicitly enable auto-deposit anymore, but can still disable it if needed.

prediction_market_agent_tooling/tools/omen/sell_positions.py (1)

16-16: Changed default behavior for auto_withdraw to True

This change makes automatic withdrawals the default behavior when selling positions. This aligns with similar changes throughout the codebase to automate token management by default, improving user experience.

scripts/sell_all_omen.py (1)

13-13: Changed default behavior for auto_withdraw to True

This change enables automatic withdrawals by default when selling all positions, consistent with the changes in other files. This improves usability by automating token handling.

scripts/bet_omen.py (2)

26-26: Default auto_deposit value changed to True

The default value for auto_deposit has been changed from False to True, making automatic deposit the default behavior when buying outcomes on Omen.

This change aligns with similar changes in other scripts, providing a consistent user experience across the codebase.


64-64: Default auto_withdraw value changed to True

The default value for auto_withdraw has been changed from False to True, making automatic withdrawal the default behavior when selling outcomes on Omen.

This change improves user experience by automatically withdrawing tokens after selling positions, eliminating the need for a separate withdrawal step in most cases.

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

26-30: Added necessary imports for ERC20 contract handling

Added imports for working with ERC20 token contracts on the Gnosis chain, which will be used by the new get_collateral_token_contract method.


176-185: Added method to retrieve collateral token contract

New method get_collateral_token_contract has been added to the OmenPosition class to easily access the collateral token contract, with appropriate web3 handling.

This method enhances the class by providing convenient access to the collateral token contract, which will be useful for operations like withdrawals. The method properly handles the case when no web3 instance is provided by falling back to a default instance.

prediction_market_agent_tooling/tools/tokens/auto_withdraw.py (6)

5-5: Added logger import for enhanced logging

Added import for the logger module to provide better feedback during token withdrawal operations.


16-19: Added wei_to_xdai import for amount conversion in logs

Added wei_to_xdai import to convert Wei amounts to xDai for more readable logging messages.


35-40: Added early return for zero withdrawal amounts

Added a check to return early if the withdrawal amount is zero, preventing unnecessary operations and providing appropriate warnings.

This is a good defensive programming practice that avoids wasting gas on zero-value transactions and provides clear feedback to the user.


43-45: Added informative logging for keeping token scenario

Added logging to inform when the collateral token matches the keeping token, explaining why no withdrawal action is being taken.

This improves transparency and helps users understand the system's behavior when tokens are already in the desired format.


53-55: Added logging for ERC4626 token withdrawals

Added informative logging when withdrawing from an ERC4626 token directly into the keeping token, showing the amount and token symbols.

This provides valuable information for debugging and monitoring token movements.


62-64: Added logging for token swaps

Added informative logging when swapping tokens through DEX, showing the amount and token symbols involved in the transaction.

This enhances observability of token swapping operations, making it easier to track and debug transactions.

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

83-83: Added new import for KEEPING_ERC20_TOKEN

This import is required for the new implementation of the get_trade_balance method at line 411-412, which now uses the KEEPING_ERC20_TOKEN.balanceOf method instead of a previously used implementation.


197-197: Changed default behavior to auto-withdraw tokens

The auto_withdraw parameter is now set to True by default in the liquidate_existing_positions method, which will automatically withdraw collateral tokens after selling positions. This change is consistent with the PR's purpose of ensuring tokens are properly withdrawn in all relevant places.


262-262: Changed default behavior to auto-withdraw tokens

The auto_withdraw parameter is now set to True by default in the sell_tokens method. This ensures collateral tokens are automatically withdrawn after selling, improving the user experience by eliminating the need for an explicit withdrawal step.


411-412: Updated trade balance implementation to use KEEPING_ERC20_TOKEN

The get_trade_balance method now uses KEEPING_ERC20_TOKEN.balanceOf for retrieving the balance. This change makes the implementation more consistent with the token management approach used throughout the PR.


1063-1063: Added auto-withdraw parameter with default value True

Added the auto_withdraw parameter to the omen_redeem_full_position_tx method with a default value of True. This is consistent with the other methods modified in this PR and ensures tokens are automatically withdrawn after redemption.


1075-1075: Added retrieval of collateral token contract

Now retrieving the collateral token contract in the omen_redeem_full_position_tx method, which is necessary for the balance tracking and auto-withdrawal functionality added later in the method.


1159-1159: Added auto-withdraw parameter with default value True

Added the auto_withdraw parameter to the omen_remove_fund_market_tx method with a default value of True. This change is consistent with the other methods and ensures tokens are automatically withdrawn after removing funds from the market.


1166-1166: Updated docstring for better clarity

Updated the documentation to clarify how the collateral token works when removing funding. This improves the understanding of the token flow in the system.


1210-1210: Enhanced fund removal with balance tracking and auto-withdrawal

Similar to the position redemption enhancement, this modification:

  1. Properly types the balance difference as wei_type
  2. Improves logging by including the token symbol
  3. Adds automatic withdrawal of the collateral token if enabled

This ensures users can see how much was withdrawn from liquidity and automatically have those tokens transferred to their account.

Also applies to: 1214-1214, 1217-1224


1229-1229: Added auto-withdraw parameter with default value True

Added the auto_withdraw parameter to the redeem_from_all_user_positions method with a default value of True. This change is consistent with the other methods and ensures tokens are automatically withdrawn after redeeming from all user positions.


1255-1257: Added collateral token contract retrieval

Added code to retrieve the collateral token contract from the position, which is necessary for the balance tracking and auto-withdrawal functionality. This makes the implementation more robust by using the position-specific token contract.


1259-1259: Enhanced user position redemption with balance tracking and auto-withdrawal

Added balance tracking, logging improvements, and auto-withdrawal functionality to the process of redeeming from all user positions:

  1. Tracks original balance before redemption
  2. Calculates the difference after redemption
  3. Logs the amount redeemed with the token symbol
  4. Automatically withdraws the redeemed amount if enabled

This ensures users can track their redeemed amounts and have them automatically withdrawn without manual intervention.

Also applies to: 1267-1269, 1271-1271, 1274-1281

kongzii and others added 2 commits February 26, 2025 15:17
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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: 1

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e2e07b9 and 87beda9.

📒 Files selected for processing (1)
  • scripts/create_market_seer.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
scripts/create_market_seer.py

26-27: SyntaxError: Expected ')', found newline

⏰ Context from checks skipped due to timeout of 90000ms (7)
  • 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 - Integration Tests
  • GitHub Check: pytest - Python 3.10.x - Unit Tests
🔇 Additional comments (1)
scripts/create_market_seer.py (1)

46-46: 🛠️ Refactor suggestion

Default auto_deposit value changed to True

The default value for auto_deposit has been changed from False to True, making automatic deposit of funds the default behavior when creating a market on Seer. However, the docstring still states the default is False.

Update the docstring to reflect the correct default value:

-        auto_deposit (bool, optional): Whether to automatically deposit funds. Defaults to False.
+        auto_deposit (bool, optional): Whether to automatically deposit funds. Defaults to True.

Comment on lines 26 to 31
auto_deposit: bool = typer.Option(True),

"""
Parameters:
auto_deposit (bool, optional): Whether to automatically deposit funds. Defaults to True.
"""
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Critical syntax error: Incorrect placement of docstring.

The docstring is incorrectly placed inside the parameter list, which will cause a syntax error. Docstrings should be placed after the function signature, not within the parameter list.

Fix the syntax by moving the docstring outside the parameter list:

def main(
    question: str = typer.Option(),
    opening_time: datetime = typer.Option(),
    category: str = typer.Option(),
    initial_funds: str = typer.Option(),
    from_private_key: str = typer.Option(),
    safe_address: str = typer.Option(None),
    min_bond_xdai: int = typer.Option(0.01),
    language: str = typer.Option("en_US"),
    outcomes: list[str] = typer.Option(OMEN_BINARY_MARKET_OUTCOMES),
-    auto_deposit: bool = typer.Option(True),
-    
-    """
-    Parameters:
-        auto_deposit (bool, optional): Whether to automatically deposit funds. Defaults to True.
-    """
+    auto_deposit: bool = typer.Option(True),
) -> None:
    """
    Creates a market on Seer.

    Args:
        question (str): The question for the market.
        opening_time (datetime): The opening time for the market.
        category (str): The category of the market.
        initial_funds (str): The initial funds for the market.
        from_private_key (str): The private key to use for transactions.
        safe_address (str, optional): The safe address for transactions. Defaults to None.
        min_bond_xdai (int, optional): The minimum bond in xDai. Defaults to 0.01 xDai.
        language (str, optional): The language of the market. Defaults to "en".
        outcomes (list[str], optional): The outcomes for the market. Defaults to OMEN_BINARY_MARKET_OUTCOMES.
        auto_deposit (bool, optional): Whether to automatically deposit funds. Defaults to False.

    Returns:
        None
    """

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

🧰 Tools
🪛 Ruff (0.8.2)

26-27: SyntaxError: Expected ')', found newline

@kongzii kongzii merged commit f713bce into main Feb 27, 2025
15 of 17 checks passed
@kongzii kongzii deleted the peter/withdrawing branch February 27, 2025 09:44
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.

1 participant