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

add withdraw all contract #384

Merged
merged 3 commits into from
Dec 17, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions web_app/api/user.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

"""
This module handles user-related API endpoints.
"""
Expand All @@ -21,6 +22,7 @@
TelegramUserDBConnector,
UserDBConnector,
)
from web_app.contract_tools.blockchain_call import CLIENT

logger = logging.getLogger(__name__)
router = APIRouter() # Initialize the router
Expand Down Expand Up @@ -298,3 +300,36 @@ async def allow_notification(
raise HTTPException(status_code=404, detail=str(e))
except Exception as e:
raise HTTPException(status_code=500, detail="Internal server error")


@router.post(
"/api/withdraw-all",
tags=["User Operations"],
summary="Withdraw all tokens from user's contract",
response_description="Status of withdrawal operations",
)
async def withdraw_all(wallet_id: str) -> dict:
"""
Withdraws all supported tokens from the user's contract.

:param wallet_id: The wallet ID of the user.
:return: detail: "Successfully initiated withdrawals for all tokens"
"""
# Get user's contract address
contract_address = await get_user_contract(wallet_id)
Copy link
Owner

Choose a reason for hiding this comment

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

here you can get method get_user_contract to get contract_address, instead of using
user_db.get_contract_address_by_wallet_id

if not contract_address:
raise HTTPException(status_code=404, detail="Contract not found")

try:
# Perform withdrawals
results = await CLIENT.withdraw_all(contract_address)
return {
"detail": "Successfully initiated withdrawals for all tokens",
"results": results
}
except Exception as e:
djeck1432 marked this conversation as resolved.
Show resolved Hide resolved
logger.error(f"Contract withdrawal failed: {str(e)}")
raise HTTPException(
status_code=500,
detail=f"Failed to withdraw tokens: {str(e)}"
)
32 changes: 32 additions & 0 deletions web_app/contract_tools/blockchain_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,5 +352,37 @@ async def add_extra_deposit(self, contract_address: str, token_address: str, amo
calldata=[self._convert_address(token_address), amount],
)

async def withdraw_all(self, contract_address: str) -> dict[str, str]:
"""
Withdraws all supported tokens from the contract by calling withdraw with amount=0.

:param contract_address: The contract address to withdraw from
:return: A dictionary summarizing the results for each token.
"""
contract_addr_int = self._convert_address(contract_address)
results = {}

for token in TokenParams.tokens():
try:
token_addr_int = self._convert_address(token.address)
token_symbol = token.name
logger.info(f"Withdrawing {token_symbol} from contract {contract_address}")
await self._func_call(
addr=contract_addr_int,
selector="withdraw",
calldata=[token_addr_int, 0]
)
results[token_symbol] = "Success"

except ValueError as e:
djeck1432 marked this conversation as resolved.
Show resolved Hide resolved
logger.error(f"Invalid address format for {token_symbol}: {str(e)}")
results[token_symbol] = f"Failed: Invalid address format"

except Exception as e:
djeck1432 marked this conversation as resolved.
Show resolved Hide resolved
djeck1432 marked this conversation as resolved.
Show resolved Hide resolved
logger.error(f"Error withdrawing {token_symbol}: {e}")
results[token_symbol] = f"Failed: {e}"

return results


CLIENT = StarknetClient()
Loading