> For the complete documentation index, see [llms.txt](https://docs.greenowl.money/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.greenowl.money/smart-contracts/contracts/owllendingadapter.md).

# OwlLendingAdapter

**OwlLendingAdapter** is a middleware contract that enables Owl Smart Wallets to access DeFi lending markets autonomously. It orchestrates multi-step borrowing workflows by chaining operations across Morpho (a lending protocol) and the USDL vault, allowing AI agents to supply collateral, borrow USDC, and mint USDL in atomic transactions.

## Overview

This adapter simplifies complex DeFi operations into single-transaction workflows, essential for autonomous AI agent operation:

1. **Supply & Borrow Flow**: Deposit collateral (WBTC/WETH) → Borrow USDC from Morpho → Deposit USDC to USDL Vault → Receive USDL
2. **Repay & Withdraw Flow**: Burn USDL → Withdraw USDC from USDL Vault → Repay Morpho debt → Withdraw collateral

By bundling these steps, the adapter reduces transaction overhead and enables atomic DeFi operations that can be executed by AI agents through MCP tools without requiring multi-step coordination.

**Key Features:**

* Atomic supply-and-borrow operations
* Collateral management through Morpho protocol
* USDL minting/burning via vault integration
* Authorization-based security model
* Gas-optimized single-transaction flows

***

## Architecture

The adapter integrates with four core components:

| Component      | Role                                                                    |
| -------------- | ----------------------------------------------------------------------- |
| **Morpho**     | Decentralized lending protocol for collateral supply and USDC borrowing |
| **USDC**       | Intermediate borrowed asset                                             |
| **USDL Vault** | ERC-4626 vault that converts USDC deposits into USDL                    |
| **USDL Token** | Final stablecoin minted to the user                                     |

**Authorization Model**: Users must grant authorization to the adapter via `morpho.setAuthorization(adapter, true)` before the adapter can manage their positions. This follows Morpho's operator pattern for secure delegation.

***

## State Variables

### usdc

```solidity
IERC20 public immutable usdc
```

The USDC token contract address. USDC is borrowed from Morpho and deposited into the USDL vault.

### usdl

```solidity
IERC20 public immutable usdl
```

The USDL stablecoin token contract address. USDL is minted when USDC is deposited to the vault and burned during repayment.

### usdlVault

```solidity
IERC4626 public immutable usdlVault
```

The USDL vault contract implementing ERC-4626. Handles USDC deposits and USDL minting/redemption.

### morpho

```solidity
IMorpho public immutable morpho
```

The Morpho lending protocol contract. Manages collateral supply, borrowing, and debt repayment.

***

## Constructor

```solidity
constructor(
    address _usdc,
    address _usdl,
    address _usdlVault,
    address _morpho
) Ownable(msg.sender)
```

Initializes the adapter with protocol addresses. All addresses are immutable after deployment.

**Parameters:**

| Name         | Type      | Description                     |
| ------------ | --------- | ------------------------------- |
| `_usdc`      | `address` | USDC token contract address     |
| `_usdl`      | `address` | USDL token contract address     |
| `_usdlVault` | `address` | USDL ERC-4626 vault address     |
| `_morpho`    | `address` | Morpho lending protocol address |

***

## Core Functions

### supplyAndBorrowUSDL

```solidity
function supplyAndBorrowUSDL(
    address collateralToken,
    uint256 collateralAmount,
    uint256 borrowAmountUSDC,
    MarketParams calldata marketParams
) external
```

Executes an atomic supply-and-borrow operation: supplies collateral to Morpho, borrows USDC, deposits USDC to the USDL vault, and mints USDL to the caller.

**Prerequisites:**

* Caller must approve the adapter to spend `collateralAmount` of `collateralToken`
* Caller must authorize the adapter in Morpho: `morpho.setAuthorization(adapter, true)`
* Sufficient collateral ratio to support the borrow amount per Morpho market rules

**Parameters:**

| Name               | Type           | Description                                                 |
| ------------------ | -------------- | ----------------------------------------------------------- |
| `collateralToken`  | `address`      | Address of the collateral token (e.g., WBTC, WETH)          |
| `collateralAmount` | `uint256`      | Amount of collateral to supply to Morpho                    |
| `borrowAmountUSDC` | `uint256`      | Amount of USDC to borrow from Morpho (converted to USDL)    |
| `marketParams`     | `MarketParams` | Morpho market parameters struct defining the lending market |

**Flow:**

1. Transfer `collateralAmount` from caller to adapter
2. Supply collateral to Morpho on behalf of caller
3. Borrow `borrowAmountUSDC` USDC from Morpho
4. Deposit USDC to USDL vault
5. Transfer minted USDL to caller

**Usage Context:** AI agents use this function via MCP tools to establish leveraged positions. The atomic nature ensures the agent doesn't hold intermediate USDC state.

***

### repayDebt

```solidity
function repayDebt(
    uint256 usdlAmountToRepay,
    MarketParams calldata marketParams
) external
```

Repays USDL debt to Morpho by burning USDL, withdrawing USDC from the vault, and repaying the Morpho loan.

**Prerequisites:**

* Caller must approve the adapter to spend `usdlAmountToRepay` USDL

**Parameters:**

| Name                | Type           | Description                                            |
| ------------------- | -------------- | ------------------------------------------------------ |
| `usdlAmountToRepay` | `uint256`      | Amount of USDL to repay (burned and converted to USDC) |
| `marketParams`      | `MarketParams` | Morpho market parameters struct for the loan           |

**Flow:**

1. Transfer USDL from caller to adapter
2. Withdraw USDC from USDL vault (burning USDL)
3. Repay USDC debt to Morpho on behalf of caller

**Post-Conditions:** After repayment, the caller can withdraw collateral directly from Morpho using `morpho.withdrawCollateral()`.

***

### repayAndWithdraw

```solidity
function repayAndWithdraw(
    address, /* collateralToken - inferred from marketParams */
    uint256 usdlAmountToRepay,
    uint256 collateralAmountToWithdraw,
    MarketParams calldata marketParams
) external
```

Atomic repayment and collateral withdrawal: repays USDL debt and withdraws collateral in a single transaction.

**Prerequisites:**

* Caller must approve the adapter to spend `usdlAmountToRepay` USDL
* Caller must authorize the adapter in Morpho: `morpho.setAuthorization(adapter, true)`
* Remaining collateral after withdrawal must satisfy Morpho's collateralization requirements

**Parameters:**

| Name                         | Type           | Description                                                             |
| ---------------------------- | -------------- | ----------------------------------------------------------------------- |
| *unused*                     | `address`      | Collateral token address (inferred from `marketParams.collateralToken`) |
| `usdlAmountToRepay`          | `uint256`      | Amount of USDL to repay                                                 |
| `collateralAmountToWithdraw` | `uint256`      | Amount of collateral to withdraw and return to caller                   |
| `marketParams`               | `MarketParams` | Morpho market parameters struct                                         |

**Flow:**

1. Transfer USDL from caller to adapter
2. Withdraw USDC from USDL vault
3. Repay USDC debt to Morpho
4. Withdraw collateral from Morpho
5. Transfer collateral to caller

**Usage Context:** AI agents use this function to atomically exit positions, ensuring collateral is returned in the same transaction as debt repayment. Critical for liquidation avoidance strategies.

***

## Security Considerations

**Authorization Model:**

* Users must explicitly authorize the adapter in Morpho before it can manage their positions
* The adapter never holds user funds beyond the transaction scope
* All operations are executed on behalf of `msg.sender`, maintaining caller accountability

**Collateral Safety:**

* The adapter does not enforce collateralization ratios — these are handled by Morpho
* Users must ensure sufficient collateral before borrowing
* Withdrawals that would violate collateral requirements will revert at the Morpho level

**Access Control:**

* Inherits from OpenZeppelin `Ownable` for admin functions (if any)
* Core functions are permissionless — any authorized user can call them

***

## Integration Guide

### For AI Agents (MCP Integration)

AI agents interact with the adapter through MCP tools that wrap these functions:

**Example: Borrow USDL via MCP**

```typescript
await mcp.call("owl_supplyAndBorrow", {
  collateralToken: "0x...", // WBTC address
  collateralAmount: "100000000", // 1 WBTC (8 decimals)
  borrowAmountUSDC: "50000000000", // 50,000 USDC (6 decimals)
  marketParams: { /* Morpho market config */ }
});
```

**Example: Repay and Withdraw**

```typescript
await mcp.call("owl_repayAndWithdraw", {
  usdlAmountToRepay: "50000000000000000000000", // 50,000 USDL (18 decimals)
  collateralAmountToWithdraw: "100000000", // 1 WBTC
  marketParams: { /* Morpho market config */ }
});
```

### For Smart Contract Integrators

**Setup Authorization:**

```solidity
// User must authorize adapter before use
morpho.setAuthorization(adapterAddress, true);
```

**Direct Contract Call:**

```solidity
// Approve tokens
IERC20(wbtc).approve(adapterAddress, collateralAmount);

// Supply and borrow
adapter.supplyAndBorrowUSDL(
    wbtcAddress,
    1e8, // 1 WBTC
    50000e6, // 50,000 USDC
    marketParams
);
```

***

## MarketParams Reference

The `MarketParams` struct is defined by Morpho and contains:

| Field             | Type      | Description                              |
| ----------------- | --------- | ---------------------------------------- |
| `loanToken`       | `address` | The token being borrowed (USDC)          |
| `collateralToken` | `address` | The token used as collateral (WBTC/WETH) |
| `oracle`          | `address` | Price oracle for the market              |
| `irm`             | `address` | Interest rate model address              |
| `lltv`            | `uint256` | Liquidation Loan-to-Value ratio          |

These parameters define the specific Morpho lending market being used and must match an existing market configuration.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.greenowl.money/smart-contracts/contracts/owllendingadapter.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
