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

initial compound workflow #80

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions ui_workflows/compound/__init__.py
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
84 changes: 84 additions & 0 deletions ui_workflows/compound/compound_borrow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
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 CompoundBorrowWorkflow(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("confirm_borrow", WorkflowStepUserActionType.tx, f"{self.token} confirm borrow", self.step_1_confirm_borrow)

steps = [step1]
Copy link
Collaborator

Choose a reason for hiding this comment

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

For single-step workflow may not be ideal to use MultiStepWorkflow abstraction, since we don't have a single step abstraction yet, you could implement something similar to what we have for the Aave workflow

Copy link
Collaborator Author

@harshraj172 harshraj172 May 10, 2023

Choose a reason for hiding this comment

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


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_confirm_borrow(self, page, context) -> StepProcessingResult:
"""Step 1: 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
page.get_by_placeholder("0").fill(str(self.amount))
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')
107 changes: 107 additions & 0 deletions ui_workflows/compound/compound_repay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
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", self.step_1_enable_repay)
step2 = RunnableStep("confirm_repay", WorkflowStepUserActionType.tx, f"{self.token} confirm repay", 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:
Copy link
Collaborator

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

Copy link
Collaborator Author

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.

Copy link
Collaborator

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

Copy link
Collaborator Author

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

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
page.get_by_placeholder("0").fill(str(self.amount))
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')
107 changes: 107 additions & 0 deletions ui_workflows/compound/compound_supply.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
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 CompoundSupplyWorkflow(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_supply", WorkflowStepUserActionType.tx, f"{self.token} enable supply", self.step_1_enable_supply)
Copy link
Collaborator

Choose a reason for hiding this comment

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

For supplying tokens, if the token is non-ETH / ERC20 (like USDC, DAI, etc.), generally the user has to first give approval to the protocol to use their tokens so how is that approval step being handled?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

So step1 is for enabling the token's use on the platform. After step1 the user will have to approve the transaction from his/her wallet then it proceeds to step2.

Copy link
Collaborator

Choose a reason for hiding this comment

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

Ok , so how is the supply of the native ETH token being handled as that shouldn't require any approval and would only require a single step?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Yea, so if the token is already enabled (if it native ETH or user enabled it before) then the step1 will return "success". See here: https://github.com/yieldprotocol/chatweb3-backend/blob/0b4cb5d3d8acced96062a1fd3244e5e26daba7fc/ui_workflows/compound/compound_repay.py#L78

step2 = RunnableStep("confirm_supply", WorkflowStepUserActionType.tx, f"{self.token} confirm supply", self.step_2_confirm_supply)

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_supply(self, page, context) -> StepProcessingResult:
"""Step 1: Enable supply"""
# 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 Supply")

# Find supply and enable
for i in range(4):
try: token_locators.nth(i).click()
except: continue
if page.locator("label").filter(has_text=re.compile(r"^Supply$")).is_visible():
page.locator("label").filter(has_text=re.compile(r"^Supply$")).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 Supply")

def step_2_confirm_supply(self, page, context) -> StepProcessingResult:
"""Step 2: Confirm supply"""
# 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 Supply")

# Find supply
for i in range(4):
try: token_locators.nth(i).click()
except: continue
if page.locator("label").filter(has_text=re.compile(r"^Supply$")).is_visible():
page.locator("label").filter(has_text=re.compile(r"^Supply$")).click()
break
page.locator(".close-x").click()

# Fill the amount
page.get_by_placeholder("0").fill(str(self.amount))
try:
page.get_by_role("button", name="Supply").click()
except PlaywrightTimeoutError:
return StepProcessingResult(status='error', error_msg=f"No Balance to Supply {self.amount} {self.token}")

return StepProcessingResult(status='success')
84 changes: 84 additions & 0 deletions ui_workflows/compound/compound_withdraw.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
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 CompoundWithdrawWorkflow(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("confirm_withdraw", WorkflowStepUserActionType.tx, f"{self.token} confirm withdraw", self.step_1_confirm_withdraw)

steps = [step1]

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_confirm_withdraw(self, page, context) -> StepProcessingResult:
"""Step 1: Confirm withdraw"""
# 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 Withdraw")

# Find withdraw
for i in range(4):
try: token_locators.nth(i).click()
except: continue
if page.get_by_text("Withdraw").is_visible():
page.get_by_text("Withdraw").click()
break
page.locator(".close-x").click()

# Fill the amount
page.get_by_placeholder("0").fill(str(self.amount))
try:
page.get_by_role("button", name="Withdraw").click()
except PlaywrightTimeoutError:
return StepProcessingResult(status='error', error_msg=f"No Balance to Withdraw {self.amount} {self.token}")

return StepProcessingResult(status='success')
Loading