-
Notifications
You must be signed in to change notification settings - Fork 17
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
initial compound workflow #80
Open
harshraj172
wants to merge
2
commits into
dev
Choose a base branch
from
harsh/compound
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
from .compound_supply import CompoundSupplyWorkflow | ||
from .compound_repay import CompoundRepayWorkflow | ||
from .compound_borrow import CompoundBorrowWorkflow | ||
from .compound_withdraw import CompoundWithdrawWorkflow |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import re | ||
from logging import basicConfig, INFO | ||
import time | ||
import json | ||
import uuid | ||
import os | ||
import requests | ||
from typing import Any, Dict, List, Optional, Union, Literal, TypedDict, Callable | ||
from dataclasses import dataclass, asdict | ||
|
||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError | ||
|
||
import env | ||
from utils import TENDERLY_FORK_URL, w3 | ||
from ..base import BaseUIWorkflow, Result, BaseSingleStepWorkflow, WorkflowStepClientPayload, StepProcessingResult, RunnableStep, tenderly_simulate_tx, setup_mock_db_objects | ||
from database.models import ( | ||
db_session, MultiStepWorkflow, WorkflowStep, WorkflowStepStatus, WorkflowStepUserActionType, ChatMessage, ChatSession, SystemConfig | ||
) | ||
|
||
TWO_MINUTES = 120000 | ||
TEN_SECONDS = 10000 | ||
|
||
class CompoundBorrowWorkflow(BaseSingleStepWorkflow): | ||
|
||
def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_type: str, workflow_params: Dict) -> None: | ||
self.token = workflow_params['token'] | ||
self.amount = workflow_params['amount'] | ||
self.user_description = f"Borrow {self.amount} {self.token} on Compound Finance" | ||
|
||
step = RunnableStep("confirm_borrow", WorkflowStepUserActionType.tx, f"{self.token} confirm Borrow on Compound Finance", self.confirm_borrow) | ||
|
||
super().__init__(wallet_chain_id, wallet_address, chat_message_id, workflow_type, workflow_params, step) | ||
|
||
def _forward_rpc_node_reqs(self, route): | ||
"""Override to intercept requests to ENS API and modify response to simulate block production""" | ||
post_body = route.request.post_data | ||
|
||
# Intercepting below request to modify timestamp to be 5 minutes in the future to simulate block production and allow ENS web app to not be stuck in waiting loop | ||
if "eth_getBlockByNumber" in post_body: | ||
curr_time_hex = hex(int(time.time()) + 300) | ||
data = requests.post(TENDERLY_FORK_URL, data=post_body) | ||
json_dict = data.json() | ||
json_dict["result"]["timestamp"] = curr_time_hex | ||
data = json_dict | ||
res_text = json.dumps(data) | ||
route.fulfill(body=res_text, headers={"access-control-allow-origin": "*", "access-control-allow-methods": "*", "access-control-allow-headers": "*"}) | ||
else: | ||
super()._forward_rpc_node_reqs(route) | ||
|
||
def _goto_page_and_open_walletconnect(self, page): | ||
"""Go to page and open WalletConnect modal""" | ||
|
||
page.goto(f"https://v2-app.compound.finance/") | ||
|
||
# Search for WalletConnect and open QRCode modal | ||
page.locator("a").filter(has_text="Wallet Connect").click() | ||
|
||
def confirm_borrow(self, page, context) -> StepProcessingResult: | ||
"""Confirm borrow""" | ||
# Find the token | ||
try: | ||
token_locators = page.get_by_text(re.compile(r".*\s{token}.*".format(token=self.token))) | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult( | ||
status="error", | ||
error_msg=f"{self.token} not available for Borrow", | ||
) | ||
|
||
# Find borrow | ||
for i in range(4): | ||
try: token_locators.nth(i).click() | ||
except: continue | ||
if page.locator("label").filter(has_text=re.compile(r"^Borrow$")).is_visible(): | ||
page.locator("label").filter(has_text=re.compile(r"^Borrow$")).click() | ||
break | ||
page.locator(".close-x").click() | ||
|
||
# Fill the amount | ||
try: | ||
page.get_by_placeholder("0").fill(str(self.amount)) | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult( | ||
status="error", | ||
error_msg=f"{self.token} not available for Borrow", | ||
) | ||
|
||
# confirm borrow | ||
try: | ||
page.get_by_role("button", name="Borrow").click() | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult( | ||
status="error", | ||
error_msg=f"No Balance to Borrow {self.amount} {self.token}", | ||
) | ||
|
||
return StepProcessingResult( | ||
status="success", | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,114 @@ | ||
import re | ||
from logging import basicConfig, INFO | ||
import time | ||
import json | ||
import uuid | ||
import os | ||
import requests | ||
from typing import Any, Dict, List, Optional, Union, Literal, TypedDict, Callable | ||
from dataclasses import dataclass, asdict | ||
|
||
from playwright.sync_api import TimeoutError as PlaywrightTimeoutError | ||
|
||
import env | ||
from utils import TENDERLY_FORK_URL, w3 | ||
from ..base import BaseUIWorkflow, MultiStepResult, BaseMultiStepWorkflow, WorkflowStepClientPayload, StepProcessingResult, RunnableStep, tenderly_simulate_tx, setup_mock_db_objects | ||
from database.models import ( | ||
db_session, MultiStepWorkflow, WorkflowStep, WorkflowStepStatus, WorkflowStepUserActionType, ChatMessage, ChatSession, SystemConfig | ||
) | ||
|
||
TWO_MINUTES = 120000 | ||
TEN_SECONDS = 10000 | ||
|
||
class CompoundRepayWorkflow(BaseMultiStepWorkflow): | ||
|
||
def __init__(self, wallet_chain_id: int, wallet_address: str, chat_message_id: str, workflow_type: str, workflow_params: Dict, workflow: Optional[MultiStepWorkflow] = None, curr_step_client_payload: Optional[WorkflowStepClientPayload] = None) -> None: | ||
self.token = workflow_params['token'] | ||
self.amount = workflow_params['amount'] | ||
|
||
step1 = RunnableStep("enable_repay", WorkflowStepUserActionType.tx, f"{self.token} enable Repay on Compound Finance", self.step_1_enable_repay) | ||
step2 = RunnableStep("confirm_repay", WorkflowStepUserActionType.tx, f"{self.token} confirm Repay on Compound Finance", self.step_2_confirm_repay) | ||
|
||
steps = [step1, step2] | ||
|
||
super().__init__(wallet_chain_id, wallet_address, chat_message_id, workflow_type, workflow, workflow_params, curr_step_client_payload, steps) | ||
|
||
def _forward_rpc_node_reqs(self, route): | ||
"""Override to intercept requests to ENS API and modify response to simulate block production""" | ||
post_body = route.request.post_data | ||
|
||
# Intercepting below request to modify timestamp to be 5 minutes in the future to simulate block production and allow ENS web app to not be stuck in waiting loop | ||
if "eth_getBlockByNumber" in post_body: | ||
curr_time_hex = hex(int(time.time()) + 300) | ||
data = requests.post(TENDERLY_FORK_URL, data=post_body) | ||
json_dict = data.json() | ||
json_dict["result"]["timestamp"] = curr_time_hex | ||
data = json_dict | ||
res_text = json.dumps(data) | ||
route.fulfill(body=res_text, headers={"access-control-allow-origin": "*", "access-control-allow-methods": "*", "access-control-allow-headers": "*"}) | ||
else: | ||
super()._forward_rpc_node_reqs(route) | ||
|
||
def _goto_page_and_open_walletconnect(self, page): | ||
"""Go to page and open WalletConnect modal""" | ||
|
||
page.goto(f"https://v2-app.compound.finance/") | ||
|
||
# Search for WalletConnect and open QRCode modal | ||
page.locator("a").filter(has_text="Wallet Connect").click() | ||
|
||
def step_1_enable_repay(self, page, context) -> StepProcessingResult: | ||
"""Step 1: Enable repay""" | ||
# Find the token | ||
try: | ||
token_locators = page.get_by_text(re.compile(r".*{token}.*".format(token=self.token), re.IGNORECASE)) | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult(status='error', error_msg=f"{self.token} not available for Repay") | ||
|
||
# Find Repay and enable | ||
for i in range(4): | ||
try: token_locators.nth(i).click() | ||
except: continue | ||
if page.get_by_text("Repay").is_visible(): | ||
page.get_by_text("Repay").click() | ||
if page.get_by_role("button", name="Enable").is_visible(): page.get_by_role("button", name="Enable").click() | ||
# Preserve browser local storage item to allow protocol to recreate the correct state | ||
self._preserve_browser_local_storage_item(context, 'preferences') | ||
return StepProcessingResult(status='success') | ||
page.locator(".close-x").click() | ||
|
||
return StepProcessingResult(status='error', error_msg=f"{self.token} not available for Repay") | ||
|
||
def step_2_confirm_repay(self, page, context) -> StepProcessingResult: | ||
"""Step 2: Confirm repay""" | ||
# Find the token | ||
try: | ||
token_locators = page.get_by_text(re.compile(r".*{token}.*".format(token=self.token), re.IGNORECASE)) | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult(status='error', error_msg=f"{self.token} not available for Repay") | ||
|
||
# Find repay | ||
for i in range(4): | ||
try: token_locators.nth(i).click() | ||
except: continue | ||
if page.get_by_text("Repay").is_visible(): | ||
page.get_by_text("Repay").click() | ||
break | ||
page.locator(".close-x").click() | ||
|
||
# Fill the amount | ||
try: | ||
page.get_by_placeholder("0").fill(str(self.amount)) | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult( | ||
status="error", | ||
error_msg=f"{self.token} not available for Repay", | ||
) | ||
|
||
# confirm repay | ||
try: | ||
page.get_by_role("button", name="Repay").click() | ||
except PlaywrightTimeoutError: | ||
return StepProcessingResult(status='error', error_msg=f"No Balance to Repay {self.amount} {self.token}") | ||
|
||
return StepProcessingResult(status='success') |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Is this special handling required for Compound?
I added it for ENS as its logic has a wait time between steps and relied on block production as a trigger to proceed to next step
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.
Not specific to Compound, thought it is common to protocols.
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.
It's special handling for ENS, not sure about Compound, double check and if not needed, you can remove the entire overridden function
_forward_rpc_node_reqs
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 rechecked this, Compound is using this function