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

Added WithdrawFromTreasury function #643

Conversation

gabrielfior
Copy link
Contributor

No description provided.

@gabrielfior gabrielfior linked an issue Jan 15, 2025 that may be closed by this pull request
@gabrielfior gabrielfior requested a review from kongzii January 15, 2025 20:58
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

This pull request introduces changes to the NFT treasury game infrastructure, focusing on treasury management and withdrawal functionality. A new WithdrawFromTreasury class is added to handle treasury withdrawals, with specific requirements for NFT token ownership. The changes also involve renaming the treasury address constant from TREASURY_SAFE_ADDRESS to TREASURY_ADDRESS and modifying the deployment logic for treasury interactions. The modifications streamline the treasury management process and integrate a new withdrawal mechanism for NFT token holders.

Changes

File Change Summary
prediction_market_agent/agents/microchain_agent/nft_functions.py - Added WithdrawFromTreasury class
- Implemented description, example_args, and __call__ methods
- Updated NFT_FUNCTIONS list to include new class
- Modified ownerOf method to owner_of in OwnerOfNFT class
prediction_market_agent/agents/microchain_agent/nft_treasury_game/constants_nft_treasury_game.py - Renamed TREASURY_SAFE_ADDRESS to TREASURY_ADDRESS
- Updated treasury address to 0x624ad0db52e6b18afb4d36b8e79d0c2a74f3fc8a
prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py - Updated import to use new TREASURY_ADDRESS constant
- Changed usage in show_treasury_part function
prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py - Removed build_treasury_safe method
- Removed retrieve_treasury_owners method
- Added retrieve_total_number_of_keys method
- Updated treasury-related logic to use TREASURY_ADDRESS
prediction_market_agent/agents/microchain_agent/nft_treasury_game/contracts_nft_treasury_game.py - Modified ownerOf method to owner_of in ContractNFTFactoryOnGnosisChain class
prediction_market_agent/agents/microchain_agent/nft_treasury_game/tools_nft_treasury_game.py - Renamed TREASURY_SAFE_ADDRESS to TREASURY_ADDRESS in get_nft_game_status function

Sequence Diagram

sequenceDiagram
    participant Agent
    participant WithdrawFromTreasury
    participant SimpleTreasuryContract
    
    Agent->>WithdrawFromTreasury: Call withdrawal
    WithdrawFromTreasury->>SimpleTreasuryContract: Check NFT balance
    SimpleTreasuryContract-->>WithdrawFromTreasury: Verify balance
    WithdrawFromTreasury->>SimpleTreasuryContract: Withdraw funds
    SimpleTreasuryContract-->>WithdrawFromTreasury: Confirm withdrawal
    WithdrawFromTreasury-->>Agent: Return success message
Loading

Possibly related PRs

  • NFT functions for general agent #582: The changes in this PR involve modifications to the messages_functions.py file, which includes the addition of the SendPaidMessageToAnotherAgent class that utilizes the send_xdai_to function, similar to the treasury withdrawal process in the main PR's WithdrawFromTreasury class.
  • NFT Game - None sending cap, update prompts, set liquidity in PMs #630: This PR introduces enhancements to the nft_treasury_game_base_prompt function, which now includes dynamic messaging related to NFT ownership, aligning with the NFT-related functionalities introduced in the main PR.
  • Switch 5 nft agents to be seller agents #637: The addition of the nft_treasury_game_seller_prompt function in this PR complements the NFT functionalities by providing context for agents in the NFT treasury game, which is relevant to the new WithdrawFromTreasury class in the main PR.

Suggested reviewers

  • kongzii

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
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
prediction_market_agent/agents/microchain_agent/nft_functions.py (1)

118-118: Verify NFT_FUNCTIONS list order.

The WithdrawFromTreasury function is a critical operation. Consider placing it at the beginning of the list to make it more visible.

 NFT_FUNCTIONS: list[type[Function]] = [
+    WithdrawFromTreasury,
     BalanceOfNFT,
     OwnerOfNFT,
     SafeTransferFromNFT,
-    WithdrawFromTreasury,
 ]
prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py (1)

295-295: Update buyer prompt to reflect dynamic treasury threshold.

The buyer prompt should use the actual treasury threshold value in the strategy description instead of hardcoding it.

-- Your goal is to acquire {DeployableAgentNFTGameAbstract.retrieve_treasury_thresold()} out of {len(DeployableAgentNFTGameAbstract.retrieve_total_number_of_keys())} NFT keys to unlock the treasury
+threshold = DeployableAgentNFTGameAbstract.retrieve_treasury_thresold()
+total_keys = DeployableAgentNFTGameAbstract.retrieve_total_number_of_keys()
+- Your goal is to acquire {threshold} out of {total_keys} NFT keys to unlock the treasury ({threshold/total_keys*100:.0f}% of total supply)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9799074 and 0df49b8.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (4)
  • prediction_market_agent/agents/microchain_agent/nft_functions.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/constants_nft_treasury_game.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py (5 hunks)
✅ Files skipped from review due to trivial changes (1)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-build-image
  • GitHub Check: pytest-docker
  • GitHub Check: pytest
  • GitHub Check: mypy
🔇 Additional comments (1)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/constants_nft_treasury_game.py (1)

3-4: Verify the new treasury address deployment and permissions.

The treasury address has been changed. Please ensure:

  1. The new address has been properly deployed and initialized
  2. The correct permissions are set up
  3. The old treasury's funds have been properly migrated
✅ Verification successful

Treasury contract deployment and references verified successfully

The new treasury contract is properly deployed with the required functionality (owner management, NFT handling, withdrawals) and all code references have been consistently updated to use the new address. No traces of the old address remain in the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the new treasury address exists and has the correct code deployed
# Test: Check if the address exists and has contract code. Expect: Non-zero bytecode length

echo "Checking treasury address deployment..."
curl -s -X POST -H "Content-Type: application/json" --data '{
    "jsonrpc":"2.0",
    "method":"eth_getCode",
    "params":["0x624ad0db52e6b18afb4d36b8e79d0c2a74f3fc8a", "latest"],
    "id":1
}' https://rpc.gnosischain.com | jq -r '.result'

Length of output: 2721


Script:

#!/bin/bash
# Search for any remaining references to the old treasury address
echo "Searching for old treasury address..."
rg -i "0xd1A54FD7a200C2ca76B6D06437795d660d37FE28"

echo "Searching for TREASURY_SAFE_ADDRESS..."
rg "TREASURY_SAFE_ADDRESS"

echo "Checking all treasury address references..."
rg "TREASURY_ADDRESS"

Length of output: 1074

Comment on lines +94 to +112
class WithdrawFromTreasury(Function):
@property
def description(self) -> str:
required_balance_nft_tokens = SimpleTreasuryContract().required_nft_balance()
return f"Transfers the entire balance of the treasury to the caller. For the function to succeed, the caller must own {required_balance_nft_tokens} NFT tokens."

@property
def example_args(self) -> list[str]:
return []

def __call__(self) -> str:
keys = MicrochainAgentKeys()
treasury_contract = SimpleTreasuryContract()
logger.info(
f"Withdrawing from the treasury using sender {keys.bet_from_address}"
)
treasury_contract.withdraw(api_keys=keys)
return "Treasury successfully emptied."

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add NFT balance validation before withdrawal.

The withdrawal implementation should validate that the caller owns the required number of NFT tokens before attempting the withdrawal to prevent unnecessary gas costs from failed transactions.

Apply this diff to add validation:

 def __call__(self) -> str:
     keys = MicrochainAgentKeys()
     treasury_contract = SimpleTreasuryContract()
+    required_balance = treasury_contract.required_nft_balance()
+    current_balance = treasury_contract.nft_balance_of(keys.bet_from_address)
+    if current_balance < required_balance:
+        raise ValueError(
+            f"Insufficient NFT balance. Required: {required_balance}, Current: {current_balance}"
+        )
     logger.info(
         f"Withdrawing from the treasury using sender {keys.bet_from_address}"
     )
     treasury_contract.withdraw(api_keys=keys)
     return "Treasury successfully emptied."
📝 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
class WithdrawFromTreasury(Function):
@property
def description(self) -> str:
required_balance_nft_tokens = SimpleTreasuryContract().required_nft_balance()
return f"Transfers the entire balance of the treasury to the caller. For the function to succeed, the caller must own {required_balance_nft_tokens} NFT tokens."
@property
def example_args(self) -> list[str]:
return []
def __call__(self) -> str:
keys = MicrochainAgentKeys()
treasury_contract = SimpleTreasuryContract()
logger.info(
f"Withdrawing from the treasury using sender {keys.bet_from_address}"
)
treasury_contract.withdraw(api_keys=keys)
return "Treasury successfully emptied."
class WithdrawFromTreasury(Function):
@property
def description(self) -> str:
required_balance_nft_tokens = SimpleTreasuryContract().required_nft_balance()
return f"Transfers the entire balance of the treasury to the caller. For the function to succeed, the caller must own {required_balance_nft_tokens} NFT tokens."
@property
def example_args(self) -> list[str]:
return []
def __call__(self) -> str:
keys = MicrochainAgentKeys()
treasury_contract = SimpleTreasuryContract()
required_balance = treasury_contract.required_nft_balance()
current_balance = treasury_contract.nft_balance_of(keys.bet_from_address)
if current_balance < required_balance:
raise ValueError(
f"Insufficient NFT balance. Required: {required_balance}, Current: {current_balance}"
)
logger.info(
f"Withdrawing from the treasury using sender {keys.bet_from_address}"
)
treasury_contract.withdraw(api_keys=keys)
return "Treasury successfully emptied."

Comment on lines +47 to +50
def retrieve_total_number_of_keys(cls) -> int:
# We could iteratively call `owner_of` for a range of token_ids, thus finding out the max supply. However,
# in the current implementation, no new tokens can be created and max_supply = 5, hence hardcoding it here.
return 5
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Replace hardcoded key count with dynamic retrieval.

The hardcoded value of 5 for the total number of keys makes the code brittle and harder to maintain. Consider retrieving this value dynamically from the contract.

 @classmethod
 def retrieve_total_number_of_keys(cls) -> int:
-    # We could iteratively call `owner_of` for a range of token_ids, thus finding out the max supply. However,
-    # in the current implementation, no new tokens can be created and max_supply = 5, hence hardcoding it here.
-    return 5
+    return ContractNFTFactoryOnGnosisChain().total_supply()

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

return [Web3.to_checksum_address(o) for o in safe.retrieve_owners()]
def retrieve_total_number_of_keys(cls) -> int:
# We could iteratively call `owner_of` for a range of token_ids, thus finding out the max supply. However,
# in the current implementation, no new tokens can be created and max_supply = 5, hence hardcoding it here.
Copy link
Contributor

Choose a reason for hiding this comment

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

Just call MAX_SUPPLY from the contract, no need to iterate anything.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Just for context: in an NFT contract, the following normally occurs
-> MAX_SUPPLY = N (N being the collection size, e.g. 100 mintable NFTs)
-> _nextTokenId = 5 (i.e. 5 NFT tokens exist)

Hence calling MAX_SUPPLY is incorrect in general - but in our case, it coincides with the number of NFT tokens that were minted. So since it's a coincidence, I would suggest we keep 5 instead of doing a MAX_SUPPLY call, if you agree.

Copy link
Contributor

Choose a reason for hiding this comment

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

Okay then, but if AgentNFT would be re-deployed at some point for some reason, let's change it to ERC721Enumerable , so we have totalSupply method available.

Copy link
Contributor

@kongzii kongzii left a comment

Choose a reason for hiding this comment

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

Cool, just move the treasury and use properly released PMAT before merging please 🙏

…function-for-emptying-the-treasury-and-fetching-the-money

# Conflicts:
#	prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 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 0df49b8 and e73978d.

⛔ Files ignored due to path filters (2)
  • poetry.lock is excluded by !**/*.lock, !**/*.lock
  • pyproject.toml is excluded by !**/*.toml
📒 Files selected for processing (5)
  • prediction_market_agent/agents/microchain_agent/nft_functions.py (3 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py (2 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/contracts_nft_treasury_game.py (1 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py (5 hunks)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/tools_nft_treasury_game.py (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • prediction_market_agent/agents/microchain_agent/nft_treasury_game/app_nft_treasury_game.py
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: test-build-image
  • GitHub Check: mypy
  • GitHub Check: pytest-docker
  • GitHub Check: pytest
🔇 Additional comments (10)
prediction_market_agent/agents/microchain_agent/nft_treasury_game/tools_nft_treasury_game.py (1)

7-7: LGTM! Consistent renaming of treasury address constant.

The changes correctly implement the renaming from TREASURY_SAFE_ADDRESS to TREASURY_ADDRESS while maintaining the existing functionality.

Also applies to: 17-17

prediction_market_agent/agents/microchain_agent/nft_treasury_game/deploy_nft_treasury_game.py (4)

6-6: LGTM! Simplified treasury threshold retrieval.

The change to use SimpleTreasuryContract().required_nft_balance() directly improves code clarity by removing the Safe abstraction layer.

Also applies to: 63-63


66-69: Hardcoded NFT supply value needs attention.

Based on the past review discussion between kongzii and gabrielfior, while the hardcoded value of 5 matches the current implementation, it would be beneficial to consider using ERC721Enumerable in future deployments to make the supply dynamically retrievable.


328-328: LGTM! Documentation and prompts updated consistently.

The changes to the documentation and buyer prompt accurately reflect the new treasury management approach and key retrieval methods.

Also applies to: 349-349


26-26: Verify complete migration from TREASURY_SAFE_ADDRESS.

Let's ensure all references to the old constant have been updated.

✅ Verification successful

Migration to TREASURY_ADDRESS is complete and consistent

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining references to TREASURY_SAFE_ADDRESS
rg "TREASURY_SAFE_ADDRESS"

Length of output: 26


Script:

#!/bin/bash
# Search for TREASURY_ADDRESS usage
rg "TREASURY_ADDRESS" -A 2

Length of output: 2838

prediction_market_agent/agents/microchain_agent/nft_treasury_game/contracts_nft_treasury_game.py (1)

28-28: LGTM! Method name updated to follow Python naming conventions.

The change from ownerOf to owner_of aligns with Python's snake_case naming convention while maintaining the same functionality.

prediction_market_agent/agents/microchain_agent/nft_functions.py (4)

5-5: LGTM! Import added for treasury contract integration.

The SimpleTreasuryContract import is correctly placed and necessary for the new withdrawal functionality.


94-111: Add NFT balance validation before withdrawal.

The withdrawal implementation should validate that the caller owns the required number of NFT tokens before attempting the withdrawal to prevent unnecessary gas costs from failed transactions.


118-118: LGTM! Function correctly added to NFT_FUNCTIONS list.

The WithdrawFromTreasury class is properly registered in the NFT_FUNCTIONS list, maintaining alphabetical order.


55-55: LGTM! Method name and type annotation updated.

The change from ownerOf to owner_of maintains consistency with the contract class, and the added type annotation improves code clarity.

Comment on lines +104 to +111
def __call__(self) -> str:
keys = MicrochainAgentKeys()
treasury_contract = SimpleTreasuryContract()
logger.info(
f"Withdrawing from the treasury using sender {keys.bet_from_address}"
)
treasury_contract.withdraw(api_keys=keys)
return "Treasury successfully emptied."
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and success validation.

The withdrawal implementation needs:

  1. Error handling for the withdraw call
  2. Validation of successful withdrawal before returning success message

Apply this diff to add error handling:

 def __call__(self) -> str:
     keys = MicrochainAgentKeys()
     treasury_contract = SimpleTreasuryContract()
+    try:
         logger.info(
             f"Withdrawing from the treasury using sender {keys.bet_from_address}"
         )
         treasury_contract.withdraw(api_keys=keys)
+        if not self._verify_withdrawal_success(treasury_contract):
+            raise ValueError("Withdrawal appeared to fail - treasury balance unchanged")
         return "Treasury successfully emptied."
+    except Exception as e:
+        logger.error(f"Treasury withdrawal failed: {str(e)}")
+        raise
+
+def _verify_withdrawal_success(self, treasury_contract: SimpleTreasuryContract) -> bool:
+    """Verify the withdrawal succeeded by checking the treasury balance."""
+    return treasury_contract.get_balance() == 0

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

@gabrielfior gabrielfior merged commit 49f24d7 into main Jan 17, 2025
10 checks passed
@gabrielfior gabrielfior deleted the 631-add-function-for-emptying-the-treasury-and-fetching-the-money branch January 17, 2025 15:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add function for emptying the treasury and fetching the money
2 participants