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

feat(morpho-markets): supply & withdraw collat + borrow and repay morpho actions #116

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
12 changes: 10 additions & 2 deletions cdp-agentkit-core/python/cdp_agentkit_core/actions/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@
from cdp_agentkit_core.actions.get_balance import GetBalanceAction
from cdp_agentkit_core.actions.get_wallet_details import GetWalletDetailsAction
from cdp_agentkit_core.actions.mint_nft import MintNftAction
from cdp_agentkit_core.actions.morpho.borrow import MorphoBorrowAction
from cdp_agentkit_core.actions.morpho.deposit import MorphoDepositAction
from cdp_agentkit_core.actions.morpho.repay import MorphoRepayAction
from cdp_agentkit_core.actions.morpho.supply_collateral import MorphoSupplyCollateralAction
from cdp_agentkit_core.actions.morpho.withdraw import MorphoWithdrawAction
from cdp_agentkit_core.actions.morpho.withdraw_collateral import MorphoWithdrawCollateralAction
from cdp_agentkit_core.actions.register_basename import RegisterBasenameAction
from cdp_agentkit_core.actions.request_faucet_funds import RequestFaucetFundsAction
from cdp_agentkit_core.actions.trade import TradeAction
Expand Down Expand Up @@ -36,6 +40,12 @@ def get_all_cdp_actions() -> list[type[CdpAction]]:
"GetBalanceAction",
"GetWalletDetailsAction",
"MintNftAction",
"MorphoDepositAction",
"MorphoWithdrawAction",
"MorphoWithdrawCollateralAction",
"MorphoSupplyCollateralAction",
"MorphoBorrowAction",
"MorphoRepayAction",
"RegisterBasenameAction",
"RequestFaucetFundsAction",
"TradeAction",
Expand All @@ -44,6 +54,4 @@ def get_all_cdp_actions() -> list[type[CdpAction]]:
"WowCreateTokenAction",
"WowSellTokenAction",
"WrapEthAction",
"MorphoDepositAction",
"MorphoWithdrawAction",
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from cdp_agentkit_core.actions.morpho.borrow import MorphoBorrowAction
from cdp_agentkit_core.actions.morpho.deposit import MorphoDepositAction
from cdp_agentkit_core.actions.morpho.repay import MorphoRepayAction
from cdp_agentkit_core.actions.morpho.supply_collateral import MorphoSupplyCollateralAction
from cdp_agentkit_core.actions.morpho.withdraw import MorphoWithdrawAction
from cdp_agentkit_core.actions.morpho.withdraw_collateral import MorphoWithdrawCollateralAction

__all__ = [
"MorphoBorrowAction",
"MorphoDepositAction",
"MorphoRepayAction",
"MorphoSupplyCollateralAction",
"MorphoWithdrawAction",
"MorphoWithdrawCollateralAction",
]
131 changes: 131 additions & 0 deletions cdp-agentkit-core/python/cdp_agentkit_core/actions/morpho/borrow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
from collections.abc import Callable
from decimal import Decimal
from typing import TypedDict

from cdp import Asset, Wallet
from pydantic import BaseModel, Field

from cdp_agentkit_core.actions import CdpAction
from cdp_agentkit_core.actions.morpho.constants import BLUE_ABI, MORPHO_BASE_ADDRESS
from cdp_agentkit_core.actions.morpho.utils import approve


# Define the structure for market parameters
class MarketParams(TypedDict):
"""Type definition for Morpho market parameters."""

loanToken: str # address
collateralToken: str # address
oracle: str # address
irm: str # address
lltv: str # uint256


class MorphoBorrowInput(BaseModel):
"""Input schema for Morpho Markets borrow action."""

market_params: MarketParams = Field(
...,
description="Market parameters including loan token, collateral token, oracle, irm, and lltv addresses",
)
assets: str
shares: str
on_behalf: str
receiver: str


BORROW_PROMPT = """
This tool allows borrowing assets from a Morpho market. It takes:

- market_params: The market parameters including:
- loanToken: The address of the loan token
- collateralToken: The address of the collateral token
- oracle: The address of the oracle
- irm: The address of the interest rate model
- lltv: The liquidation LTV (loan-to-value ratio)
- assets: The amount of assets to borrow in whole units
Examples for WETH:
- 1 WETH
- 0.1 WETH
- 0.01 WETH
- shares: The amount of shares to borrow (use "0" to borrow using assets amount)
- on_behalf: The address to borrow on behalf of
- receiver: The address to receive the borrowed assets
"""


def borrow_from_morpho(
wallet: Wallet,
market_params: dict,
assets: str,
shares: str,
on_behalf: str,
receiver: str,
) -> str:
"""Borrow assets from a Morpho market.

Args:
wallet (Wallet): The wallet to execute the borrow from
market_params (dict): The market parameters
assets (str): The amount of assets to borrow in whole units (e.g., 0.01 WETH)
shares (str): The amount of shares to borrow
on_behalf (str): The address to borrow on behalf of
receiver (str): The address to receive the borrowed assets

Returns:
str: A success message with transaction hash or error message
"""

if (assets == "0" and shares == "0") or (assets != "0" and shares != "0"):
return "Error: Exactly one of 'assets' or 'shares' must be zero, the other number has to be positive"

try:
# TODO We are going to need to verify that a collateral position has been provided.

token_asset = Asset.fetch(wallet.network_id, market_params["loanToken"])
# Validate that exactly one of assets or shares is zero

atomic_assets = (
str(int(token_asset.to_atomic_amount(Decimal(assets)))) if assets != "0" else "0"
)
atomic_shares = (
str(int(token_asset.to_atomic_amount(Decimal(shares)))) if shares != "0" else "0"
)

# Convert market_params dictionary to the required tuple format
market_params_tuple = [
market_params["loanToken"],
market_params["collateralToken"],
market_params["oracle"],
market_params["irm"],
str(market_params["lltv"]), # Convert lltv to int for uint256
]

borrow_args = {
"marketParams": market_params_tuple,
"assets": atomic_assets,
"shares": atomic_shares,
"onBehalf": on_behalf,
"receiver": receiver,
}

invocation = wallet.invoke_contract(
contract_address=MORPHO_BASE_ADDRESS,
method="borrow",
abi=BLUE_ABI,
args=borrow_args,
).wait()

return f"Borrowed {assets} from Morpho market with transaction hash: {invocation.transaction_hash} and transaction link: {invocation.transaction_link}"

except Exception as e:
return f"Error borrowing from Morpho Blue: {e!s}"


class MorphoBorrowAction(CdpAction):
"""Morpho Blue borrow action."""

name: str = "morpho_borrow"
description: str = BORROW_PROMPT
args_schema: type[BaseModel] = MorphoBorrowInput
func: Callable[..., str] = borrow_from_morpho
104 changes: 104 additions & 0 deletions cdp-agentkit-core/python/cdp_agentkit_core/actions/morpho/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,3 +38,107 @@
"type": "function",
},
]


BLUE_ABI = [
{
"inputs": [
{
"name": "marketParams",
"type": "tuple",
"internalType": "struct MarketParams",
"components": [
{"name": "loanToken", "type": "address", "internalType": "address"},
{"name": "collateralToken", "type": "address", "internalType": "address"},
{"name": "oracle", "type": "address", "internalType": "address"},
{"name": "irm", "type": "address", "internalType": "address"},
{"name": "lltv", "type": "uint256", "internalType": "uint256"},
],
},
{"name": "assets", "type": "uint256", "internalType": "uint256"},
{"name": "shares", "type": "uint256", "internalType": "uint256"},
{"name": "onBehalf", "type": "address", "internalType": "address"},
{"name": "receiver", "type": "address", "internalType": "address"},
],
"name": "borrow",
"outputs": [
{"name": "", "type": "uint256", "internalType": "uint256"},
{"name": "", "type": "uint256", "internalType": "uint256"},
],
"stateMutability": "nonpayable",
"type": "function",
},
{
"inputs": [
{
"name": "marketParams",
"type": "tuple",
"internalType": "struct MarketParams",
"components": [
{"name": "loanToken", "type": "address", "internalType": "address"},
{"name": "collateralToken", "type": "address", "internalType": "address"},
{"name": "oracle", "type": "address", "internalType": "address"},
{"name": "irm", "type": "address", "internalType": "address"},
{"name": "lltv", "type": "uint256", "internalType": "uint256"},
],
},
{"name": "assets", "type": "uint256", "internalType": "uint256"},
{"name": "shares", "type": "uint256", "internalType": "uint256"},
{"name": "onBehalf", "type": "address", "internalType": "address"},
{"name": "data", "type": "bytes", "internalType": "bytes"},
],
"name": "repay",
"outputs": [
{"name": "", "type": "uint256", "internalType": "uint256"},
{"name": "", "type": "uint256", "internalType": "uint256"},
],
"stateMutability": "nonpayable",
"type": "function",
},
{
"inputs": [
{
"name": "marketParams",
"type": "tuple",
"internalType": "struct MarketParams",
"components": [
{"name": "loanToken", "type": "address", "internalType": "address"},
{"name": "collateralToken", "type": "address", "internalType": "address"},
{"name": "oracle", "type": "address", "internalType": "address"},
{"name": "irm", "type": "address", "internalType": "address"},
{"name": "lltv", "type": "uint256", "internalType": "uint256"},
],
},
{"name": "assets", "type": "uint256", "internalType": "uint256"},
{"name": "onBehalf", "type": "address", "internalType": "address"},
{"name": "data", "type": "bytes", "internalType": "bytes"},
],
"name": "supplyCollateral",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function",
},
{
"inputs": [
{
"name": "marketParams",
"type": "tuple",
"internalType": "struct MarketParams",
"components": [
{"name": "loanToken", "type": "address", "internalType": "address"},
{"name": "collateralToken", "type": "address", "internalType": "address"},
{"name": "oracle", "type": "address", "internalType": "address"},
{"name": "irm", "type": "address", "internalType": "address"},
{"name": "lltv", "type": "uint256", "internalType": "uint256"},
],
},
{"name": "assets", "type": "uint256", "internalType": "uint256"},
{"name": "onBehalf", "type": "address", "internalType": "address"},
{"name": "receiver", "type": "address", "internalType": "address"},
],
"name": "withdrawCollateral",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function",
},
]
Loading