Skip to content

tuyakhov/aave-loop

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Aave Loop ⚡

Composable Solidity contracts for opening and closing leveraged Aave positions with Morpho flash loans and pluggable collateral adapters.

The current implementation focuses on looping a debt asset into Pendle Principal Tokens (PT), supplying the PT as collateral on Aave, and borrowing the debt asset back to settle the flash loan.

⚠️ Security note: this code is experimental and unaudited. Treat it as a prototype until it has full integration tests, invariant tests, deployment review, and an external audit.

What It Does 🧠

Aave Loop automates a common leveraged DeFi workflow:

  1. A user provides an initial amount of a debt asset, such as USDC or another Aave borrowable token.
  2. The contract optionally borrows extra liquidity from Morpho using a flash loan.
  3. The combined funds are converted into collateral through an adapter.
  4. The collateral is supplied to Aave on behalf of the user.
  5. The contract borrows the debt asset from Aave on behalf of the user to repay the flash loan.

The close flow reverses the position:

  1. The contract flash-borrows enough debt asset to repay the user's Aave variable debt.
  2. It repays the debt on Aave.
  3. It pulls the user's aTokens, withdraws the underlying collateral, and converts it back through the adapter.
  4. It returns the remaining debt asset to the user after flash loan repayment.

Core Idea 🔁

The project separates position orchestration from collateral-specific logic:

  • GenericLeverager owns the open and close lifecycle.
  • ICollateralAdapter defines a small interface for entering and exiting collateral.
  • PendleAdapter implements that interface for Pendle PT markets.

This keeps the main leverager contract generic enough to support additional strategies later, such as different Pendle markets, ERC-4626 vault shares, LP tokens, or other collateral wrappers.

Architecture 🏗️

User
  │
  ▼
GenericLeverager
  ├── Morpho flashLoan()
  ├── Aave supply() / borrow() / repay() / withdraw()
  └── CollateralAdapter
        └── PendleAdapter
              └── Pendle Router + Market

Contracts

Contract Purpose
src/core/GenericLeverager.sol Main position manager. Handles opening and closing positions, Morpho flash loan callbacks, and Aave interactions.
src/adapters/PendleAdapter.sol Converts the configured debt asset into Pendle PT collateral and converts PT collateral back to the debt asset.
src/core/interfaces/ICollateralAdapter.sol Adapter interface used by the leverager.
src/core/interfaces/IMorphoFlashLoan.sol Minimal Morpho flash loan interface.
src/core/utils/ERC20Recoverable.sol Owner-only token recovery helper for stuck ERC-20 balances.
script/Deployer.sol Foundry deployment script for the Pendle adapter and generic leverager.

Open Position Flow 🚀

userDebtIn + Morpho flashAmount
          │
          ▼
PendleAdapter.enter()
          │
          ▼
Pendle PT collateral
          │
          ▼
Aave supply(collateral, user)
          │
          ▼
Aave borrow(debtAsset, user)
          │
          ▼
Repay Morpho flash loan

Call:

openPosition(uint256 userDebtIn, uint256 flashAmount, bytes calldata adapterData)

adapterData currently contains the minimum Pendle output:

abi.encode(uint256 minOutput)

Close Position Flow 🔓

Morpho flash loan debtAsset
          │
          ▼
Aave repay(user variable debt)
          │
          ▼
Transfer user's aTokens to leverager
          │
          ▼
Aave withdraw(collateral)
          │
          ▼
PendleAdapter.exit()
          │
          ▼
Return surplus debtAsset to user

Call:

closePosition(uint256 collateralAmount, bytes calldata adapterData)

The user must approve the leverager to transfer the relevant Aave aToken before closing.

Pendle Adapter 🌊

PendleAdapter supports two exit paths:

  • Before market expiry: swapExactPtForToken
  • After market expiry: exitPostExpToToken

Both enter and exit require a non-zero minOutput encoded in adapterData, giving callers a basic slippage protection hook through Pendle router parameters.

Tech Stack 🛠️

  • Solidity ^0.8.24
  • Foundry
  • Aave V3 core interfaces
  • Morpho Blue flash loan callback interface
  • Pendle V2 router and market interfaces
  • OpenZeppelin contracts

Getting Started ⚙️

Install dependencies:

forge install

Build:

forge build

Run tests:

forge test

Format contracts:

forge fmt

Generate a gas snapshot:

forge snapshot

Deployment 🚢

script/Deployer.sol expects these environment variables:

AAVE_POOL=
MORPHO_FLASHLOAN=
DEBT_ASSET=
PENDLE_PT=
PENDLE_MARKET=
PENDLE_ROUTER=
AAVE_POOL_DATA_PROVIDER=

Example deployment command:

forge script script/Deployer.sol:DeployGenericLeverager \
  --rpc-url <RPC_URL> \
  --private-key <PRIVATE_KEY> \
  --broadcast

For Tenderly-style verification, configure the values in foundry.toml and provide the relevant API keys in your environment.

Current Test Coverage ✅

The test suite currently covers:

  • Leverager constructor wiring
  • Opening positions with and without flash loans
  • Closing positions through mocked Aave and Morpho components
  • Pendle adapter enter and exit behavior
  • Expired Pendle market exit path
  • Invalid adapter slippage data

Run everything with:

forge test -vvv

Important Implementation Notes 🧩

  • GenericLeverager borrows Aave variable debt using interest rate mode 2.
  • The close path calculates the user's current variable debt through AaveProtocolDataProvider.
  • The leverager must be approved to transfer the user's aTokens before closing a position.
  • Adapter integrations are responsible for handling asset conversion and slippage parameters.
  • The current adapter expects Pendle router outputs to be sent back to the caller.

Suggested Next Steps 🧪

  • Add fork tests against the intended deployment network.
  • Add health factor and liquidation-risk checks before opening positions.
  • Add more explicit slippage, deadline, and receiver validation.
  • Add events for open and close operations.
  • Add integration tests for real Pendle markets.
  • Review allowance patterns and token recovery permissions.
  • Run a professional smart contract audit before production use.

License

MIT

About

Opening and closing leveraged Aave positions with Morpho flash loans

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors